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.
- UPDATED: refactor using sets, index, ...
- '''
- # 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 ""
- # Compare the user's list of cities to see which cities are in common with my list
- # Keep a count to display at the end
- sameCities = set(yourCities).intersection(set(myCities))
- sameCityCount = len(sameCities)
- # Display the number of cities in common, with correct plural noun
- if sameCityCount > 0:
- print "Cities we both like:", ", ".join(sameCities)
- if sameCityCount > 1:
- print "We have",str(sameCityCount) + " cities in common."
- else:
- print "We have",str(sameCityCount) + " city in common."
- else:
- print "We have no cities 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:
- # If this item to delete, pop it
- yourCities.pop(yourCities.index(cityToDelete))
- # 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