How to switch functions in a while loop python - python

I am trying to make a program that adds, delete and can view dishes a user enters. It seems very simple however, I run into issues with my while loop. When I type in add I am able to add items to my list, however, when I type view the addDish function keeps on looping. I thought I fixed it with my if statement but there's something missing ... !
dish_list = []
user_input = ''
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
user_input = input("Please enter a command: ")
while True:
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)

Instead of having a while loop, you should call a function that asks for user input once previous input has been handled.
dish_list = []
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def get_input():
user_input = input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
getInput()
getInput()

A bit cleaner:
dish_list = []
def add_dish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def view_dish(dish_list):
# for dish in dish_list:
# print(dish)
print('\n'.join(dish_list))
while True:
user_input = input("Please enter a command: ")
if user_input == 'add':
add_dish(dish_list)
elif user_input == 'view':
view_dish(dish_list)
else:
print("Unknown command %s" % user_input)

Your variable user_input never gets set back to empty, so you can never enter a new command since it just takes the last entry you input to user_input, which would be the dish type read in the addDish function. Also, your call to addDish has an extra parameter. I also recommend throwing everything in a main method.
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def main():
dish_list = []
while True:
user_input = ''
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
main()

Here's a fixed version of the above code snippet:
def addDish(dish_list):
user_input = raw_input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for dish in dish_list:
print(dish)
dish_list = []
while True:
user_input = raw_input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
elif user_input == 'exit':
print('Over!')
break
else:
print('Wrong entry. Retry...')
Execution output:
$python so.py
Please enter a command: add
Please type the dish you want: Bread
Please enter a command: add
Please type the dish you want: Burger
Please enter a command: view
Bread
Burger
Please enter a command: foo
Wrong entry. Retry...
Please enter a command: exit
Over!
$

Related

An attribute error appeared when I tried to make a code allowing a user to create their own record

I am trying to allow a user to create their own record and output their record. When I run my code this message appears:
File "filename", line 25, in
record = user_class(fact_list)
File "filename", line 17, in init
self.feild_list[i]=feild_list[i]
AttributeError: 'user_class' object has no attribute 'feild_list'
This is my code:
user_list = []
choice=input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
for i in range(record_length):
self.feild_list[i]=feild_list[i]
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice=input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" or choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
In user_class.__init__() you don't have a self.feild_list variable. I assume you want one (see below). Alternatively you could just clone the list self.feild_list = feild_list[:].
user_list = []
choice = input("Enter choice (Y/N):")
if choice == "Y":
feild_list = []
record_length = int(input("Enter record length:"))
for i in range(record_length):
feild = input("Enter a feild:")
feild_list.append(feild)
class user_class():
def __init__(self, feild_list):
self.feild_list = []
for i in range(record_length):
self.feild_list.append(feild_list[i])
fact_list = []
for i in range(len(feild_list)):
fact = input("Enter a fact:")
fact_list.append(fact)
record = user_class(fact_list)
user_list.append(record)
print(user_list)
choice = input("Enter choice (Y/N):")
elif choice == "N":
print("Program Ended.")
else:
while choice != "Y" and choice != "N":
print("Invalid choice")
choice = input("Enter choice (Y/N):")
Also fixed the logic error in the choice retry. Consider moving that retry logic to the start so always get a valid choice:
while True:
choice = input("Enter choice (Y/N):")
if choice in "NY":
break
print("Invalid choice")

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!

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]

Q2() Function keeps looping

I'm making a simple menu for students to see and admins to login.
def main():
while(True):
print("1. Display Class")
print("2. Admin Login")
a = input("Please enter a choice or q to quit: ")
if a=="1":
Q1()
elif a=="2":
Q2()
elif a=="q":
break
def Q1():
print('Class A in Room 1, Class B in Room 2')
def Q2():
passwd = {'admin1': Q2}
user_input = input("Enter administrator password: ")
if user_input in passwd:
func = passwd[user_input]
func()
print ('Success')
else:
print("Incorrect password")
main()
print("Goodbye")
The Q2() function does not work as I intended. It keeps looping "Enter administrator password: " when password is entered correctly.
Correct?
def Q2():
passwd = {'admin1','admin2','admin3'}
user_input = input("Enter administrator password: ")
if user_input in passwd:
print ('Success')
else:
print("Incorrect password")

Categories

Resources