Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在用户输入后重复while循环_Python_Python 3.x_While Loop - Fatal编程技术网

Python 在用户输入后重复while循环

Python 在用户输入后重复while循环,python,python-3.x,while-loop,Python,Python 3.x,While Loop,我需要创建一个程序,对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到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循环,并在结尾询问用户。像这样:

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
num=2
总数=0
con_1=真
而con_1:

while num如果要求再次运行程序的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()
def main():
再次='y'
再一次。lower()==“y”:
num=2
总数=0

而num检查求和是否为闭合形式总是好的。这个系列与类似,它有一个,所以没有理由迭代偶数

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
输出
def sum_even(stop):
    return (stop // 2) * (stop // 2 + 1)

print(sum_even(100)) # 2550
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