如何正确使用while和if语句

2024-05-20 15:28:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在练习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

Tags: toinputageyouristypeexitprogram
1条回答
网友
1楼 · 发布于 2024-05-20 15:28:34

首先,检查你的压痕。您在这里介绍的代码似乎有一些缩进问题。你知道吗

然后,这里的错误很可能是您将邮政编码作为一个数字输入(您已经将您的input压缩为int()),但是比较起来就像邮政编码是一个字符串:"123" == 123将计算为False!你知道吗

删除"中的zipCode == "76324",或者更改为str(zipCode) == "76324"。你知道吗

编辑-Python提示: 我知道你正在测试ifwhile的,但是对于未来,一个更具python的方法可能是使用字典,就像这样

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)

相关问题 更多 >