First I'm sorry this might be a dumb question but I'm trying to self learn python and I can't find the answer to my question.
I want to make a phonebook and I need to add an email to an already existing name. That name has already a phone number attached. I have this first code:
phonebook = {}
phonebook ['ana'] = '12345'
phonebook ['maria']= '23456' , 'maria#gmail.com'
def add_contact():
name = raw_input ("Please enter a name:")
number = raw_input ("Please enter a number:")
phonebook[name] = number
Then I wanted to add an email to the name "ana" for example: ana: 12345, ana#gmail.com. I created this code but instead of addend a new value (the email), it just changes the old one, removing the number:
def add_email():
name = raw_input("Please enter a name:")
email = raw_input("Please enter an email:")
phonebook[name] = email
I tried .append() too but it didn't work. Can you help me? And I'm sorry if the code is bad, I'm just trying to learn and I'm a bit noob yet :)
append isn't working because the dictionary's values are not lists. If you make them lists here by placing them in [...]:
phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , 'maria#gmail.com']
append will now work:
def add_contact():
name = raw_input("Please enter a name:")
number = raw_input("Please enter a number:")
phonebook[name].append(number)
Related
I am attempting to create a contact list with a def() function to easily loop back to the top later in the code. The issue I am having is that I define "function_question" in the def portion but when I run the code it gives me a NameError saying "function_question" is not defined. Any help or suggestions is appreciated!!
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
function_question = int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
name = input('What is the persons name? ')
phone_number = input('What is the phone number? ')
email = input('What is your email? ')
address = input('What is the person adress? ')
if len(phone_number) != 10:
phone_number = input("the phone number you provided is not the proper length. Re-enter:")
contact = [] + [name] + [phone_number] + [email] + [address]
contact_list.append(contact)
ans = input('Would you like to add another contact? ')
if ans == 'yes':
continue
if ans == 'no':
user_prompt()
You could simply return the value from the function and save it to a variable outside the function. Like:
def user_prompt():
print('Welcome to your contact directory.')
return int(input("question"))
input_question = user_prompt()
The issue is that the variable function_question is empty.
In your code you defined two variables function_question with the same name but with different memory address; the first is a local variable that works only into the user_prompt() function.
The correct code is:
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
return int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
function_question = user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
...
I suggest you to search about python scope variable for more details.
The function_question variable is in the scope of the user_prompt function so you cannot use it in the global scope. You need to make it global for it to be acessible
I reccomend reading through this,
https://www.w3schools.com/PYTHON/python_scope.asp
I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")
im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
pin = int(input("Enter your pin: "))
if pin in pins.values():
nameinp = pins.get(pin)
print("Hello Mr." + nameinp)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for key in pins.keys():
print(key)
input()
So the idea is to make greeting screen for the particular person who inserted his own pin code, tried to research didn't find the answer, hope you will help!
Answers to all of you
There is no error, there is a question:
how to make that when you put in password that is equal some value, and later when the system recognizes your password prints("Greetings" + value)
You have the order of the dictionary key-value pairs interchanged. So instead of
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
you should do
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
I took the liberty to change the variable name to be more descriptive what it actually does: Given a pin it returns the username. For example: user_from_pin[1111] == "Joe". The rest of the script should be adapted a little bit to work with this definition:
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
pin = int(input("Enter your pin: "))
user = user_from_pin.get(pin)
if user:
print("Hello Mr." + user)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for value in pins.values():
print(values)
input()
I'm basically running a code that builds up an address book into a text file through user entries.
While doing so, I'm checking to see if the inputed information is correct and, in the case that it's not, asking them to correct it. However, I realize that it's possible (though unlikely) that a user could input incorrect information an indefinite number of times and so I'm looking to implement a "while" loop to work around this.
In the case of the code below, I'm basically attempting to have it so that instead of the first ifelse entry I can enter into a loop by checking for the boolean value of "First_Name.isalpha():". However, I can't really think of a way to enter into it as when "First_Name.isalpha():" is true I don't need to enter into the loop as the entry is correct. When it's false, we skip over the loop altogether without having the entry corrected.
That basically prompts the question of whether or not there is a way to enter into a loop for when a boolean value is false. Or, if there's another creative solution that I'm not considering.
Thanks,
A Novice Coder
NewContact = "New Contact"
def NewEntry(NewContact):
# Obtain the contact's information:
First_Name = input("Please enter your first name: ")
Last_Name = input("Please enter your last name: ")
Address = input("Please enter your street address: ")
City = input("Please enter your city of residence: ")
State = input("Please enter the 2 letter abbreviation of your state of residence: ")
ZipCode = input("Please enter your zip code: ")
Phone_Number = str(input("Please enter your phone number: "))
# Ensure all information inputted is correct:
if First_Name.isalpha():
First_Name = First_Name.strip()
First_Name = First_Name.lower()
First_Name = First_Name.title()
else:
First_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
if Last_Name.isalpha():
Last_Name = Last_Name.strip()
Last_Name = Last_Name.lower()
Last_Name = Last_Name.title()
else:
Last_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
# Organize inputted information:
NewContact = Last_Name + ", " + First_Name
FullAddress = Address + " " + City + ", " + State + " " + ZipCode
# Return information to writer to ensure correctness of information
# Write information onto document
TheFile = open("AddressBook", "w")
TheFile.write(str(NewContact) + "\n")
TheFile.write(str(FullAddress) + "\n")
TheFile.write(str(Phone_Number) + "\n")
TheFile.close()
NewEntry(NewContact)
You're looking for the not operator, which inverts a boolean value:
>>> not False
True
>>> not True
False
>>> not "".isalpha()
True
>>> not "abc".isalpha()
False
You can tack it on the front of any expression that's a valid condition for an if or while.
Use this structure
invalid = True
while invalid:
## get inputs
## validate inputs
## set invalid accordingly