我需要创建一个程序,该程序求2到100之间的偶数之和。我编写的部分如下:
def main():
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
main()
下一部分是我应该在当前的while循环中添加一个while循环,该循环要求输入Y / N,如果输入为yes,则将重复该程序。我花了很长时间尝试将以下内容放置在不同的位置:
while again == "Y" or again == "y":
again = input("Would you like to run this again? (Y/N)")
但是我无法使其正常工作,或者在最佳情况下,我无法获得它来打印数字的总和并询问是否要再次运行它,但是当我键入是时,它又回到询问我是否想要再次运行它。
我将另一个while语句放在哪里?
答案 0 :(得分:1)
def sum_evens():
active = True
while active:
sum_of_evens = 0
for even in range(2, 101, 2):
sum_of_evens += even
print('Sum of the evens is:', sum_of_evens)
while True:
prompt = input('Type "Y" to start again or "N" to quit...\n')
if prompt.lower() == 'y': # doesn't matter if input is caps or not
break
elif prompt.lower() == 'n':
active = False
break
else:
print('You must input a valid option!')
continue
sum_evens()
答案 1 :(得分:1)
检查汇总是否为封闭形式总是很好的。该序列与sum of positive integers类似,它具有一个序列,因此没有理由遍历偶数。
def sum_even(stop):
return (stop // 2) * (stop // 2 + 1)
print(sum_even(100)) # 2550
要将其置于while循环中,请在函数调用后要求用户输入并中断输入是否为'y'
。
while True:
stop = int(input('Sum even up to... '))
print(sum_even(stop))
if input('Type Y/y to run again? ').lower() != 'y':
break
Sum even up to... 100
2550
Type Y/y to run again? y
Sum even up to... 50
650
Type Y/y to run again? n
答案 2 :(得分:0)
您应该在开头添加while循环,然后在末尾询问用户。像这样:
num = 2
total = 0
con_1 = True
while con_1:
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
ask = str(input("Do you want to run this program again(Y/n)?:"))
if ask == "Y" or ask == "y":
con_1 = True
elif ask == "N" or ask == "n":
con_1 = False
else:
print("Your input is out of bounds.")
break
答案 3 :(得分:0)
我的while循环要求再次运行程序,而不必在计算总和的循环内,那么以下应该回答您的约束:
def main():
again = 'y'
while again.lower() == 'y':
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
again = input("Do you want to run this program again[Y/n]?")
main()
请注意,如果您回答N
(否,或者不是Y
或y
的其他内容),程序将停止。它不会永远问。