In this article let's learn how to create a Python list containing city names and then print them, while I will be asking a user to enter the number of cities using the input function call and then iterate from 0 to N to ask cities and then print it.
This python script is of only eight lines.
Write A Python Script To Create A List Of City Names Taken From The User
Let's take a variable named cities and assign an empty list to it. This list contains strings, where the string is a city name.
Take another variable named as length and using the input function call ask a user to enter the cities list length and then convert it into an integer using int() type conversion.
cities = []
length = int(input("Enter City List Length : "))
Using the for loop, iterate from 0 to N. inside the for loop take a temporary variable and using the input function call ask a user to enter the city name and then append it to the city list. use the built-in function list append() To add an item to the list.
for _ in range(length):
temp = input("Enter City Name : ")
cities.append(temp)
Once the follow-up is completed you will be having all the cities names into the program. Use the for loop and iterate all the cities present in the cities list, also use print statement to print all the cities
print("City List Created, below is the list of cities ")
for city in cities:
print(city)
Python Code
================
cities = []
length = int(input("Enter City List Length : "))
for _ in range(length):
temp = input("Enter City Name : ")
cities.append(temp)
print("City List Created, below is the list of cities ")
for city in cities:
print(city)
Output
==============
Enter City List Length : 5
Enter City Name : Jaipur
Enter City Name : Delhi
Enter City Name : Bangalore
Enter City Name : Chennai
Enter City Name : Mumbai
City List Created, below is the list of cities
Jaipur
Delhi
Bangalore
Chennai
Mumbai
Output
================
Enter City List Length : 3
Enter City Name : New York
Enter City Name : Phoenix
Enter City Name : Chicago
City List Created, below is the list of cities
New York
Phoenix
Chicago
Conclusion
===================
Execute the above Python program by providing the number of city lengths and then input all city names to the Python program, no down the result.
Comment it down below if you have any suggestions to improve the above Python program.
0 Comments