簡體   English   中英

為什么IF在WHILE循環中似乎不起作用? (Python 3.4)

[英]Why doesn't IF seem to work inside a WHILE loop? (Python 3.4)

我正在使用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循環中不起作用嗎?

這是您的問題:

choice = input("option: ")

在Python 3下,這會將字符串放入choice 您需要一個整數:

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

如果用戶鍵入的不是整數,則將引發ValueError 您可以使用try / except ValueErrorexcept ValueError ,也可以保留問題中顯示的choice行,並將所有比較更改為如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM