簡體   English   中英

在用戶輸入后重復 while 循環

[英]Repeating a while loop after user input

我需要創建一個程序,將 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,如果輸入為是,將重復該程序。 我花了很長時間嘗試將以下內容放在不同的位置:

while again == "Y" or again == "y":
again = input("Would you like to run this again? (Y/N)")

但是我一直無法讓它工作,或者在最好的情況下我讓它打印數字的總數並詢問我是否想再次運行它但是當我輸入 yes 時它又回到詢問我是否想運行再說一遍。

我把另一個 while 語句放在哪里?

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()

如果要求再次運行程序的 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 (否,或其他非Yy答案),程序將停止。 它不會永遠要求。

檢查您的求和是否有封閉形式總是好的。 這個系列類似於正整數,它有一個,所以沒有理由迭代偶數。

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

您應該在開頭添加 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM