簡體   English   中英

將列表與輸入進行比較

[英]compare list with input

def calculate():
    operator = input("What operator do you wanna use(*,/,+,-)? ")
    possible_op = ["*", "+", "-", "/"]
    if not operator == possible_op:
        calculate()
    number_1 = float(input("What is your first number? "))
    if number_1 != float:
            calculate()
    number_2 = float(input("What is your second number? "))
    if number_2 != float:
            calculate()
    
    if operator == "+":
        print(number_1 + number_2) 
    elif operator == "-":
        print(number_1 - number_2) 
    elif operator == "*":
        print(number_1 *  number_2) 
    elif operator == "/":
        print(number_1 / number_2) 
    else:
        print("Wrong Input")
        calculate()

    again()

def again():
    print("Do you wanna calculate again? ")
    answer = input("(Y/N) ").lower()
    if answer == "y":
        calculate()
    elif answer == "n":
        exit
    else:
        print("Wrong Input")
        again()

calculate()

有誰知道為什么我的代碼總是一次又一次地詢問操作員問題,即使有一個正確的操作員? 我是否必須更改列表的名稱並比較輸入或

這段代碼有很多問題,但你已經設法使用你所知道的並且處於正確的軌道上,所以我現在只對它進行審查,而不是給你一個解決方案。

大多數情況下,我建議讓您的計算函數保持簡單並在其他地方處理循環(而不是遞歸)。

def calculate():
    operator = input("What operator do you wanna use(*,/,+,-)? ")
    possible_op = ["*", "+", "-", "/"]
    if not operator == possible_op:  # this will never be true because operator is a string, use `not in`
        calculate()  # you probably don't want to run calculate again, maybe return early
    number_1 = float(input("What is your first number? "))
    if number_1 != float:  # number_1 is a float it's not the `float` type so always True
            calculate()  # return
    number_2 = float(input("What is your second number? "))
    if number_2 != float:  # same as number_1 above
            calculate()  # return
    
    if operator == "+":  # this block is good, simple and to the point
        print(number_1 + number_2) 
    elif operator == "-":
        print(number_1 - number_2) 
    elif operator == "*":
        print(number_1 *  number_2) 
    elif operator == "/":
        print(number_1 / number_2) 
    else:
        print("Wrong Input")  # here you also want to retry
        calculate()  # but not by recursing

    again()  # and definitely not call again

def again():
    print("Do you wanna calculate again? ")
    answer = input("(Y/N) ").lower()
    if answer == "y":
        calculate()
    elif answer == "n":
        exit  # what is this exit ?
    else:
        print("Wrong Input")
        again()  # also don't recurse this, loop if you want

calculate()

暫無
暫無

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

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