【问题标题】:Why doesn't IF seem to work inside a WHILE loop? (Python 3.4) [duplicate]为什么 IF 似乎在 WHILE 循环中不起作用? (Python 3.4)[重复]
【发布时间】:2015-01-28 19:27:44
【问题描述】:

我正在使用 python 编写计算器的代码。

loop = 1
while loop == 1:    #loop calculator while loop is TRUE
    print   ("""Options:
        Addition       1)
        Subtraction    2)
        Multiplication 3)
        Division       4)
        Quit           5)   
        Reset Sum      6) """)      #display calculator's options
    (' ')   #spacer
    choice = input("option: ")  #get user input for calculator options
#----------------------------------------------------------------------------Addition
    if choice == 1:     #check if user wants to add
        print (' ') #spacer
        print ('Addition Loaded!')  #tell the user they are adding
        print (' ') #spacer
        add1 = int(input('Base Number'))    #get value for add1
        sum = int(input('Number ta add'))   #get value for sum
        sum = add1 + sum    #make sum equal the sum of add1 and sum
        print (str(sum))    #print sum
        addloop = 1     #set addloop to TRUE
        while addloop == 1:     #continue addition while addloop = TRUE
            add1 = int(input('Additional number to add'))   #get value for add1
            if add1 == 0:   #check if add1 equals zero
                print (' ') #spacer
            sum = add1 + sum    #make sum equal the sum of add1 and sum
            if add1 != 0:   #check if add1 is not equal to 0
                print (str(sum))    #print sum
            if add1 == 0:   #check if add1 is equal to 0
                print ('Total: ',)  #print prefix
                print (str(sum))    #print sum
                addloop = 0 #set addloop to FALSE

在此处列出的加法部分下方,还有其他用于减法、乘法等的部分,它们使用 ELIF 而不是 IF(应该是这样吗?)。问题是,当用户为计算器选择一个选项(加法、减法...)时,它反而会循环回到 while 循环,而不会通过任何 IF 或 ELIF 语句。 IF 语句在 WHILE 循环中不起作用吗?

【问题讨论】:

  • 源代码中的每一行都不需要注释,尤其是注释只是重复代码的时候
  • 这个问题可能很难弄清楚...print(choice) 似乎显示一个整数...但print(repr(choice)) 显示它实际上是一个字符串(它永远不等于整数)。
  • @Jasper 我对每一行都进行了评论,以养成做 cmets 的习惯。我不打算在以后评论不必要的行,只是为了帮助我早日学会这样做。

标签: python if-statement while-loop calculator


【解决方案1】:

这是你的问题:

choice = input("option: ")

在 Python 3 下,这会将 字符串 放入 choice。你需要一个整数:

choice = int(input("option: "))

如果用户键入的不是整数,这将引发ValueError。您可以使用try/except ValueError 块来捕捉它,或者您可以保留问题中出现的choice 行并将所有比较更改为如下所示:

if choice == "1":  # compare to a string instead of an integer

【讨论】:

  • 简单的演示方法:运行解释器 (python3) 并输入 1 == "1"。输出为False
猜你喜欢
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2020-01-08
相关资源
最近更新 更多