IF语句和输入

时间:2018-10-21 04:06:15

标签: python

我只是在练习基本的python,并尝试构建仅具有加,减和乘函数的计算器。运行代码并输入1、2或3时,没有输出。

这是我的代码:

question1 = input("Enter 1 to add, 2 to substract, or 3 to multiply: ")
if question1 == 1:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result)
elif question1 == 2:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result)
elif question1 == 3:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    result = float(num1) + float(num2)
    print(result))

3 个答案:

答案 0 :(得分:3)

在Python3中使用input()进行输入时,您将得到一个字符串。

使用以下命令进行测试:

foo = input()
print(type(foo))

无论输入内容如何,​​结果均为<class 'str'>(表示foo的类型为字符串)。如果要将输入用作整数,则必须将类型更改为int(整数)。

您应该使用int(input())来获取如下所示的整数:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))

您还必须更改每个if-else块中的数字输入:

if question1 == 1:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 + num2
    print(result)

或者,您可以在要计算时进行更改:

result = int(num1) + int(num2)

答案 1 :(得分:1)

您的旅途顺利!如评论中所述,您的所有语句都是False,因为input()本身返回的字符串类型永远不会等于整数。

您只需更改代码的所有input()即可将其转换为要存储的int值。下面是一个示例:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))

答案 2 :(得分:1)

您需要将输入转换为整数。尝试以下代码:

question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
if question1 == 1:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 + num2
    print(result)
elif question1 == 2:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 - num2
    print(result)
elif question1 == 3:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 * num2
    print(result)