Advance on getting information from a menu - python

This is my entire code: https://github.com/samy-b/Assignment1/blob/main/addressbook
The main bit I am struggerling with is line 45. We have to create a function that will ask the user to enter the first letter of the surname of a person. Once the user has entered the letter then the program will display all of the attributes such firstname, lastname, address and phone number related to that letter. What can I use to make that happen?

Right after the user input the letter, make the program iterate through the keys of the info dictionary, using the subscription of [1] to get the Surname element of each list, and the subscription of [0] to get the first character of each surname:
elif user_input == 3:
firstletter = input("Please enter the first letter of their Surname")
for line in info:
if info[line][1][0] == firstletter:
print(info[line])

You can get the list of all surnames starting with what you typed:
list(filter(lambda u: u[1].startswith(firstletter), user_info))

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 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 do I randomly join the users input to strings stored in an array using random.choice

I need to write a program that will automatically generate unique usernames for students. The usernames have to be six characters long. The program should generate and display a list of student usernames.
The program will ask how many usernames are to be generated. For each username, the first three letters of the student’s first name will be entered and then combined with a random ending from the list below:
Ing, end, axe, gex, goh
For a student with the first name David, the technician would enter Dav. The program will generate the username by RANDOMLY joining Dav to one of the endings. For example – Daving.
This is all I have so far, I would really appreciate it if anyone knows how to use random.choice to randomly combine the students first 3 letters of their name to the endings that are stored in the array. Thank you!
my code so far:
#Initialising the variables
usernames=0
usernameEndings=["ing", "end", "axe", "gex", "goh"]
studentsName=""
#Getting inputs
usernames=int(input("How many ``usernames are to be generated?"))
#proccess
for counter in range(0,usernames):
studentsName = str(input("Please enter the first three letters of students name."))
while len(str(studentsName)) <3 or len(str(studentsName)) >3:
studentsName= str(input("ERROR, please re-enter the first three letters of students name."))
I've made some minor style tweaks in your code, corrected an indentation error, and added the line you were missing. If there's no need to store the usernames, the program can simply print out each username in turn:
import random
#Initialising the variables
usernames = 0
usernameEndings = ["ing", "end", "axe", "gex", "goh"]
studentsName = ""
#Getting inputs
usernames=int(input("How many usernames are to be generated?"))
#process
for counter in range(0,usernames):
studentsName = str(input("Please enter the first three letters of students name."))
while len(str(studentsName)) != 3:
studentsName = str(input("ERROR, please re-enter the first three letters of students name."))
print('Your username is {}'.format(studentsName[:3] + random.choice(usernameEndings)))
Output:
How many usernames are to be generated?2
Please enter the first three letters of students name.ali
Your username is aligoh
Please enter the first three letters of students name.bob
Your username is bobaxe
Thank you so much for everybodies help I really appreciate it. it helped me finish my project. here is the code I put together.
#Initialising the variables
usernames=0
usernameEndings=["ing", "end", "axe", "gex", "goh"]
studentsName=""
#Getting inputs
usernames=int(input("How many usernames are to be generated?"))
#proccess
for counter in range(0,usernames):
studentsName = str(input("Please enter the first three letters of students name."))
while len(str(studentsName)) != 3:
studentsName= str(input("ERROR, please re-enter the first three letters of students name."))
import random
print((str(studentsName))+random.choice(usernameEndings))
#end of program

How do you add users multiple inputs to a list?

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.

How to receive a list of unknown length of strings

I'd like to receive a list of user aliases for the purpose of looking up an email. As of now, I can do this for only 1 input with the following code:
def Lookup(Dict_list):
user_alias = raw_input("Please enter User Alias: ")
data = []
for row in Dict_list:
#print "row test"
#print row
if user_alias in row.values():
print row
for row in Dict_list:
if user_alias == row['_cn6ca']:
email = row['_chk2m']
print email
return email
But I want to be able to have the user enter in an unknown amount of these aliases (probably no more than 10) and store the resulting emails that are looked up in a way that will allow for their placement in a .csv
I was thinking I could have the user enter a list [PaulW, RandomQ, SaraHu, etc...] or have the user enter all aliases until done, in which case they enter 'Done'
How can I alter this code (I'm guessing the raw_data command) to accomplish this?
This will accept input until it reaches an empty line (or whatever sentinel you define).
#! /usr/bin/python2.7
print 'Please enter one alias per line. Leave blank when finished.'
aliases = [alias for alias in iter (raw_input, '') ]
print (aliases)
You can ask the user to enter a list of aliases, separated by spaces, and then split the string:
In [15]: user_aliases = raw_input("Please enter User Aliases: ")
Please enter User Aliases: John Marry Harry
In [16]: for alias in user_aliases.split(): print alias
John
Marry
Harry
In [17]:
In case the user aliases can have spaces in them, ask them to use, say, a comma as a separator and split by that: user_aliases.split(',')

Categories

Resources