1

昨天我开始学习 Python,到目前为止我很享受它的简单性。今天,我尝试创建一个可以加、减、乘、除和取模的简单计算器。虽然它工作得非常好,但每当程序询问用户是否希望在第二次尝试后再试一次时,就会出现“什么?再试一次”这一行。出现,仅当用户对问题“再试一次?”给出的答案不在 noList 或 yesList 中时才会出现。对不起,如果这些都没有意义,但我会把我的代码放在下面。

functionList = ["add", "subtract", "multiply", "divide", "mod"]
yesList = ["yes", "yeah", "yup", "y"]
noList = ["no", "nope", "nah", "n"]

print("Welcome to Bryan's Calculator!")

def calculator():
whatFunction = input("What math function do you want to use (add/subtract/multiply/divide/mod)? ")
if whatFunction == "add":
    numAddOne = float(input("What is your first number? "))
    numAddTwo = float(input("What is your second number? "))
    answerAdd = numAddOne + numAddTwo
    print(str(answerAdd) + " is the answer!")
if whatFunction == "subtract":
    numSubtractOne = float(input("What is your first number? "))
    numSubtractTwo = float(input("What is your second number? "))
    answerSubtract = numSubtractOne - numSubtractTwo
    print(str(answerSubtract) + " is your answer!")
if whatFunction == "multiply":
    numMultiplyOne = float(input("What is your first number? "))
    numMultiplyTwo = float(input("What is your second number? "))
    answerMultiply = numMultiplyOne * numMultiplyTwo
    print(str(answerMultiply) + " is your answer!")
if whatFunction == "divide":
    numDivideOne = float(input("What is your dividend? "))
    numDivideTwo = float(input("What is your divisor? "))
    answerDivide = numDivideOne / numDivideTwo
    print(str(answerDivide) + " is your answer!")
if whatFunction == "mod":
    numModOne = float(input("What is your dividend? "))
    numModTwo = float(input("What is your divisor? "))
    answerMod = numModOne % numModTwo
    print(str(answerMod) + " is your remainder!")
elif whatFunction not in functionList:
    print("What? Try again.")
    calculator()

def askTryAgain():
tryAgain = input("Try again? ")
if tryAgain in yesList:
    calculator()
if tryAgain in noList:
    print("Thanks for using my calculator!")
    exit()
if tryAgain not in yesList or noList:
    print("What? Try again")
    askTryAgain()
calculator()
askTryAgain()
4

0 回答 0