How do you add users multiple inputs to a list? - python

In terms of using this:
names = [] # Here we define an empty list.
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(eingabe)
How do you use it for multiple inputs?

Try this:
names = [] # Here we define an empty list.
flag = True
while flag:
eingabe = input('Please enter a name: ')
if not eingabe:
flag=False
names.append(eingabe)
print(eingabe)
So, until the flag not became False this while loop run continuously.
and if user does not entered any input value than it set the flag value False and loop will terminate.

If all you want is to convert multiple user inputs to a list, this will be the easiest way:
names = input('Please enter names (separated by space): ').split()

According to your question and given code above , it already takes multiple input from user but it seems that you are not printing them. If you want to get multiple input from user and add them to a empty list and print them out , then you've to change a bit more of your code.
names = []
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(names)
or you can do this simply just using split() method -
names = input('Enter name like : "apple microsoft facebook ...": ').split()
print(names)
Please let me know whether it is or not.

Related

Write a program that first takes in word pairs that consist of a name and a phone number (both strings), separated by a comma

I have the following prompt:
A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes in word pairs that consist of a name and a phone number (both strings), separated by a comma. That list is followed by a name, and your program should output the phone number associated with that name. Assume the search name is always in the list.
Ex:
If the input is: Joe,123-5432 Linda,983-4123 Frank,867-5309 Frank the
output is: 867-5309
my code:
pn = str(input()).split()
search = str(input())
i=0
for i in range(len(on)):
if pn[i] == (search):
print([i+1])
The input is getting split into a name and number. When the code goes to check if the names are the same, it always returns false. I've tried using the re.split() method, but it didn't work.
You should split twice and second split char should be a comma s.split(",")
s = "Joe,123-5432 Linda,983-4123 Frank,867-5309"
for i in s.split():
temp = i.split(",");
print("name :", temp[0] , " number is :" , temp[1] )
Output
name : Joe number is : 123-5432
name : Linda number is : 983-4123
name : Frank number is : 867-5309
Try splitting around the comma when searching for the name:
pn = input().split()
search = input()
for i in pn:
val = i.split(',')
if val[0] == search:
print(val[1])
You need to have the following things in your program to meet the basic requirements
Infinite loop to enter contact info until user stop entering
List or Dictionary to hold entered info and for searching
The code can be like following
contacts = {}
while True:
info = input('Enter Contact Info or Leave empty to Stop Entering: ').split(',')
if len(info) > 1:
contacts[info[0]] = info[1]
else:
break
name = input('Enter name to search: ')
print(contacts[name])
Output is following
It seems like you're trying to store the data as an input, ask the user for a query (name of a person), and then respond with that person's phone number.
# Get the data
inputs = input("Enter the input. >>> ").split(sep=" ")
# Split the data into lists
for pos in range(len(inputs)):
inputs[pos] = inputs[pos].split(sep=",")
# Ask for a search query
query = input("Enter a name. >>> ")
# Check for the name in the first element of each item
for item in inputs:
if item[0] == query:
print(f"{query}'s phone number is {item[1]}.")
break
A sample data input, as called in line 2:
Enter the input. >>> John,12313123 Bob,8712731823
As of the search query line of the code, your inputs variable looks something like: [['John', '12313123'], ['Bob', '8712731823']]. The program will iterate through the items of inputs, where each item is a list of two strings, and then check if the first item of this sub-list matches the inputted query.
contact_list = input().split(sep=" ")
search_list = input()
def Convert(lst):
res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res_dct
contact_dict = Convert(contact_list)
print(contact_dict[search_list])

How to save a name as a variable when saving a Data frame file?

