簡體   English   中英

有沒有辦法從用戶使用while循環輸入的數字中找到偶數和奇數?

[英]Is there way to find the even sum and odd sum from the numbers inputted by the user using a while loop?

我是 python 的新手,我剛剛學習了循環。 我正在嘗試編寫一個程序,該程序讀取六個整數,然后使用 while 循環找到偶數和奇數的總和。 我不確定在這種情況下如何使用 while 循環。 這是我開始的:

print('Please enter 6 integers:')
n_1=int(input('>',))
n_2=int(input('>',))
n_3=int(input('>',))
n_4=int(input('>',))
n_5=int(input('>',))
n_6=int(input('>',))
Even_sum = 0
Odd_sum = 0
while

您可以使用 while 循環來保持輸入 n 次(在您的示例中為 6 次),而不是為每個輸入寫一行。 此外,最好在一開始就初始化這兩個總和,並將給定的每個偶數或奇數輸入添加到每個總和中。 您還需要定義將停止循環的計數器或 boolean 語句。

sum_even = 0
sum_odd = 0
i=0
while i < 6:
    num = int(input())
    # check if input is even
    if (num % 2) == 0:
        sum_even+=num
    else:
        sum_odd+=num
    i+=1

暫無
暫無

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

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