【问题标题】:If statement not executing. Python如果语句未执行。 Python
【发布时间】: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 语句。
  • strintfloat 等类型不会修改其输入。他们返回(可能)新值。 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


【解决方案1】:

您遇到类型转换问题。因此,当您从用户那里获取输入时,所有 userInput 都是 str 而不是 int,因此在进行进一步的计算器操作之前,您需要将其转换为 userInput = int(userInput)。 此外,您需要将 float 转换分配给这样的变量 variableA = float(variableA)variableB = float(variableB) 否则您的加/减/除/乘等将不会执行预期的操作。

例如添加将进行连接,即 '2' + '4' = 24 而不是 2 + 4 =6.0

import operator as op
print("Greetings user, welcome to the calculator program.
We offer a list of functions:")
print("1. Add
2. Subtract
3. Multiply
4. Divide
5. Modulus
6. 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():
        variableA = float(variableA)  # <-- fix this line
        break
    else:
        print("Incorrect input. Please try again.")
        continue

while True:
    variableB = input("Enter the second value: ")
    if variableB.isdigit():
        variableB = float(variableB)  # <-- fix this line
        break
    else:
        print("Incorrect input. Please try again.")
        continue

userInput = int(userInput)  # <-- fix this line
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")

【讨论】:

  • 我现在明白了,它真的只是我没有包括的那条简单的线。非常感谢您的帮助!
  • @DepletedMoney 很高兴有帮助,祝你好运
【解决方案2】:

如果用户输入应该是 int,请尽早转换并快速失败。

while True:
    userInput = input(...)
    try:
        userInput = int(userInput)
    except ValueError:
        print("Not an integer, try again")
        continue
    if userInput in range(1, 7):
        break
    print("Number out of range, try again")

和类似的操作数

while True:
    variableA = input("Enter the first value: ")
    try:
        variableA = float(variableA)
        break
    except ValueError:
        print("not a float")

不过,没有理由将菜单选项转换为整数。你可以简单地写

while True:
    userInput = input(...)
    if userInput in "123456":  # ... in ["1", "2", "3", "4", "5", "6"]
        break
    print("Invalid choice, try again")

【讨论】:

  • 我现在明白你的意思了,我刚刚发现默认情况下它是一个字符串值!无论如何,谢谢你教我一个新东西。队友的欢呼声!
猜你喜欢
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多