python - 如何在python输入中添加多个元素?
问题描述
x1 = 1
x2 = 2
ans=int(input(x1, "+", x2, "="))
if (ans==(x1+x2)):
print("Correct")
else:
print("Incorrect")
我有这段代码,它应该告诉用户输入一个他们认为是 x1 + x2 正确答案的值,但是当我运行代码时,输入部分给了我一个错误。有什么我做错了吗?
解决方案
输入只需要 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")
推荐阅读
- shell - stty:标准输入:设备的 ioctl 不合适。从 shell 脚本运行 Perl 脚本
- ruby-on-rails - [RAILS]:云显示照片1
- angular - [Angular][单元测试] this.isDateInstance 不是函数
- c# - 将值传递给另一个 ViewModel
- javascript - Node.js - 重新创建 navigator.onLine
- python - 在一个主列和另一个可选列之间选择 Pandas 中的布尔值
- sql-server - 通过 SQL Server 2012 中的透明数据加密 (TDE) 实现强大的安全性?
- python - 根据特定条件删除重复项
- python - 在python中以多行方式编写文本
- android - 从 Worker 更改 Db 时 LiveData 未更新