簡體   English   中英

如何正確使用 while 和 if 語句

[英]How to correctly use while and if statements

我正在嘗試練習我的 while 語句和 if 語句,有人可以向我解釋我做錯了什么嗎? 我將提供與我自己的代碼相匹配的代碼,但不包括我的郵政編碼示例和投票站的位置:

print ("VOTER ELIGIBILITY AND POLLING STATION PROGRAM\n")
ageMin = 18
end = 0
zipCode = 0
usrAge = int(input("\nEnter your age (Type '0' to exit program): "))
while usrAge < ageMin and usrAge != end:
    print("YOU ARE INELIGIBLE TO VOTE")
    usrAge = int(input("\nEnter your age (Type '0' to exit program): "))
if usrAge == end:
    input("\nRun complete. Press the Enter key to exit.")
while usrAge != end:
    zipCode = int(input("\nEnter your residence's zip code: "))
    usrAge = int(input("\nEnter your age (Type '0' to exit program): "))
    input("\nRun complete. Press the Enter key to exit.")
if zipCode == "93620":
    print("Your polling station is 123 elm st.")
    if zipCode == "83340":
        print("Your polling station is 14 bell monte st. ")
    elif zipCode == "76324":
        print("Your polling station is  147 avalon dr.")
    elif zipCode == "15547":
        print("Your polling station is 632 elena st. ")
    elif zipCode == "63295":
        print("Your polling station is 100 monte clare st.")
    else:
        print("Error – unknown zip code")

該腳本運行但由於某種原因它沒有顯示正確的輪詢地址,即使我不希望它直接進入 else 語句,我也試圖循環 usrAge 語句,以便用戶可以他們想要的提示。

例子:

VOTER ELIGIBILITY AND POLLING STATION PROGRAM


Enter your age (Type '0' to exit program): 19

Enter your residence's zip code: myzipCode

Enter your age (Type '0' to exit program): 0

Run complete. Press the Enter key to exit.
Error – unknown zip code

首先,檢查你的縮進。 您在此處提供的代碼似乎存在一些縮進問題。

然后,這里的錯誤很可能是您將 zip 代碼作為數字input (您已使用int()封裝您的輸入),但比較起來好像 zip 代碼是一個字符串: "123" == 123將評估為False

在您的zipCode == "76324"中刪除" ,或更改為str(zipCode) == "76324"

編輯 - 一個 pythonic 提示:我知道你正在測試if s 和while s,但是對於未來,一個更Pythonic的方法可能是使用字典,像這樣

zipcodes = {93620:"123 elm st", 83340:"14 bell monte st"}

zipCode = 93620
if int(zipCode) in zipcodes:
    print("Your polling station is ", zipcodes[zipCode])
else:
    print("ERROR - unknown zip code: '%s'" % zipCode)

暫無
暫無

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

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