python - IF 语句和输入

标签 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))

最佳答案

当您使用 input() 获得一些输入时在 Python3 中,你得到一个字符串。

用下面的方法测试它:

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 中的数字输入 block 也:

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

或者,您可以在需要计算时更改它:

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
...
result = int(num1) + int(num2)

关于python - IF 语句和输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912034/

相关文章:

python - 删除numpy数组的空维度

python - 我如何以编程方式注销用户?[Django]

python - 如何从多个元组中添加值?

python - 我可以将 xvfb 与 AWS Lambda 一起使用吗?

python - Python 中的“无写”变量

Python分割文本

python - 在字符串变量的情况下,如何在没有显式引号的情况下制作准备好的语句

python - 如何在 Python 的 for 循环中检索剩余的项目?

python - 捕获行直到第一次响应 python 中的事件

python - 如何根据多列中的单个值从多索引中进行选择?