gpt4 book ai didi

python - IF 语句和输入

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:03 25 4
gpt4 key购买 nike

我只是在练习基本的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com