【问题标题】:If/Elif/Else Statement in Python - Else Statement prints even though the if constraints are being metPython 中的 If/Elif/Else 语句 - 即使满足 if 约​​束,也会打印 Else 语句
【发布时间】:2020-06-07 00:47:10
【问题描述】:

我在编程的第一个月就遇到了我正在开发的应用程序的问题。我确信对于有经验的人来说这相当简单,但我不知道如何在没有语法错误的情况下修复它。这是我的代码(输出错误见下文)

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()

所以输入功能有效,但无论我输入什么数字(1、2 或 3),else 命令下的“打印”总是会打印。例如,输出如下:

你想找到什么? 1 = 坡度,2 = 高海拔,3 = 低海拔 : 1 选择与您要查找的内容相对应的数字 插入更高的海拔:

因此,在此之后我有更多代码创建更高海拔的提示,但我只想知道如何确保它在运行后不打印 else 语句。我还在为我的 IDE 使用 Visual Studio Code。

来自非常缺乏经验的编码人员,在此先感谢您的帮助!

更新:在修改和使用其他人的输入后,这就是我所拥有的:

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()

这一切都说得通,把它变成输出(在我插入 if 语句的相应数字之一之后):

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

不确定这是如何发生的,或者为什么更改开头的“find”会产生这个输出。请帮帮我!谢谢

【问题讨论】:

  • 条件不成立。想想input 返回什么类型,1 是什么类型。
  • 您输入了错误的值。试试int(find) == 1
  • type(find)str。您将strint 进行比较。 strint 不相等。
  • 谢谢你们!我会试一试,让你知道

标签: python if-statement printing output


【解决方案1】:

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

 find = int(input(": "))

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

 if find == 1:
   #run this scope

等等等等……

【讨论】:

  • 完全有道理,但请参阅我对我的问题的更新。输入后输出现在不起作用,我不知道为什么。
  • 所以在更新的代码中,您正在调用 3 个可能属于同一类或来自未在此范围内定义的另一个文件的其他函数..您必须查看定义 find_scope() 的位置,它是如何定义的以及如何调用它(您通常已经这样做了)。或者这些函数代表什么,因为这是范围的要点..
  • 好的,我会继续努力,看看能否让它运行起来,并通知您。感谢您的帮助,我仍在努力解决这个问题
  • 也许你也可以在这里添加其他部分,看看社区是否可以看到错误所在:)
  • 我明白了!我在定义函数 find_slope() 之前调用了 what_to_find()。一旦我将函数调用 what_to_find() 移到它下面,它就能够找到 find_slope() 并运行!感谢您的帮助!