Exiting a For Loop & Enumeration (Python) - 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())

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)

How can I exit a while loop after the user inputs "0"? If user inputs anything else, I want it to continue

Write a Python program that will ask the user for the name of a movie. Add the movie entered to a list. Continue asking for a movie until the user enters ‘0’.
After all movies have been input, output the list of movies one movie per line.
This is what I've tried:
def main():
movies = []
while movies != 0:
movie = str(input("Enter the name of a movie: "))
if movie == 0:
break
if movie != 0:
movies.append(movie)
print("That's your list")
print(movies)
main()
movie = str(input("Enter the name of a movie: "))
if movie == 0:
break
if movie != 0:
movies.append(movie)
The idea is correct here. But there is one mistake. You are asking for a string input then checking if the string input is an integer.
Try to take a string input but compare it to another string.
if movie == "0":
break
Suggested Code
I changed your code your code up a bit too, much cleaner
def main():
movies = []
while "0" not in movies:
movies.append(str(input("Enter the name of a movie: ")))
print("That's your list")
print(movies[:-1])
main()
Use the break keyword to interrupt either a while or a for loop.
The code given by BuddyBob is not 100% correct because it will include the "0" in the list of movies (since it is first appended).
The code given by ALI NAQI is actually comparing with a lowercase 'o'.
I believe this would be the best way:
def main():
movies = []
while True:
movie = input("Enter the name of a movie: ")
if movie == "0":
break
else:
movies.append(movie)
print("That's your list")
print(movies)
main()
movie = str(input("Enter the name of a movie: "))
if movie == 0:
break
if movie != 0:
movies.append(movie)
This seems good but remember you are comparing string value (movie) with an integer like:
if movie == 0: #thats the mistake . now correct one is listed below
if movie == "o":
break
Hope you understood this.

Python error: "break is outside the loop"

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()

how to find user input value in the dictionary and display them, if it exists

MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# And another function here for the user menu
selection = input(MENU_PROMPT)
def movie_data():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def display():
print("movies =", end =" ")
for movie in movies:
print(movie['title'])
while selection != 'q':
if selection == "a":
movie_data()
elif selection == "l":
display()
elif selection == "f":
find = input("enter the movie title")
if find in movies:
print("movie found.", movies)
else:
print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??
I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)
You can make a search function which iterates over each element in the list and searches for the title attribute in dictionary.
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# And another function here for the user menu
selection = input(MENU_PROMPT)
def movie_data():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def display():
print("movies =", end =" ")
for movie in movies:
print(movie['title'])
def search(title):
for i in range(len(movies)):
if(movies[i]['title']== str(title)):
return movies[i]
return None
while selection != 'q':
if selection == "a":
movie_data()
elif selection == "l":
display()
elif selection == "f":
find = input("enter the movie title:")
movie = search(find)
if (movie):
print("movie found:", movie)
else:
print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
You have a list with dictionaries that contain title, director and year keys. You can loop through the list and search a match for the title, assuming the user inputs the title:
movies.append({
'title': "title",
'director': "director",
'year': "year"
})
for m in movies:
if m.get('title').lower().find("title") > -1:
print("true")
else:
print("false")

Is this code simplified? Should I use more functions?

So I'm working on this program that opens an external file and then runs through it to see if it contains specific information. Is there a way to simplify it or is the way it is now the most efficient way write this?
def printGender(alist):
if "Female" in alist:
print(alist)
print("Female Students")
def maleInfo(blist):
if "2010" in blist:
print(blist)
print("Students who enrolled in 2010")
def csc2010(clist):
if "CSC" in clist and "2010" in clist and "Female" in clist:
print(clist)
print("Female students who registered in CSC in 2010")
def main():
ref = open("file1.txt","r")
studentList = ref.readlines()
ask = 10
while ask != 0:
print("1) print all female info")
print("2) display all male info from 2010")
print("3) display female students who registered for CSC in 2010")
ask = int(input("Enter option 1, 2, 3 or 0 to quit: "))
if ask == 1:
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
elif ask == 2:
for i in range(len(studentList)):
blist = studentList[i]
maleInfo(blist)
elif ask == 3:
for i in range(len(studentList)):
clist = studentList[i]
csc2010(clist)
elif ask == 0:
print("You chose to quit")
break
else:
print("Not a Valid input")
continue
ref.close()
main()
Is there a way to simplify this code so that I don't create three seperate list in the main function.
if ask == 1:
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
elif ask == 2:
for i in range(len(studentList)):
blist = studentList[i]
maleInfo(blist)
elif ask == 3:
for i in range(len(studentList)):
clist = studentList[i]
csc2010(clist)
elif ask == 0:
print("You chose to quit")
break
else:
ect...
I was curious to see if there was a shorter way to get the same result. Maybe using a function that runns that section of code but I'm not sure how to do that.
Some problems to be aware of:
the construct
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
is pretty nasty; if you actually need i you should use
for i, student in enumerate(student_list):
print_gender(student)
otherwise
for student in student_list:
print_gender(student)
Your functions are poorly named; they don't do what they say they do! printGender prints female students, printMale prints students from 2010, etc. Similarly, your variable names are poorly chosen; alist is not a list of students, it is a single student.
You seem to have a text string per student, at a guess something like 2009, 176915, Jones, Susan, Female, CSC; but you make no attempt to separate out fields. This will lead to annoying problems with students like 2009, 292010, Male, Jill, Female, RCSCA who will be reported as a student in both 2009 and 2010 (false match on student number), and both female and male (false match on last name), and in CSC (false match on course name). You really need to use a better data format - whether .csv or .json or a database, anything which returns named fields - to solve this problem.
Your search options are non-orthogonal and limited to pre-coded options; you have no way of searching, for example, for all CSC students in 2007 without rewriting your program.
Fixing these problems leads you to something like
import json
def record_print_format(record):
return "{Year:4} {Id:6} {Gender:6} {Firstname:>20} {Lastname:<20} {Course:6}".format(**record)
def show_records(records, format_fn=record_print_format):
for r in records:
print(format_fn(r))
num = len(records)
print("{} records:".format(num))
def filter_records(records, field, value):
return [r for r in records if r[field] == value]
def match_year(records, year):
return filter_records(records, "Year", year)
def match_gender(records, gender):
return filter_records(records, "Gender", gender)
def match_course(records, course):
return filter_records(records, "Course", course)
def main():
with open("student_list.json") as studentfile:
all_students = json.load(studentfile)
records = all_students
while True:
print("1: Filter by year")
print("2: Filter by gender")
print("3: Filter by course")
print("8: Show results")
print("9: Clear filters")
print("0: Exit")
option = input("Please pick an option: ").strip()
if option == "1":
year = input("Which year? ").strip()
records = match_year(records, year)
elif option == "2":
gender = input("Which gender? [Male|Female] ").strip()
records = match_gender(records, gender)
elif option == "3":
course = input("Which course? ").strip()
records = match_course(records, course)
elif option == "8":
show_records(records)
elif option == "9":
records = all_students
elif option == "0":
print("Goodbye!")
break
else:
print("I don't recognize that option.")
if __name__=="__main__":
main()

Categories