在Python中,你可以通过以下几种方法输入一行数字并求和:
1. 使用`input()`函数获取用户输入,然后使用`split()`方法将输入的字符串分割成列表,最后使用`sum()`函数求和。
获取一行输入,例如 "1 2 3 4 5"
input_str = input("请输入一行数字,用空格分隔:")
将输入的字符串分割成列表
numbers = list(map(int, input_str.split()))
使用sum函数求和
total = sum(numbers)
输出结果
print("数字之和为:", total)
2. 使用`eval()`函数直接计算输入字符串的结果。
获取一行输入,例如 "1 + 2 + 3 + 4 + 5"
input_str = input("请输入一行数字,用加号分隔:")
使用eval函数计算结果
total = eval(input_str)
输出结果
print("数字之和为:", total)
请注意,使用`eval()`函数可能存在安全风险,因为它会执行输入的字符串作为代码,所以请确保输入是可信的。
以上两种方法都可以实现在Python中输入一行数字并求和。您可以根据自己的需要选择合适的方法