【发布时间】:2022-12-05 23:02:20
【问题描述】:
我还是编程新手,我想用 python 做一个简单的计算器。但是,我的代码只能达到这一点:
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
float(variableA)
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
float(variableB)
break
else:
print("Incorrect input. Please try again.")
continue
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
不确定为什么在用户输入所有正确内容后我的 if 语句没有执行。我主要关注错误处理部分,在一切顺利之后,if 语句就不再执行了。可能有一个简单的错误,但即使我也不明白这里发生了什么。
【问题讨论】:
-
您有六个
if语句。 -
str、int和float等类型不会修改其输入。他们返回(可能)新值。userInput是总是代码中的str值。如果你想把它转换成int,你需要说一些userInput = int(userInput)。请记住,如果无法将输入转换为int,例如int('foo'),int可能会引发ValueError。 -
@chepner 我试图将 userInput 转换为 int,因为它不会在 range() 中得到验证。我很清楚更好的错误处理恶作剧,但也许我想先了解我的编码。
-
@jarmod 我不确定你的意思。我确实有 6 个“如果”,但它们用于有条件地触发每个功能。我必须在这里做什么?
-
关键是,
str(userInput)没用,原因有二:userInput是已经一个字符串(在上一行调用int(userInput)并没有改变它),如果它不是一个字符串,您不会在任何地方保存新创建的字符串。稍后在您的代码中,userInput == 1为 false,因为userInput是字符串而'1' != 1。
标签: python if-statement calculator