python-3.x 为什么它不工作我正在试着做一个简单的计算器

toe95027  于 2022-12-05  发布在  Python
关注(0)|答案(4)|浏览(119)
def add(a, b):
    return a + b

print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == 1:
    print(a, "+", b, "=", add(a, b))

我不知道它为什么不想

qcuzuvrc

qcuzuvrc1#

您需要将select转换为int

def add(a, b):
    return a + b

print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2"))

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == 1:
    print(a, "+", b, "=", add(a, b))
wbgh16ku

wbgh16ku2#

You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:

def add(a, b):
    return a + b

print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2: "))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
    print(f"{a} + {b} = {add(a, b)}")

Output:

choose 1 to add and 2 to subtract
enter choice 1/2: 1
enter 1st nunber: 21
enter 2nd number: 3
21.0 + 3.0 = 24.0
jhdbpxl9

jhdbpxl93#

input返回一个字符串,但在if select == 1行中,您将其与int进行比较。对此有几种解决方案,但我将采用的解决方案是只使用字符串,即if select == "1"12是任意值,因此实际上没有必要将它们转换为数字,您可以使用ab轻松地实现相同的目标。
你可以做的另一件有用的事情是验证用户输入。

while select not in ["1", "2"]:
    print(f"you entered {select}, which is not a valid option")
    select = input("enter choice 1/2")

这将继续要求用户选择一个选项,直到他们输入一个有效的选项,并且还具有额外的好处,帮助您捕获代码中的错误,如intstr问题。

a0x5cqrl

a0x5cqrl4#

正如其他人提到的,由于input返回一个str,它应该与相同类型的对象进行比较。只需将第10行的1改为str(1)就可以解决这个问题。

def add(a, b):
    return a + b

print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == str(1):
    print(a, "+", b, "=", add(a, b))

相关问题