提问人:unleasehed 提问时间:11/10/2023 更新时间:11/10/2023 访问量:47
如何使用 for 循环计算 2 个输入的总和
How to calculate the sum of 2 inputs using a for loop
问:
我要求用户输入 2 个数字(x 和 y),我需要计算从 x 到 y 的数字之和,并使用 for 循环将最终值存储在变量中。
我所拥有的输出是
请输入x的值:3
请输入 y: 4 的值
它以没有求和和错误消息结束。
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
if x.isnumeric() and y.isnumeric():
num1 = int(x)
num2 = int(y)
else:
print("One or more of your inputs are not numeric!")
for sum_of_numbers in (num1, num2):
totalsum=num1
if totalsum <= num2:
totalsum=num1+1
else:
print("The sum of numbers between " + str(num1) + " and " + str(num2) + " is " + str(totalsum))
答:
1赞
Tanishq Chaudhary
11/10/2023
#1
您想要用于遍历从 到 的数字。
对于 for 循环的每次迭代,将来自范围的电流添加到我们所做的注释中,而不是 ,因为范围不包括第二个参数。range
num1
num2
num
totalsum
num2 + 1
num2
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
if x.isnumeric() and y.isnumeric():
num1 = int(x)
num2 = int(y)
totalsum = 0
for num in range(num1, num2 + 1):
totalsum += num
print(
"The sum of numbers between "
+ str(num1)
+ " and "
+ str(num2)
+ " is "
+ str(totalsum)
)
else:
print("One or more of your inputs are not numeric!")
解决这个问题的一个更好的方法是直接在 python 中使用,如下图所示。sum
totalsum = sum(range(num1, num2 + 1))
更好的方法是直接使用数学公式。x 和 y 之间的数字之和是 y 之前的数字之和减去 x 之前的数字之和(但不包括 x)。以下代码显示了相同的内容。
totalsum = num2 * (num2 + 1) // 2 - (num1 - 1) * num1 // 2
0赞
Codist
11/10/2023
#2
使用循环来计算总数不是最佳选择,但这是要求,因此:
x = input("Input value for X: ")
y = input("Input value for Y: ")
try:
total = 0
for n in range(int(x), int(y)): # add 1 to the 2nd argument if range is to be inclusive
total += n
print(f"The sum of numbers between {x} and {y} is {total}")
except ValueError:
print("One or more of your inputs are not numeric!")
评论