Home > database >  Using sequence-type functions with lists from user input
Using sequence-type functions with lists from user input

Time:06-14

I am currently writing a program where user user would input a list of cities they have lived in. Next the code will return the number of cities they have lived in. I am having trouble generating the number of cities the user has lived in. I am using len(). Below is my code.

#stores the user input in a string call myfirst_string
myfirst_string = (input("Hello, What is your name: "))

#Returns the first 2 letters of the user's name
print("The first two letters of your name is: ", myfirst_string[0]   myfirst_string[1])

#stores the lists of cities where the user has lived into a variable call places_lived_list
places_lived_list = [input("Which cities have you lived in: ")]

#outputs the cities the user has lived in and then returns the number of cities lived in based on the cities the user has input and are separated by commas.
print("You have lived in these cities: ",places_lived_list)
print("you have lived in", len(places_lived_list), 'City')

Screenshot of output

CodePudding user response:

The third line should be somthing like:

places_lived_list = input("Which cities have you lived in: ").split(",")

Note that this only works if the cities are provided in the format "city1,city2,city3"

CodePudding user response:

You asked a few follow-up questions in the comments, here's your code with some corrections and the problem resolved:

# no parentheses required around the call to `input`
myfirst_string = input('Hello, What is your name: ')

# nothing is returned here, the string is indexed twice and print 
# technically returns `None`, but this isn't captured
print("The first two letters of your name is:", myfirst_string[0]   myfirst_string[1])

# here's the answer
places_lived_list = input('Which cities have you lived in (with commas): ').split(',')

# still a list
print('You have lived in these cities:', places_lived_list)

# so the length is correct
print('You have lived in', len(places_lived_list), 'cities')

You were also using both ' and " to delimit your strings, it's generally best to pick one and ' is the Python default.

Running the script now:

Hello, What is your name: Grismar
The first two letters of your name is: Gr
Which cities have you lived in (with commas): Den Haag, Brisbane
You have lived in these cities: ['Den Haag', ' Brisbane']
You have lived in 2 cities
  • Related