python - 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
解决方案
为了消除int(find)
对每个 if 语句执行的开销,只需在初始用户输入上实现所需的条件,如下所示:
find = int(input(": "))
然后每个 if 语句都可以像这样检查值:
if find == 1:
#run this scope
等等等等……
推荐阅读
- javascript - 递归角度 div 模板
- r - 基于正则表达式模式在列表元素之间连接
- node.js - React Socket.IO-Client 与 NodeJS (express) WebSockets 不兼容?
- mysql - 在 where 子句中限制结果集会提高 group by 和 having 的性能吗?
- c - C中的函数对变量求和
- r - 将xml文件转换为R中的数据框并回溯源
- linux - 在 Linux 上卸载 NuGet 包
- c++ - 如何在巨大的文本文件中对整数进行排序?
- javascript - Bootstrap:从 datetimepicker 中隐藏 glyphicon-time
- matlab - 查找图像中物体的直径