Python error: "break is outside the loop" - python

This is a program to book tickets for a movie online. The output shows "break is outside the loop". What should I change to correct this?
viewers = []
class TenetMovie:
def __init__(self,movie_name):
self.movie_name=movie_name
def ticket_buyer(self):
print('at any point if you want to exit press "q"')
your_name = input("your name : ")
if your_name == 'q':
break
no_of_tickets = input("how many tickets : ")
if no_of_tickets == 'q':
break
seats = input("select the seats : ")
if seats == 'q':
break
viewers.extend((self.movie_name,your_name,no_of_tickets,seats))
for viewer in viewers:
print("\nMovie : "+self.movie_name)
print("name : "+your_name)
print("Number of Tickets : "+no_of_tickets)
print("Seat Number : "+seats)
break
movie_tickets=TenetMovie(input("Which movie would you like to watch : "))
movie_tickets.ticket_buyer()

use return not break when you want to exit a function.

You have to use return not break Because you are not working with a loop, a function.
viewers = []
class TenetMovie:
def __init__(self,movie_name):
self.movie_name=movie_name
def ticket_buyer(self):
print('at any point if you want to exit press "q"')
your_name = input("your name : ")
if your_name == 'q':
return
no_of_tickets = input("how many tickets : ")
if no_of_tickets == 'q':
return
seats = input("select the seats : ")
if seats == 'q':
return
viewers.extend((self.movie_name,your_name,no_of_tickets,seats))
for viewer in viewers:
print("\nMovie : "+self.movie_name)
print("name : "+your_name)
print("Number of Tickets : "+no_of_tickets)
print("Seat Number : "+seats)
break
movie_tickets=TenetMovie(input("Which movie would you like to watch : "))
movie_tickets.ticket_buyer()

Related

Trying to pass in the list of name and number from my contact python code but only save the very last input

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':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#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 have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)

Trouble with saving and loading dictionary with class instances using pickle

New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()

Exiting a For Loop & Enumeration (Python)

I'm new to Python and working on a bootcamp project... and I'm absolutely making it harder than it needs to be...
What I'm looking to ultimately do, is create the following:
Name: Titanic \n
Director: Spielberg \n
Year: 1997 \n\n
Name: The Matrix \n
Director: Waskowskis \n
Year: 1996 \n\n
AFTER I've added them with the "(A)dd Movie function... So, firstly, I can't seem to 'exit' the For Loop... once I run it, it just repeats indefinitely... and beyond that, I'm not able to get the formatting correct if I try to use "enumerate".
Here's my code: (the portion I'm talking about is under the "def show_movies" function:
import sys
import random
import os
movies = []
def menu():
global user_input
print("Welcome to 'The Movie Program!!'")
print("(A)dd movie to your list")
print("(L)ist movies you've added")
print("(S)earch for movies in your list")
user_input = str(input("Which function would you like to do?:\n\n""Selection: ").capitalize())
while user_input != 'Q':
if user_input == 'A':
add_movies()
elif user_input == 'L':
show_movies()
elif user_input == 'A':
search_movies()
else:
print("\n\n--Unknown command--Please try again.\n")
print("Welcome to 'The Movie Program!!'")
print("(A)dd movie to your list")
print("(L)ist movies you've added")
print("(S)earch for movies in your list")
user_input = str(input("Which FUNCTION would you like to do?:\n\n""Selection: ").capitalize())
def add_movies():
#name = (input('What is the title of the movie?: ').title())
#director = str(input("Who was the director of this movie?: ").title())
year = None
while True:
try:
name = (input('What is the title of the movie?: ').title())
director = str(input("Who was the director of this movie?: ").title())
year = int(input("What was the release year?: "))
except ValueError:
print("Only numbers, please.")
continue
movies.append({
"name": name,
"director": director,
"year": year
})
break
menu()
add_movies()
def show_movies():
for movie in movies:
print(f"Name: {movie['name']}")
print(f"Director: {movie['director']}")
print(f"Release Year: {movie['year']}\n")
#continue
#break
def search_movies():
movies
print("This is where you'd see a list of movies in your database")
menu()
The problem is in your while user_input != 'Q': loop.
If user_input is equal to L, then it calls show_movies(), but doesn't ask for more input. It just goes round and round the while loop calling show_movies() each time.
You should input user_input again each time through the loop, not only in your else clause.
while user_input != 'Q':
if user_input == 'A':
add_movies()
elif user_input == 'L':
show_movies()
elif user_input == 'A':
search_movies()
else:
print("\n\n--Unknown command--Please try again.\n")
print("Welcome to 'The Movie Program!!'")
print("(A)dd movie to your list")
print("(L)ist movies you've added")
print("(S)earch for movies in your list")
# the next line is now outside your `else` clause
user_input = str(input("Which FUNCTION would you like to do?:\n\nSelection: ").capitalize())

How do I loop the answers so that if the user inputs 1,2 or 3 and they carry out the function, it will ask them the choices again?

Allows the user to submit a pairing
Allows the user to delete a pairing
Allows the user to submit final pairings
How can I edit the program so that the user (after completing 1, 2 or 3) i asked the same question again? (Question = user_selection)
clue_list = {'#':'A', '%':'N', '*':'M'}
user_selection = input('What would you like to do? 1.Submit a letter or symbol pairing, 2.Delete a letter/symbol pairing, 3. Submit Final Answers ')
while user_selection != '3':
if user_selection == '1':
userkey = input('Please enter a symbol to add: ')
uservalue = input('Please enter a letter to add: ')
if userkey in clue_list:
print('This symbol has already been matched. Please try again.')
else:
clue_list[userkey] = uservalue
print(clue_list)
if user_selection == '2':
user_delete_input = input('What letter/symbol would you like to delete? (Please enter symbol to delete the pairing ')
if user_delete_input in clue_list:
del clue_list[user_delete_input]
print('That letter/symbol has been deleted.')
else:
print('Error: That letter/symbol has not been found in file.')
user_submit1 = input('Would you like to submit more pairings? Yes/No ')
if user_submit1 == 'Yes':
function_result2 = submit(clue_list)
else:
if user_submit1 == 'No':
print('...')
The crux of your question is getting the selection process to repeat. You can do so quite easily if you learn to abstract away parts of your code with functions. For example, a possible answer to your question looks like:
while True:
user_selection = input(msg_ask).strip()
if user_selection == '1': add_symbol(clue_list)
elif user_selection == '2': remove_symbol(clue_list)
elif user_selection == '3': break
Where we've defined the functions add_symbol and remove_symbol like so:
clue_list = {'#':'A', '%':'N', '*':'M'}
msg_ask = '''
What would you like to do?
1. Submit a letter or symbol pairing,
2. Delete a letter/symbol pairing,
3. Submit Final Answers
'''
def add_symbol(clue_list):
userkey = input('Please enter a symbol to add: ')
uservalue = input('Please enter a letter to add: ')
if userkey in clue_list:
print('This symbol has already been matched.')
else:
clue_list[userkey] = uservalue
print(clue_list)
def remove_symbol(clue_list):
msg = 'What letter/symbol would you like to delete? (Please enter symbol to delete the pairing) '
user_delete_input = input(msg)
if user_delete_input in clue_list:
del clue_list[user_delete_input]
print('That letter/symbol has been deleted.')
else:
print('Error: That letter/symbol has not been found in file.')
You'll notice how the first code block is much easier to read.

Invalid syntax error on the elif statement

I'm writing this program that lets users choose an option to display, change,add, remove, write or quit
I keep getting invalid syntax error on this elif statement in my program and i dont know why?
DISPLAY = 'D'
CHANGE = 'C'
ADD = 'A'
REMOVE = 'R'
WRITE = 'W'
QUIT = 'Q'
#main function
def main ():
print()
print()
print('\t Wombat Valley Tennis Club')
print('\t Member Register')
print('\t =======================')
main_dic = {}
with open ('wvtc_data.txt','r')as x:
for line in x:
line = line.rstrip ('\n')
items = line.split (':')
key,value = items[0], items[1:]
main_dic[key] = values
choice = input('choice: ')
while choice != QUIT:
choice = get_menu_choice()
if choice==DISPLAY:
display(main_dic)
elif choice==CHANGE:
change(main_dic)
elif choice== REMOVE:
remove (main_dic)
elif choice==WRITE:
write(main_dic)
def get_menu_choice():
print()
print("\t\t Main Menu")
print()
print('\t<D>isplay member details')
print('\t<C>hange member details')
print('\t<A>dd a new member')
print('\t<R>emove a member')
print('\t<W>rite updated details to file')
print('\t<Q>uit')
print()
print('Your choice (D, C, A, R, W OR Q)?\t[Note: Only Uppercase]')
print()
choice = input("Enter your choice: ")
while choice < DISPLAY and choice < CHANGE or choice > QUIT:
choice = input ('Enter your choice: ')
return choice
def display(main_dic):
name = input('Type the name of the member:')
print()
print (main_dic.get(name, 'not found!'))
print()
print()
def change(main_dic):
name=input("Enter the member number")
print()
print(main_dic.get(name,'not found!'))
print()
NAME = 1
EMAIL = 2
PHONE = 3
print('Please select')
print('==============')
print('Change Name<1>')
print('Change E-mail<2>')
print('Change Phone Number<3>')
print()
if choose == NAME:
new_name = input('Enter the name: ')
print()
print("Data has been changed")
main_dic[name][0]=new_name
print (mem_info[name])
print()
elif choose == EMAIL:
new_email=input('Enter the new email address:')
print ('Email address has been changed')
#change the data
main_dic[name][1]=new_email
print(mem_info[name])
print()
elif choose == PHONE:
new_phone = int (input('Enter the new phone number'))
print ("phone number has been changed")
main_dic[name][2]=new_phone
print(main_dic[name])
print
def write(main_dic):
print()
name = input ("Enter the name of a member:")
print()
print (mem_info.get(name,'Not found!'))
print()
main()
main()
Also any help or suggestions in making this code work are appreciated.
It's a formatting problem. The elifs have to start in the same column as the if to which they belong.
Example
if something:
do_somtething()
elif something_else:
do_the_other_thing()

Categories