Python 如何正确使用while和if语句
我正在练习while语句和if语句,有人能告诉我我做错了什么吗?我将提供与我自己的代码相匹配的代码,但不包括我的邮政编码示例和投票站的位置:Python 如何正确使用while和if语句,python,python-3.x,Python,Python 3.x,我正在练习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 < ag
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")
首先,检查你的缩进。您在这里介绍的代码似乎有一些缩进问题 然后,这里的错误很可能是您将邮政编码输入为一个数字(您已使用
int()
)将输入的压缩为,但将邮政编码作为字符串进行比较:“123”==123
将计算为False
在zipCode==“76324”
中删除”
,或更改为str(zipCode)==“76324”
编辑-蟒蛇提示:
我知道您正在测试if
s和while
s,但对于未来,一种更具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)
我认为您可能有一些复制粘贴错误,至少在您提供的代码中是这样的:最后两个if
s和下面的elif
s完全相同(?)。是的,它们很相似,因为在我这边,我有不同的邮政编码以及投票站地址。myzipCode
对于这个程序来说是无效的输入。你在那里键入了什么?@LeoV。你确定你的代码缩进正确吗?正如这里所示,如果zipCode==“93620”,它将停止并计算“
。如果False
,则退出。@LeoV。如果我下面的回答解决了您的问题,请将其标记为“已接受”。或者,如果您已经实现了自己的解决方案,请在下面发布并接受它。
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)