首页 > 解决方案 > If/Elif/Else Statement in Python - Else Statement prints even though the if constraints are being met

问题描述

I am in my first month of programming and I have encountered an issue in an app I'm developing. I'm sure it's fairly simple for someone experienced but I don't know how to fix it without a syntax error. Here's my code (see below for output error)

def what_to_find():
    find = (input(": "))
    if find == int(1):
        find_slope()
    elif find == int(2):
        find_elevation1()
    elif find == int(3):
        find_elevation2()
    else:
        print("Choose a number corresponding to what you want to find")


what_to_find()

So the input function works, but regardless of what number I put in (either 1, 2, or 3), the 'print' under the else command always prints. Here is what the output is for example:

What are you trying to find? 1 = Slope, 2 = Higher Elevation, 3 = Lower Elevation : 1 Choose a number corresponding to what you want to find Insert higher elevation:

So I have more code after this which creates the prompt for the higher elevation, but I just want to know how to make sure it doesn't print the else statement once it runs. Also I am using Visual Studio Code for my IDE.

From a very inexperienced coder, thanks in advance for your help!

UPDATE: After revising and using input from others, this is what I have:

def what_to_find():
    find = int(input(": "))
    if find == 1:
        find_slope()
    elif find == 2:
        find_elevation1()
    elif find == 3:
        find_elevation2()
    else:
        print("Choose a number corresponding to what you want to find")


what_to_find()

Which all made sense, put this becomes the output (after I plug in one of the corresponding numbers of the if statement):

What are you trying to find?
1 = Slope, 2 = Higher Elevation, 3 = Lower Elevation
: 1
Traceback (most recent call last):
  File "gcalc.py", line 24, in <module>
    what_to_find()
  File "gcalc.py", line 15, in what_to_find
    find_slope()
NameError: name 'find_slope' is not defined

Not sure how this occurred or why the change to the beginning 'find' made this output. Please help me out! Thanks

标签: pythonif-statementprintingoutput

解决方案


为了消除int(find)对每个 if 语句执行的开销,只需在初始用户输入上实现所需的条件,如下所示:

 find = int(input(": "))

然后每个 if 语句都可以像这样检查值:

 if find == 1:
   #run this scope

等等等等……


推荐阅读