# Initialized list of cities
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
# Get user input
inCity = input("Enter name of city: ")
# Write your test statement here to see if there is a match.
for i in range(len(CitiesInMichigan)):
if CitiesInMichigan[i] == inCity:
while CitiesInMichigan is True:
print("City found. ")
break
else:
print("Not a city in Michigan. ")
input("Enter name of city: ")
# If the city is found, print "City found."
# Otherwise, "Not a city in Michigan" message should be printed.
所以我想要做的是讓輸入不區分大小寫,以便(Acme、ACME、acMe 等)可以作業,如果輸入匹配則讓它中斷,或者如果輸入為假則重試。相反,我一直收到所有輸入都不是密歇根州的一個城市。我究竟做錯了什么?
PS我正在為學校學習python,作為一種熱情,我仍然是新手,我的腦袋圍繞著它,請批評我做錯的任何事情以進一步改進我的編碼。謝謝
uj5u.com熱心網友回復:
您的while回圈是不必要的,您的else子句應該簡單地移出回圈。如果找不到城市,您還需要一直回圈回到初始輸入。
cityFound = False
while not cityFound:
inCity = input("Enter name of city: ")
for i in range(len(CitiesInMichigan)):
if CitiesInMichigan[i] == inCity:
print("City found. ")
cityFound = True
break
if not cityFound:
print("Not a city in Michigan. ")
要進行不區分大小寫的匹配,在檢查是否相等之前,您應該在輸入和串列中的值上使用string upper 方法。CitiesInMichigan
其他注意事項:
- 您不需要在 for 回圈中使用索引,您可以使用
for city in CitiesInMichigan - 通常變數名以小寫字母(
citiesInMichigan而不是CitiesInMichigan)開頭。類名以大寫字母開頭
uj5u.com熱心網友回復:
正如其他人所提到的,while回圈是不必要的。下面的代碼比它需要的要長,但它很好地解釋了自己。
# Initialized list of cities
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
def get_input():
'''Get user input and capitalize it'''
inCity = input("Enter name of city: ")
inCity = inCity.capitalize()
check_against_list(name=inCity)
def check_against_list(name):
'''check if the item is in the list. if yes, print. if not, print and start over'''
if name in CitiesInMichigan:
print("City found. ")
else:
print("Not a city in Michigan. ")
get_input()
get_input()
uj5u.com熱心網友回復:
CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland",
"Brooklyn"]
CitiesInMichigan_casefold = [i.casefold() for i in CitiesInMichigan ]
inCity = input("Enter name of city: ")
while True:
if inCity.casefold() in CitiesInMichigan_casefold:
print("city found",inCity)
break
else:
print("city not found")
inCity = input("Enter name of city again: ")
Try this. you have to compare case fold strings both in input and as well as from the mentioned list.
if the city is found, it prints city name and breaks the loop.
else it continues until the city is matched.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526653.html
