【问题标题】:Matching variables to an array using user input in Python在 Python 中使用用户输入将变量与数组匹配
【发布时间】:2018-08-01 18:59:37
【问题描述】:

我无法弄清楚为什么这些步骤没有改变以通过循环并检查每个步骤。

# MichiganCities.py - This program prints a message for invalid cities in 
Michigan.  
# Input:  Interactive
# Output:  Error message or nothing
# Initialized list of cities
citiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", 
"Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"] 
inCity = "userinput"
step = 0
size = 10
while step < size:
    inCity = input("Enter name of city: ")  # Get user input
    print (inCity)
    if inCity == citiesInMichigan[step]: # If the city is found, print "City found."
        print ("City found.")
        step = step +1
    else:
        print ("Not a city in Michigan.") # Otherwise, "Not a city in 
Michigan" 
message should be printed. 

【问题讨论】:

  • 为什么不直接做if inCity in citiesInMichigan

标签: python arrays loops matching


【解决方案1】:
citiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", 
"Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"] 
inCity = "userinput"
step = 0
size = 10
while step < size:
    inCity = input("Enter name of city: ")  # Get user input
    print (inCity)
    if inCity in citiesInMichigan: # If the city is found, print "City found."
        print ("City found.")
        step = step +1
    else:
        print ("Not a city in Michigan.") # Otherwise, "Not a city in  Michigan" message should be printed.

嗨!请试试这个。希望有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2016-07-28
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多