I'm trying to figure out what is probably something very simple. I need to make a program where I print the user's specified city and state that they provide. They need to type it in as city,state in the input statement and their answer is stored in a variable called userInput.
Now, here's my issue: Users won't always have the same city and state. Thus, the index numbers of the string that they need to give will change. My question is: How do I print these two things apart from one another, no matter their position in the string?
Edit: Here is an example of what I am trying to do:
userInput = input("Enter your city and state in the format city,state ")
The program should print "You live in the state of [state the user types]" on one line and "Your city is [city the user types>]" on the other.
If user always input "city,state" with a comma separator you could use split()
user_input = input("Enter city,state :")
city, state = user_input.split(",")
Use the str.split() function to split the user's input at the comma, and use formatted strings to print the values into the lines:
city, state = input("Enter your city and state in the format city,state ").split(',')
print(f"You live in the state of {state}\nYour city is {city}")
Related
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
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"
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
I have a scenario where I have a list of names of countries. Now, I have to prompt for user input 5 times and if that input matches a particular string in the list, then I have to append that string into a second list. If the value entered does not match with any name in the list, then I have to keep on asking the user until a correct word is typed. My python code is mentioned below.
Python Code:
a = []
for i in range(5):
b = str(input("Enter the name: "))
if(b == 'USA' or b == 'UK'):
a.append(b)
else:
for name in a:
if(b == name):
c.append(name)
print(c)
Problem:
I am not able to compare the user input with the strings present in the list.
Can someone please help me in implementing the above-mentioned logic?
To check if your input provided country exists in a list you can do the following:
country = input("Enter the name of a country: ")
if country in country_names:
# logic if exists
else:
# logic is not exists
if name not in country_name:
country_list.append(name)
Ive written a program which takes in the name and age of multiple entries seperated by a comma and then sepearates the aplhabets from the numerics and then compares the name with a pre defined set/list.
If the entry doesnt match with the pre defined data, the program sends a message"incorrect entry" along with the element which didnt match.
heres the code:
from string import digits
print("enter name and age")
order=input("Seperate entries using a comma ',':")
order1=order.strip()
order2=order1.replace(" ","")
order_sep=order2.split()
removed_digits=str.maketrans('','',digits)
names=order.translate(removed_digits)
print(names)
names1=names.split(',')
names_list=['abby','chris','john','cena']
names_list=set(names_list)
for name in names1:
if name not in names_list:
print(f"{name}:doesnt match with predefined data")
the problem im having is even when i enter chris or john, the program treats them as they dont belong to the pre defined list
sample input : ravi 19,chris 20
output:ravi ,chris
ravi :doesnt match with predefined data
chris :doesnt match with predefined data
also i have another issue , ive written a part to eliminate whitespace but i dont know why, it doesnt elimintae them
sample input:ravi , chris
ravi :doesnt match with predefined data
()chris :doesnt match with predefined data
theres a space where ive put parenthesis.
any suggestion to tackle this problem and/or improve this code is appreciated!
I think some of the parts can be simplified, especially when removing the digits. As long as the input is entered with a space between the name and age, you can use split() twice. First to separate the entries with split(',') and next to separate out the ages with split(). It makes comparisons easier later if you store the names by themselves with no punctuation or whitespace around them. To print the names out from an iterable, you can use the str.join() function. Here is an example:
print("enter name and age")
order = input("Seperate entries using a comma ',': ")
names1 = [x.split()[0] for x in order.split(',')]
print(', '.join(names1))
names_list=['abby', 'chris', 'john', 'cena']
for name in names1:
if name not in names_list:
print(f"{name}:doesnt match with predefined data")
This will give the desired output:
enter name and age
Seperate entries using a comma ',': ravi 19, chris 20
ravi, chris
ravi:doesnt match with predefined data
So for part of the assignment I am doing, I ask the user their address (including street name) and minus it from 68.
so far I have:
streetName = raw_input("Please enter your address: ")
say the user enters there address as 668 Rickman Street, I am supposed to take the 668 and minus it from 68 and what would be printed is
"your secret code is -600"
-600 being obviously the calculation of 68-668
However I do not know how to take the 668 out of the raw input and put it into the calculation.
You can check and try to cast each splitted string if you are sure you have spaces between your number and street name
streetName = raw_input("Please enter your address: ")
names = streetName.split(' ')
secret_code = -1
for name in names :
try :
secret_code = 68 - int(name)
except ValueError :
continue
# Thanks to Jon Clements
if secret_code > 68 :
print 'something went wrong , check your address'
else
print secret_code
You can go through streetName using a for loop and stop wherever you find the first space, store the index and extract a substring starting in 0 to the index calculated, then parse it to integer.
Example Code:
stringVar = "123 Hello world"
subStringVar = a[0:3]
stringParsed = int(subStringVar)
So now stringParsed is 123, then just do a simple operation 68 - stringParsed.
you can split the input string on whitespace delimiter:
>>> int("668 Rickman Street".split()[0])
668
I think the first thing to do is to understand what data structures you will use
to get to your final answer. Look out for examples on string and list comprehension.
Lets say street_name is a string. If the address occurs in the same index in street_name then you can exit the loop once you have accessed the first word or encountered the first blank space after 686.
Or you can convert the string into a list.
street_name_lst = street_name.split()
where street_name_lst => ['668', 'Rickman', 'Street']
Now you just access the first element using first index.
address = street_name_lst[0]
Now str_address => '686' , but this is in string(incompatible type to do any processing with an Integer type for your case), so lets convert String address
to Integer type.
int_add = int(str_address)
Now you have int_add => 686 and now you can do further computation on it.
Remember data structures and type systems in any language are important.
Also look into PEP8 standard to check for good convention on naming your variables.
https://www.python.org/dev/peps/pep-0008/#id38
It might be helpful to install ipython. check http://ipython.org/
Let's say that I have a line with: a = input("Enter your name and age:")
How can I make the variable "a" store each section of the input, lets say "George 25" as "George, 25" either as a standard variable or a list? All I want to do is be able to store user input as separate elements in a list or variable so that input with words separated by a space would become separate elements in a variable. Is this clear enough? I am using Python 3.0
How about using str.split():
user_input_list = input("Enter your name and age:").split(' ')
This creates a list of each space-separated word in the input.
>>> 'George 25'.split(' ')
['George', '25']
Then you can access each part as:
user_input_list[0] # George
user_input_list[1] # 25
Is that what you're after ?