Python While While-两个数字之间的加法

时间:2016-03-04 02:45:03

标签: python loops for-loop while-loop addition

基本上,如果用户输入2,12,则输出应为2 + 3 + 4 + 5 + 6 + 7 + 9 + 10 + 11 + 12.

num1 = int(input("Please enter a number between 1 and 10: "))
num2 = int(input("Please enter a number between 11 and 20: "))
addition = num1 + num2
print (addition)
sum = 0
count = 1

while (count <= num1):
   sum = sum + 1
   count = count + 1


print ("Your total price comes to ", total_price)

2 个答案:

答案 0 :(得分:0)

请尝试以下代码:

num1 = int(input("Please enter a number between 1 and 10: "))
num2 = int(input("Please enter a number between 11 and 20: "))
the_sum = 0

start = num1
end = num2 + 1

m = start
while m  < end:
    the_sum += m
    m += 1

print ("Your total price comes to ", the_sum)

答案 1 :(得分:0)

你有几个问题......包括你实际上没有做任何事情。你真正做的只是做addition行并打印它是什么。当然,您应该从for循环开始,循环遍历用户设置的限制:

for i in range(num1, (num2)+1):

现在要在两者之间添加数字并跟踪当前总和,让我们创建两个变量来跟踪:

current_sum = 0
number = num1
for i in range(num1, (num2)+1):

现在将number添加到current_score并向number添加一个:

current_sum = 0
number = num1
for i in range(num1, (num2)+1):
    current_score += number
    number += 1

然后最后打印结果:

current_sum = 0
number = num1
for i in range(num1, (num2)+1):
    current_score += number
    number += 1
print current_sum