I have to save several files at a time.
It is saved as .txt using .to_csv.
The following method is used to save the Data Frames of position, energy, number, event, and height.
position.to_csv('/HDD1/abc_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/abc_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/abc_height.txt',index=False,sep=" ")
Let's check the save file name above. They contain 'abc'.
I want to replace 'abc' with the variable 'A = abc' without having to write it down many times.
In other words, it should be as follows.
A = abc
postion.to_csv('/HDD1/A_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/A_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/A_height.txt',index=False,sep=" ")
Is there a way to save files using variables as above?
Are you looking for f-strings?
A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")
can use an f-string. Let
A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_number.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")
EDIT
Aditional (don't know if pythonic) you can create dictionary with all your dataFrames and call this a simplier way:
dataFrames = {'position':position,
'energy':energy,
'number':number,
'event':event,
'height':height
}
A = 'abc'
dir = '/HHD1'
for key,val in dataFrames.items():
val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ")
The last one liner is the same as:
[val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ") for key, val in dataFrames.items()]
I think the first way is more pythonic, but not sure

The program repeats until the input string is quit and disregards the integer input that follows

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. The program repeats until the input string is quit and disregards the integer input that follows.
Ex: If the input is:
apples 5
shoes 2
quit 0
the output is:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.
This is what I've got so far:
string = input().split()
string2 = input().split()
string3 = input().split()
all_input = (string + string2 + string3)
for word in all_input:
while word != 'quit':
print('Eating {} {} a day keeps the doctor away.'.format(string[1] , string[0]))
print('Eating {} {} a day keeps the doctor away.'.format(string2[1], string2[0]))
string = input().split()
string2 = input().split()
string3 = input().split()
all_input = (string + string2 + string3)
I get the correct output but also receive this error:
Traceback (most recent call last):
File "main.py", line 11, in <module>
string = input().split()
EOFError: EOF when reading a line
And when it tests with the inputs:
cars 99
quit 0
Then I get no output. I feel like I need to use a break statement somewhere but nowhere I put it seems to work.
you are using input() multiple times where you can use it once inside a loop and if the input_string contains 'quit' it will be terminated. try the following code, it will continue taking input till the user enters quit
while True:
input_string = input()
if 'quit' in input_string:
break
else:
a,b = input_string.split(' ')
print(f'Eating {b} {a} a day keeps the doctor away.')
OR
if you want to take all inputs at once, then find the code below, it will work as you expected
input_string = []
while True:
line = input()
if 'quit' in line:
break
else:
input_string.append(line)
for line in input_string:
a,b = line.split(' ')
print(f'Eating {b} {a} a day keeps the doctor away.')
You can use a loop to achieve the same result, and you can use it too for files with more and less lines.
You can use 'quit' not in variable_name as the exit condition of the loop. When the variable you test is a substing, this statement will look for "quit" as a substring.
To split the words in the lines str.split() is your friend. After calling it, it returns an array. The first element of this array will be the object, and the second the number of elements.
mad_lib = input()
while 'quit' not in mad_lib:
MD_list = mad_lib.split()
thing = MD_list[0]
integer = MD_list[1]
print("Eating {} {} a day keeps the doctor away.".format(integer,thing))
# Read the input again to process more lines
mad_lib = input()
The main roadblock may be splitting the input first, as others noted. Additionally, do not think of this exercise as there will be a set number of strings. Strings can be 0 to infinity -- that will be left to the user (or computer) to decide. Once you str.split() and loop input before the loop and in the loop, you can KISS (keep it simple stupid) with a not in rather than using breaks. Sure, the breaks look as if you paid attention during your lessons in the chapter, though so far I have found breaks to be only needed under select circumstances (if at all?). If your instructor does not have requirements on what you need to use in your program, use the following (also seen in #Jamal McDaniel / #Iñigo González above).
user_input = input() #initial input
while 'quit' not in user_input:
choices = user_input.split() #split the string
word = choices[0]
integer = choices[1]
print("Eating {} {} a day keeps the doctor away.".format(integer, word))
user_input = input() #get another input and loop until 'quit'
I solved the problem using this code.
var1 = input() #takes in string(apples 5)
mad_lib = var1.split() #splits user input into two strings (apples, 5)
while 'quit' not in mad_lib: #loop that only stops when 'quit' is entered
print('Eating {} {} a day keeps the doctor away.'.format(mad_lib[1], mad_lib[0]))
var1 = input() #increments loop with new input(shoes 2)
mad_lib = var1.split() #splits new user input into two strings again (shoes, 2)

How to split a single line input string having Name(1 or more words) and Number into ["Name" , "Number"] in Python?

I am a newbie. I failed one of the test cases in a phone book problem. As per the question, a user is expected to enter a single line input which contains a name (which can be one or more words) followed by a number. I have to split the the input into ["name","number"] and store it in dictionary. Note that the name will have one or more words(Eg: John Conor Jr. or Apollo Creed). I am confused with the splitting part. I tried out the split() function and re.split(). Not sure I can solve this.
Sample input 1 : david james 93930000
Sample Input 2 : hshhs kskssk sshs 99383000
Output: num = {"david james" : "93930000", "hshhs kskssk sshs" : "99383000"}
I need to store it in a dictionary where the key:value is "david james": "93930000"
Please help. Thank you
=====>I found a solution<==========
if __name__ == '__main__':
N=int(input())
phonebook={}
(*name,num) = input().split()
name = ''.join(map(str,name)
phonebook.update({name:num})
print(phonebook)
The astrik method words. But for a large data set this might slow me down. Not sure.
So im assuming that the inputs stated are coming from a user, if that
is the case you could change the format in your code to something
similar to this. You can change the range depending on how many inputs you want.
name = {}
for i in range(5):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
name[student_name.title()] = student_mark
print(marks)
This should print the results in the way you mentioned!
Please check for the updated answer if this is what you are looking
for.
# Sample text in a line...
# With a name surname and number
txt = "Tamer Jar 9000"
# We define a dictionary variable
name_dictionary = {}
# We make a list inorder to appened the name and surname to the list
name_with_surname = []
# We split the text and if we print it out it should look something like this
# "Tamer", "Jar", "9000"
# But you need the name and surname together so we do that below
x = txt.split()
# We take the first value of the split text which is "Tamer"
# And we take the second value of the split text us "Jar"
name = x[0]
surname = x[1]
# And here we append them to our list
name_with_surname.append(name + " " + surname)
#print(name_with_surname)
# Finally here to display the values in a dictionary format
# We take the value of the list which is "Tamer Jar" and the value of the number "9000"
name_dictionary[name_with_surname[0]] = x[2]
print(name_dictionary)
The above answers can't handle if a data has too many name parts in one line.
Try my code below.
You can just loop through whatever the total number of inputs you want.
phonebook = {}
total_inputs = int(input())
for i in range(total_inputs):
name_marks = input().split() # taking input and splitting them by spaces
name = " ".join(x for x in name_marks[:-1]) # extracting the name
marks = name_marks[-1] # extracting the marks
phonebook[name] = marks # storing the marks in the dictionary
This way you can store the marks for the name. It will handle even one input has many name parts.

How to read input line by line, instead of by spacing

I'm trying to read a large number of user inputs line by line instead of by spacing.
code:
keyword = (input("\n Please enter the keywords "))
keywords = keyword.split(" ")
words:
a
abandon
ability
able
abortion
The input function ends by pressing enter or moving to a new line, so you have to define how you want to finish instead.
If you're looking for a way to enter 5 words like you did in your example, this should be enough:
print("\n Please enter the keywords ")
keywords = [input() for i in range(5)]
You can change range(5) to range(3000) or any other number that you wish.
If you would like in input an infinite amount of words until some special keyword is entered (like "quit") you can do this:
print("\n Please enter the keywords ")
keywords = []
while True:
k = input()
if k == 'quit':
break
else:
keywords.append(k)
You may want to read from the sys.stdin, for example:
import sys
it = iter(sys.stdin)
while True:
print(next(it))
Here you have a live example

Categories

Resources