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]
Related
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.
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.
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!
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 try to create an object saving account and store it in a dictionary and this works fine but when i try to use the object of the dictionary with an method i get an error, so im not sure what im doing wrong?
I hope you guys understand what im trying to say and if somebody has an easier way to get the what i look for please let me know.
thanks
def print_accounts(accounts):
print(accounts)
pass
def add_savingaccount(account_name, iban, name, address, accounts):
print(accounts, name)
accounts[name]=account_name
account_name = SavingAccount(iban , name, address)
pass
def get_savingaccount(accounts, name):
current_account = (accounts.get(name, 'Name nicht verfügbar'))
print(current_account)
user_answer = int(input("What do you want to do 1. get credit, 2. withdraw, 3. deposit, 4. close account, 5. open account, 6. change rate, 7. sleep: "))
if user_answer == 1:
current_account.encode().decode().show_credit()
elif user_answer == 2:
current_account.withdrawn(int(input("How much do you want to withdraw: ")))
elif user_answer == 3:
current_account.deposit(int(input("How much do you want to deposit: ")))
elif user_answer == 4:
current_account.close_account()
elif user_answer == 5:
current_account.open_account()
elif user_answer == 6:
current_account.change_interest_rate(int(input("How much do you want to deposit: ")))
elif user_answer == 7:
current_account.sleep(int(input("Sleep time: ")))
pass
def load_accounts(accounts, filename):
with open(filename, "r") as file:
accounts = json.load(file)
#for key in phone_book:
# accounts[key]=phone_book[key]
accounts.update(accounts)
pass
def save_accounts(accounts, filename):
with open(filename, "w+") as new_file:
json.dump(accounts, new_file, separators=(',',':'))
pass
def print_menu():
print ('1. Print Phone Numbers')
print ('2. Add a SavingAccount')
print ('4. Get SavingAccount')
print ('5. Load accounts')
print ('6. Save accounts')
print ('7. Quit')
print()
accounts = {}
menu_choice = 0
print_menu()
while True:
menu_choice = int(input("Type in a number (1-7): "))
if menu_choice == 1:
print_accounts(accounts)
print_menu()
elif menu_choice == 2:
print("Add Name and Number (Valid IBAN gets transferred)")
account_name = input("Accountname: ")
name = input("Name: ")
iban = "CH 54 3242 3345 5342 4235"
address = input("Address: ")
add_savingaccount(account_name, iban, name, address, accounts)
print_menu()
elif menu_choice == 4:
print("get_savingaccount")
name = input("Name: ")
get_savingaccount(accounts, name)
print_menu()
elif menu_choice == 5:
filename = input("Filename to load: ")
load_accounts(accounts, filename)
print_menu()
elif menu_choice == 6:
filename = input("Filename to save: ")
save_accounts(accounts, filename)
print_menu()
elif menu_choice == 7:
break
else:
print_menu()