簡體   English   中英

Python 開始:無法弄清楚如何告訴用戶他們的數字是奇數還是偶數(5 個數字)

[英]Python Beginning: Can't figure out how to tell user their number is odd or even (for 5 numbers)

我剛剛注冊,我不確定這是否會進入正確的論壇(假設這是這里的事情)。

幾周前我剛剛開始學習 Python。 我們在做迭代。

這是我們本次作業的閱讀材料: https : //www.py4e.com/html3/05-iterations

這是作業和我的代碼。

編寫一個程序,讓用戶一次輸入五個數字。 每次輸入后,告訴用戶數字是奇數還是偶數。 在所有輸入的末尾,在屏幕上顯示所有輸入數字的總和。

x = 0
num = 0   
while x < 5:
    x += 1
    num += int(input("Enter a number: "))
    mod = num % 2
    if mod > 0:
        print(num-x,"is an odd number.")
    else:
        print(num-x,"is an even number.")
print("Your total is",num)

這不適用於作業的奇數和偶數部分。 我很確定這與每次用戶輸入新數字時 'num' 變量都發生變化有關,而不是僅僅告訴用戶他們剛剛輸入的數字是偶數還是奇數,而是將數字相加。

所以,如果第一個用戶輸入是 3,它會說它是奇怪的。 但是如果他們再次為第二個數字輸入 3,它會說它是 Even 因為它加上 3 + 3 得到 6。很明顯,我不希望它在最終打印之前將數字加起來。

This is my output:
Enter a number: 1
0 is an odd number.
Enter a number: 1
0 is an even number.
Enter a number: 1
0 is an odd number.
Enter a number: 1
0 is an even number.
Enter a number: 1
0 is an odd number.
Your total is 5

顯然,所有這些 1 都應該是奇數,而我剛剛意識到 0 不屬於那里。

您正在嘗試將num用於兩個不同的目的:

  • 累計金額
  • 剛剛輸入的號碼

結果,您最終測試的是累積和的奇數/偶數,而不是剛剛輸入的數字。

將它們分成兩個不同的變量numtotal ,然后它會變得更容易。

我還建議對x使用for而不是while循環:

total = 0   
for x in range(5):
    num = int(input("Enter a number: "))
    mod = num % 2
    if mod > 0:
        print(num, "is an odd number.")
    else:
        print(num, "is an even number.")
    total += num

print("Your total is", total)
x = 0
total_num = 0
while x < 5:
    num = int(input("Enter a number: "))
    mod = num % 2
    if mod > 0:
        print(num,"is an odd number.")
    else:
        print(num,"is an even number.")
    total_num += num
    x += 1

print("Your total is",total_num)

你是部分正確的。 檢查數字是否為奇數/偶數的邏輯是好的。 現在,問題是每次您讀取一個數字時,您都會將該新數字添加到前一個數字上。 這里的解決方案是使用另一個變量來跟蹤總數,這樣您就可以單獨檢查數字是否為奇數/偶數,並在最后獲得總和。
此外,如果您檢查mod == 0而不是mod > 0 ,它看起來更干凈。 所以只需切換那些。 最后,您不需要從您的num減去xx只是您的計數器,用於跟蹤您在給定時刻進行的迭代。

x = 0
num = 0
total = 0
while x < 5:
    x += 1
    num = int(input("Enter a number: ")) # Read new number
    total += num # Add new number to the total
    mod = num % 2 # Check if new number is odd
    if mod == 0:
        print(num,"is an even number.")
    else:
        print(num,"is an odd number.")
print("Your total is",total)

不是將變量num相加,而是分配一個不同的變量來計算輸入的數字。

x = 0
num = 0
sum1 = 0
while x < 5:
        x += 1
        num = int(input("Enter a number: "))
        sum1 += num
        mod = num % 2
        if mod > 0:
               print(num,"is an odd number.")
        else:
               print(num,"is an even number.")
print("Your total is",sum1)

對縮進進行了細微的更改,分配了一個額外的變量並且它起作用了。

我不是 Python 程序員,但您需要第三個變量來計算總數。 目前 num 正在做這部分工作,當使用 += 分配值時。 這意味着它正在對小計而不是條目值進行修改。

它應該是:

num = int(input("Enter a number: "))

那沒有+。

然后你需要第三個變量來顯示最后的總數:

total = total + num

暫無
暫無

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

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