How to check if contact is always in the list - python

import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','a') as file:
file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I add to if else function, one to save the contact list and one to just update it with the new contact. But When I run it I still get the old contact that where already saved. Any ideas on how to fix it to only append the new contacts to the already saved txt file.
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','a') as file:
file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
I just changed the "w" in choice 7 to "a" to append the new contact but I still get all the old one in the new save. Any ideas.

Related

How to have input in Python only take in string and not number or anything else only letters

I am a beginner in Python so kindly do not use complex or advanced code.
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Print \n 7. Exit \n Enter "))
#I have already tried
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
sort_contact = input("Enter yes to print your contact")
if sort_contact in contact:
confirm = input("Do you want to print your contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
strs = [display_contact]
print(sorted(strs))
else:
print("Phone book is printed.")
else:
break
I tried but keep getting errors and I can't fiugre out how to make it only take string or letter as input and not numbers.
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
it is not working my code still accepts the ans in integer and string.
I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.
You can use a regex with re.fullmatch:
import re
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
Or use the case-insensitive flag: re.fullmatch(r'[a-z]+', name, flags=re.I):
As you noted that you are a beginner, I'm adding this piece of code
as a "custom-made" validation, just so you can check how you would do something like this by your own .
Note: #mozway gave a MUCH BETTER solution, that is super clean, and I recommend it over this one.
def valid_input(input: str):
# Check if any char is a number
for char in input:
if char.isdigit():
print('Numbers are not allowed!')
return False
return True
while True:
name = input("Enter data:")
if valid_input(name):
break
I found this answer from another website:
extracted_letters = " ".join(re.findall("[a-zA-Z]+", numlettersstring))
First, import re to use the re function.
Then let's say that numlettersstring is the string you want only the letters from.
This piece of code will extract the letters from numlettersstring and output it in the extracted_letters variable.

Unable to pass/exit a python function

Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!

How do I print out a set of information at once in python?

I'm a python beginner I tried making a contact book program but this is the problem, I
want to add search-like feature so after I add a contact name, phone number, email and store
it to another file(contact.txt) I want to access it and print it via search.
example:
Name: Johan
Phone: 036902480157
Email: Johan#Email.com
I want to access all the information regarding Johan just by typing his contact name or his phone number, how I can do that?
note: I want to print the name, phone number, and email in each different line
Thanks in advance
my code
import os
def head():
print("")
print("========================")
print(" Contact Book ")
print("========================")
def restart():
response = input("\nOpen menu again? (yes/no): ").lower()
if response == "yes":
task()
else:
print("\nSee You next time!")
def task():
head()
done = False
print('''1. Add Contact
2. Search
3. View Contact List
4. Delete All Contact
5. Exit''')
while not done:
task = input("\nWhat do You want to do? (1-5):")
if task == "1":
print("\nAdding a new contact!")
with open('contact.txt', 'a') as f:
name = input("Name: ")
phone = input("Phone Number: ")
if not phone.isnumeric():
while not phone.isnumeric():
print("Invalid input, please enter only a number!")
phone = input("Phone Number: ")
email = input("Enter an email: ")
f.writelines(('\n',('=' * 15),'\nName: ',name,
'\nPhone: ',phone,'\nEmail: ',email,'\n',('=' * 15)))
print("\nContact is saved!")
done = True
restart()
elif task == "2":
with open('contact.txt', 'r') as f:
search = input("\nSearch: ")
for i in f:
if search in i:
print(i)
else:
print("\nNo info was found!")
done = True
restart()
elif task == "3":
if os.path.getsize('contact.txt') == 0:
print("\nNo contact info available!")
else:
with open('contact.txt', 'r') as f:
print("\nAll Contact Info")
for i in f:
print(i,end="")
done = True
restart()
elif task == "4":
with open('contact.txt', 'w') as f:
print("\nSuccesfully deleted all contact info!")
done = True
restart()
elif task == "5":
print("See You next time!")
break
else:
print("Invalid input please enter a single number from 1 to 5")
restart()
task()
Adding a contact and then searching for this contact prints:
Adding a new contact!
Name: mrd
Phone Number: 99
Enter an email: the#ff.com
Contact is saved!
...
What do You want to do? (1-5):2
Search: mrd
Name: mrd
No info was found!
which is inaccurate as you just fount the name. What you want to do is save all the contact info in the same line in the contacts.txt so when you search for a number or a name it will give you back that line and then you can print it as you want.
Alternatively you could hold an in memory dictionary that you persist on exit in a json as suggested and you load when you start your program
In answer to the comment
if task == "1":
print("\nAdding a new contact!")
# TODO make sure no commas in the input!
name = input("Name: ")
phone = input("Phone Number: ")
while not phone.isnumeric():
print("Invalid input, please enter only a number!")
phone = input("Phone Number: ")
email = input("Enter an email: ")
with open('contact.txt', 'a') as f:
f.write(','.join([name, phone, email]) + '\n')
print("\nContact is saved!")
done = True
restart()
elif task == "2":
search = input("\nSearch: ")
with open('contact.txt', 'r') as f:
for i in f:
if search in i:
for caption, data in zip(['Name:', 'Phone:', 'Email:'],
i.split(',')):
print(caption, data)
break # contact was found don't go to the else!
else:
print("\nNo info was found!")
done = True
restart()

i need multiple input to run main function phonebook python

I am having trouble writing a program to repeat input part. for instance
input 1 ___run add_contact()
again ask for input
input 4____run disp_contact()
...
...
I've never written a long code! :\
I'm totally begginer! and learning a bit of Python in my spare time
my mentor said you should define several functions and put them in a main function which get input.
so If anyone can tell me why I get stuck like this I would appreciate it.
contact={}
print(''' phone book
1. add contact
2.delete contact
3.search contact
4.display all
5.Quit''')
def add_contact():
name=input('enter the name: ')
number=input('enter the number: ')
contact[name]=number
print(name, 'added to phone book!')
def del_contact():
name=input('enter the name: ')
while name not in contact:
print("not found! try again" )
name=input('enter again: ')
else:
print(name,' deleted')
del contact[name]
name=False
def search_contact():
name=input('enter the name: ')
while name not in contact:
print('not found!')
name=input('enter again: ')
else:
print(name, 'number is :', contact[name])
def disp_contact():
if len(contact)>0:
print('phone book contacts are: ')
for i in contact:
print(i, end=' ')
else:
print('phone book is empty!')
def main_def(num):
if num==1:
add_contact()
elif num==2:
del_contact()
elif num==3:
search_contact()
elif num==4:
disp_contact()
elif num==5:
print('bye bye')
x=int(input(' enter a number: '))
main_def(x)
You may wrap the main_def in a while True, and use exit(O) to quit properly when 5 is given
def main_def(num):
if num == 1:
add_contact()
elif num == 2:
del_contact()
elif num == 3:
search_contact()
elif num == 4:
disp_contact()
elif num == 5:
exit(0)
while True:
x = int(input(' enter a number: '))
main_def(x)
Note
For del_contact and search_contact, you don't need the else just put after like this
def del_contact():
name = input('enter the name: ')
while name not in contact:
print("not found! try again")
name = input('enter again: ')
print(name, ' deleted')
del contact[name]

Basic option menu is failing - help needed

I am creating a basic phonebook program that can perform operations (add new, update, delete, lookup and exit). I have the first option as add entry and the second as delete entry. Every time the user completes an action, the option to select an action again should come up. When the user selects for the second time, it brings back to the first item instead of the selection; For example; 1 is to add new contact, 2 is to delete new contact. User selects 1, adds new contact is asked to select another option, chooses 2 but the code for option 1 runs again to add new instead of delete.
print("Please select an option from the main menu :\n")
def print_menu():
print("1 : Add New Entry")
print("2 : Delete Entry")
print("3 : Update Entry")
print("4 : Lookup Number")
print("5 : QUIT")
print()
print_menu()
while 1 == 1:
try:
menuOption = int(input())
break
except:
print("Invalid! Please choose an option between 1 and 5.")
while menuOption not in(1,2,3,4,5):
print("Invalid! Please choose an option between 1 and 5.")
try:
menuOption = int(input())
break
except:
print("Invalid! Please choose an option between 1 and 5.")
###the above works perfect to set menu and restrict entry
phonebook = {}
#while menuOption != 5:
#menuOption = int(input("Enter your selection (1-5): "))
while 1 == 1 :
if menuOption == 1: #
print("\nNEW CONTACT")
while True:
name = input("Contact Name : ")
if name.replace(' ','').isalpha():
break
print('Please enter a valid name.')
while True:
try:
number = int(input("Contact Number : "))
if number:
break
except:
print("Please enter a valid number.")
if number in phonebook:
print("Contact already exists. Duplicates are not allowed.\n")
else:
phonebook[number] = name
print("Success! New contact has been added.\n")
print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5 \n")
try:
option = int(input())
except:
print("Please enter a numeric value between 1 and 5 \n")
elif menuOption == 2: ##delete
print("\nDELETE CONTACT")
name = input("Contact Name : ")
if name in phonebook:
del phonebook[name]
print(name, "has been removed from your contacts.")
else:
print("Contact not found.")
print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5 \n")
try:
option = int(input())
except:
print("Please enter a numeric value between 1 and 5 \n")
Welcome to the stack, rainyday! On looking at/running your code, the message to remind the user to enter between one and five came up a bit more than I expected, along with random other errors that you probably just haven't coded for yet. I would suggest that defining more functions (for the menu options) and structuring your code a bit more would make your code easier to read and follow.
Below (which is not complete or error-free btw), I re-structured your code so that when main() is called, the Phone Book menu options shows and the user can choose another option. Instead of using long "else-if"/elif s between the various functions, the various menu routines are neatly organised in one while statement in the main() function and the choices are organised into 5 different functions: add()/delete() etc. (I put dummy code into the update/lookup/exit fns). I hope you find this helpful. I did find that if I entered a string when a digit was expected as input that it threw an error message. I inserted comments to assist.
Hope this helps
phonebook= []
def main():
print("\n\tPhone Book") #title
# main menu
print("\n\tMain Menu")
print("\t1. Add a contact")
print("\t2. Delete a contact")
print("\t3. Update a contact")
print("\t4. Look up")
print("\t5. Quit")
menuOption = int(input("\nPlease select one of the five options "))
while menuOption not in(1,2,3,4,5) :
## insert try/except error handling needed here to handle NaN ##
print("\nPlease insert a numeric option between 1 and 5")
menuOption =int(input())
while menuOption <=5:
mOpt =menuOption
if menuOption == 1:
Add(mOpt)
elif menuOption == 2:
Delete(mOpt)
elif menuOption == 3:
Update(mOpt)
elif menuOption == 4:
LookUp(mOpt)
elif menuOption == 5:
ExitPhone(mOpt)
else:
print("Invalid input! Please insert a value between 1 and 5")
# add contact
def Add(mOpt):
##Option 1
add = ""
contact = True
print("\n\tADD CONTACT")
while contact == True:
if mOpt == 1:
print("\nNEW CONTACT")
while True:
name = input("Contact Name : ")
if name.replace(' ','').isalpha():
break
print('Please enter a valid name.')
while True:
try:
number = int(input("Contact Number : "))
if number:
break
except:
print("Please enter a valid number.")
if number in phonebook:
print("Contact already exists. Duplicates are not allowed.\n")
else:
#item = name + number this won't be found in the delete function
phonebook.append(name)
phonebook.append(number)
#print(phonebook)
print("Success! New contact has been added.\n")
add = input("Would you like to add another? Y (yes) or N (no)")
add = add.lower()
if add=="yes" or add=="y":
contact = True
else:
contact = False
main()
# delete
def Delete(mOpt):
redel = ""
delcontact = True
print("\n\tDELETE CONTACT")
while delcontact == True:
if mOpt == 2:
print("Enter Contact Name:")
name = input("Contact Name : ")
if name in phonebook:
## insert code here to find associated number
## and concatenate it if you have created an 'item'
phonebook.remove(name) #removes name, leaves the number
print(name, "has been removed from your contacts.")
#print(phonebook)
else:
print("Contact not found.")
redel = input("Would you like to delete another? Y (yes) or N (no)")
redel = redel.lower()
if redel =="yes" or redel =="y":
delcontact = False
else:
delcontact = True
main()
def Update(mOpt):
if mOpt == 3:
print("\nUpdate function")
main()
def LookUp(mOpt):
if mOpt == 4:
print("\nLookUp function")
main()
def ExitPhone(mOpt):
if mOpt == 5:
print ("Exit?")
main()
main()
Your code checks the menuOption's value, but inputs option. Just change
option = int(input())
into
menuOption = int(input())

Categories

Resources