简体   繁体   中英

Storing user values in a Python list using a for loop

This is my Code for Asking user to input the number of cities and should allow only that number of cities to enter Requirement is to use For Loop

global number_of_cities
global city
global li
global container
li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
    city = (raw_input("Enter City Name -->"))
    li = city
    print li[]

Assuming you want a list of the cities in li you can do the following:

li = []
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
    li.append(raw_input("Enter City Name -->"))
print(li)

No need for the global in front of the variables and no need to define the other variables at the beginning, only the empty list.

Actually this is a nice example for learning list comprehension, eg

n = int(raw_input("Enter Number of Cities: "))
li = [raw_input('City Name: ') for city in range(n)]
print(li)

This gives:

>>> n = int(raw_input("Enter Number of Cities: "))
Enter Number of Cities: 4
>>> li = [raw_input('City Name: ') for city in range(n)]
City Name: London
City Name: Paris
City Name: Dubai
City Name: Sidney
>>> print(li)
['London', 'Paris', 'Dubai', 'Sidney']

Instead of

li = city

Use

li.append(city)

Hope thi helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM