Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This Python 2 program will build a list of favorite
- cities based on input from the user, then compare the
- cities to my list of favorite cities and output the
- similarities. It then offers to delete a city from
- the list and show the results. Uses while loops,
- if-else and in statements and the isdigit() function.
- '''
- #Initialize my list with my favorite cities
- myCities = ['New York','Los Angeles','London','Paris']
- #Print out my favorite cities
- print "My favorite cities are: ",myCities
- print ""
- #Ask the user for the number of cities they want to enter
- yourCityCount = raw_input ("How many favorite cities do you have?: ")
- #Validate that the input is a positive number
- while not(yourCityCount.isdigit()):
- yourCityCount = raw_input ("How many favorite cities do you have? (NUMBERS ONLY): ")
- #Change type to integer
- yourCityCount = int(yourCityCount)
- #Setup an empty list to be appended to by the user
- yourCities=[]
- #Loop through based on the user's number of cities and add their city to their list
- #x is the loop counter
- x=1
- while x<yourCityCount+1:
- #Get the name of the city
- city = raw_input("Enter your number " + str(x) + " favorite city: ")
- #Make sure it's not a duplicate. If it's not, add it to the list and increase the loop counter
- if city in yourCities:
- print "You already entered", city + "! Please try again."
- else:
- x+=1
- yourCities.append(city)
- #Output the user's list of cities
- print ""
- print "You have",str(yourCityCount) + " favorite cities: "
- print yourCities
- print ""
- #Loop through the user's list of cities to see which cities are in common with my list
- #Keep a count to display at the end
- sameCityCount=0
- for yourCity in yourCities:
- if yourCity in myCities:
- sameCityCount += 1
- print "We both like", yourCity + "."
- #Display the number of cities in common, with correct plural noun
- if sameCityCount > 0:
- if sameCityCount > 1:
- print "We have",str(sameCityCount) + " cities in common."
- else:
- print "We have",str(sameCityCount) + " city in common."
- print ""
- #Offer to delete a city. Only attempt if there are cities
- if yourCityCount > 0:
- #Get the name of the city to delete
- cityToDelete = raw_input("Which city would you like to delete?: ")
- #Only proceed if the city is in the list
- if cityToDelete in yourCities:
- #Loop back from the end of the list to prevent loop counter issues
- #x is the loop counter
- x=yourCityCount
- while x!=0:
- x-=1
- #If this item to delete, pop it
- if cityToDelete==yourCities[x]:
- yourCities.pop(x)
- #Print out the new list of cities
- print "I have deleted", cityToDelete + " from your list:", yourCities
- else:
- #Print an error message
- print "I couldn't find", cityToDelete + " in your list."
- #Exit
- raw_input ("Press Enter to Exit")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement