How to differentiate different names? - python

FIGURED IT OUT! IT WASN'T LIKE THE ANSWERS BUT I ADDED A SPACE CHARACTER INTO firstName AND THEN EDITED THE VARIABLE lastName
def nameFinder(rollCall, aName):
spaceCharacter = aName.index(" ")
firstName = aName[0:spaceCharacter]
lastName = aName[spaceCharacter:len(aName)+1]
if (firstName in rollCall) or (lastName in rollCall):
return True
else:
return False
rollCall = "Bobby Lee", "Margaret Me"
print(nameFinder(rollCall, "Bob Ce"))
For this function, I have to find whether the first or last name is in the rollCall. It does not have to be both first and last, only first or last. For example "Bob Ce" would result in False because "Bob" was not in the rollCall. How can I make it like that, since it keeps resulting in True.

After removing (firstName in studentList) or from your code, I get False as output.
I believe your firstName in studentList in your if statement is True, so True or False result the output of True
Please also note, you are checking lastName in rollCall in your if statement, in your code lastName is ' Ce'

Your version, modified
Basically, we split aName and then loop through rollCall, trying to match all of the names. If one matches, return true. Otherwise, return false.
def nameFinder(rollCall, aName):
studentName = aName.split(" ")
for name in rollCall:
rollCallName = name.split(" ")
if rollCallName[0] == studentName[0] or rollCallName[1] == studentName[1]:
return True
return False
rollCall = "Bobby Lee", "Margaret Me"
print(nameFinder(rollCall, "Bob Ce"))
A version that takes up less lines
The following code will first merge both lists into First, Last, First2, Last2, then will scan against the name entered, and if at least one matches, then it will return true:
def nameFinder(rollCall, aName):
array_merged = [partName for fullname in rollCall for partName in fullname.split(" ")]
return any([checkingPartName in array_merged for checkingPartName in aName.split(" ")])
rollCall = ["Bobby Lee", "Margaret Me"]
print(nameFinder(rollCall, "Bob Ce"))
Note: Since we are checking if either name exists in the list, I think merging the two lists would simplify the code. However, if you are only given ["Bobby Lee", "Margaret Me"], then this function will work like a charm.

Related

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

check if key or value exists from one input

I have a dictionary that is similar to
my_dict ={'Bob' : 11, 'Sandy':12, 'Katy':13}
and I have a code that checks if the input matches the value
user_input = input('Enter a name')
while my_dict.get(user_input) == None:
chosenSchool = input('please enter a correct name')
and then other code happens
so that works out fine, but Im trying to have code commence if the user has typed the correct value from user_input, i tried something like this, and i made a list of both the keys and values from my_dict, person_name, and person_code.
if user_input.isdecimal():
while user_input not in my_dict.values():
chosenSchool = input("enter a correct name or number")
numval = int(user_input)
pos_of_Name = person_code.index[numval]
Name_person = person_name[pos_of_name]
So eventually the name of this person should be Name_person, and the code numval, but clearly I am doing something wrong. I could probably make a function or something as well

Why IF statement become false , If I write a name present in the nested list

When I input "Ali" it jumps to new user statement. Anyone please explain me why?
Data_base = [["Ali","1234","5000"],["Sara","1234","2000"]]
User_name = input("Enter your name")
if User_name in Data_base:
print("User persent")
elif User_name not in Data_base:
print("New User")
New_User_name = input("Your name: ")
Data_base.append(New_User_name)
print(Data_base)
The problem is that your list is made up of two separate lists.
Data_base = [["Ali","1234","5000"],["Sara","1234","2000"]]
So when you check if the input is in the list, Python checks if any of the internal values are equal to the input. i.e.:
input = ["Ali","1234","5000"] or input = ["Sara","1234","2000"]
By grouping it into a list I assume the second and third values belong to the first value. Instead of the list I would suggest using a dictionary:
Data_base = {"Ali" : ["1234","5000"], "Sara" : ["1234","2000"]}
And then, for checking:
if User_name in Data_base:
print("User persent")
else:
# Do whatever

How to make search input case insensitive for txt file

Right now the code is working but if I don't capitalize the first letter of both first and last name the code will return "error: person not found."
How can I set it up so that no matter how the user inputs the search it will return the requested data?
#Iterate through the lines and save them in a dictionary, with the
#full name as the key
for line in file:
stripped = line.strip()
name = stripped[:stripped.index(',')]
d[name] = stripped[stripped.index(',')+1:].strip()
def main():
#call the input function to read the file
addresses = input_address()
#Get the user option
option = int(input("Lookup (1) phone numbers or (2) addresses: "))
if option == 1:
phone = True
else:
phone = False
#Ask for names and print their information in case they exist, end on blank entry
while True:
name = input("Enter space-separated first and last name: ")
if name == "":
return main()
if name not in addresses:
print("Error: person not found")
else:
display(addresses[name], phone)
main()
Try using:
.capitalize()
For example:
'hello world'.capitalize()
yields,
'Hello World'
So in your case, you would do:
name.capitalize()
then look for it inside addresses.
You can use lower(), upper(), or capitalize(), as long as you attach the chosen method to end of both variables.
Using lower():
for i in range(len(addresses)):
addresses[i] = addresses[i].lower() # Converting array values to lowercase
if name.lower() not in addresses: # Seeing if lowercase variable is in lowercase array
print("Error: person not found")
else:
print("Person found")

Python: Looping If Statement

friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
for friend in friends:
print friend
if friend == name:
return True
else:
return
print (is_buddy('Tim'))
What is the problem here? Why do I get False if I put in "Tim" or anyone else other than Bob?
Try:
def is_buddy(name):
for friend in friends:
if friend == name:
return True
return False
The problem is that you checked name against the first entry of the list which is Bob and you decided to make a boolean decision. You should have returned False only at the end where you checked against every element of the list.
The pythonic way to do what you want:
friends = ["Bob","Mike","Ana","Tim","Dog"]
def is_buddy(name):
if name in friends:
return True
else:
return False
print (is_buddy('Tim'))
Your problem is that else statement tigers return which causes the end of the for loop after 1'st iteration
What you probably want to do is to continue looping. So just remove else part from your function or replace return with something like print "not found"

Categories