首页 > 解决方案 > 如何在python输入中添加多个元素?

问题描述

x1 = 1
x2 = 2
ans=int(input(x1, "+", x2, "="))

if (ans==(x1+x2)):
   print("Correct")
else:
   print("Incorrect")

我有这段代码,它应该告诉用户输入一个他们认为是 x1 + x2 正确答案的值,但是当我运行代码时,输​​入部分给了我一个错误。有什么我做错了吗?

标签: pythonpython-3.x

解决方案


输入只需要 1 个参数。通过使用逗号,您传递了 4。因此,只需使用“+”运算符而不是“,”将它们转换为单个字符串。

x1 = 1
x2 = 2

ans = int(input(str(x1) + "+" + str(x2) + "="))
# As string concatenation is an expensive operation, the following
# might be an optimal approach for acheiving the same result. 

ans = int(input("".join(str(x1), "+", str(x2), "=")))
# But in this scenario, it doesn't matter because the number of strings 
# being concatenated and the length of them are both small. So, it won't 
# make much difference. 

# Also now, Python3.5+ supports `f-strings`. So, you can do something like
ans = int(input(f"{x1} + {x2} = "))

if (ans == (x1 + x2)):
   print("Correct")
else:
   print("Incorrect")

推荐阅读