gpt4 book ai didi

python - 一行,三个变量

转载 作者:太空狗 更新时间:2023-10-29 22:24:13 26 4
gpt4 key购买 nike

我在这里试图用 python 制作一个简单的计算器,我想知道是否可以在命令运行时将前 3 行合并为一行。我的意思是;我不必按 Enter 键来键入下一个数字/运算符,而是按空格键(在输入部分)。

while True:
import operator

num1 = int(input("Whats the first number:"))
oper = input("Which operator would you like to use: (+,-,/,*,**,^) :")
num2 = int(input("Whats the second number:"))


if oper == "+":
x = operator.add

elif oper == "-":
x = operator.sub

elif oper == "*":
x = operator.mul

elif oper == "/":
x = operator.__truediv__
elif oper == "**":
x = operator.pow
elif oper == "^":
x = operator.xor

else:
print("invalid input")

print(num1,oper,num2,"=",x(num1,num2))

最佳答案

可以使用Python字符串的split方法来完成。请注意,此代码取决于输入的三个对象,以空格分隔。如果输入了更多或更少或忘记了空格,或者“数字”实际上不是整数,则会出现错误。

print("Enter a number, a space, an operator, a space, and another number.")
num1str, oper, num2str = input().split()
num1, num2 = int(num1str), int(num2str)

关于python - 一行,三个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612268/

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