I cannot access the movies list I created (python) - python

I am currently having issues having my program access my list after the user enters a menu option. the only entry being read is the 1939 entry, any other year will only present the "enter a valid year" option. Another issue is when displaying categories, only the first 2 drama films will pop up, every other category doesn't work when asked for. It also will not display the entire list when I call to display it (only the 1939 entry would pop up). Any help would be very appreciated!
movies = [[1939,'Gone With the Wind','drama'],
[1943,'Casablanca','drama'],
[1965,'The Sound of Music','musical'],
[1969,'Midnight Cowboy','drama'],
[1972,'The Godfather','drama'],
[1973,'The String','comedy'],
[1977,'Annie Hall','comedy'],
[1981,'Chariots of Fire','drama'],
[1984,'Amadeus','historical'],
[1986,'Platoon','action'],
[1988,'Rain Man','drama'],
[1990,'Dances with Wolves','western'],
[1992,'Unforgiven','western'],
[1993,'Schindlers List','historical'],
[1994,'Forrest Gump','comedy'],
[1995,'Braveheart','historical'],
[1997,'Titanic','historical'],
[1998,'Shakespeare in Love','comedy'],
[2001,'A Beautiful Mind','historical'],
[2002,'Chicago','musical'],
[2009,'The Hurt Locker','action'],
[2010,'The Kings Speech','historical'],
[2011,'The Artist','comedy'],
[2012,'Argo','historical'],
[2013,'12 Years a Slave','drama'],
[2014,'Birdman','comedy'],
[2016,'Moonlight','drama'],
[2017,'The Shape of Water','fantasy'],
[2018,'Parasite','comedy']]
menu = """
1 - Display winning movie for a selected year
2 - Display movie and category for a selected year
d - Display entire movie list
dc - Display movies in a selected category - year and title
q = quit
"""
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[1]:
print("The winning movie in ", year," was: ", m[1])
else:
print("Input a valid year")
break
elif option == "2":
year = int(input("Please enter a valid year: "))
for m in movies:
if year == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
else:
print("Please enter a valid year")
break
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
break
elif option == "dc":
cat = input("Please enter a valid category")
for m in movies:
if cat == m[2]:
print(m[0], m[1])
else:
print("Please enter a valid category")
break
else:
print()
print("Please select a valid option")

At m[1] pulls movie name and not year.
Converting year input to integer and comparing.
if int(year) == m[0]:
Also, Breaks are used improperly. for display option index are not correctly used.
print(m[0], m[1], m[2])
Corrected Code
while True:
print(menu)
option = input("Please enter a valid menu option from above: ")
if option in 'qQ':
print("Ending program")
break
elif option == "1":
year = input("Please enter a valid year: ")
print(year)
for m in movies:
if int(year) == m[0]:
print("The winning movie in ", year," was: ", m[1])
elif option == "2":
year = input("Please enter a valid year: ")
for m in movies:
if int(year) == m[0]:
print("The winning movie was: ", m[1], "and its category was: ", m[2])
elif option == "d":
for m in movies:
print(m[0], m[1], m[2])
elif option == "dc":
cat = input("Please enter a valid category : ")
for m in movies:
if cat == m[2]:
print(m[1], m[2])
else:
print("Please select a valid option")

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)

If a user checks out 5 copies of book1 and returns 3 returns 2 and then returns 1 more it allows it even if it exceeds the original amount of copies

if you choose to return a book at the start of the program, without checking out any books,
then it won't allow the return (intended). So say the user wants to check out 5/10 copies of
book1. It checks them out and subtracts them from the copies on shelf. They choose to return
3 one day, and 2 another day. (For testing purposes) the day after that, they return another
copy of book1, which is more than they checked out. It appends it to the book1.borrow aka
num of copies. It should not allow the user to return more copies than the original numbr of copies. So this is what I have in my main module. I can add the class LibraryBook if
needed.
from LibraryBook import *
book1 = LibraryBook()
book1.title = "not set"
book1.year = "no se"
book1.author = "set not"
book1.borrow = 10
book2 = LibraryBook()
book2.title = "tes ton"
book2.year = "es on"
book2.author = "ton tes"
book2.borrow = 8
selection = 0
amount = 0
amount1 = 0
while selection != 5:
print("Select an option")
print('1 - Borrow a book')
print('2 - Return a book')
print('3 - See info on available books')
print('4 - Exit')
print()
selection = int(input("What would you like to do? "))
print()
if selection == 1:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Enter the book number. "))
print()
if bookNum == 1:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book1.borrow) and (amount > 0):
book1.borrowed(amount)
else:
print("We only have", book1.borrow, "copies available.")
print()
elif bookNum == 2:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book2.borrow) and (amount > 0):
book2.borrowed(amount)
else:
print("We only have", book2.borrow, "copies available.")
print()
else:
print()
print("That book is not here. Enter 1 or 2. ")
print()
if selection == 2:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Which book would you like to return? "))
print()
if bookNum == 1:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book1.returned(amount1)
print()
elif book1.borrow == book1.borrow:
print("Invalid number of copies. Count the books and try again ")
print()
else:
print("You only checked out", amount)
print()
elif bookNum == 2:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book2.returned(amount1)
print()
elif book2.borrow == book2.borrow:
print("You did not check out this book.")
print()
else:
print("You only checked out", amount)
print()
else:
print("Invalid selection. Choose book 1 or book 2.")
print()
if selection == 3:
print()
print("Book 1:")
print(book1.__str__())
print()
print("Book 2:")
print(book2.__str__())
print()
if (selection <= 0) or (selection >= 5):
print("Invalid selection. Enter a number 1-4. ")
print()
if selection == 4:
break
I'm not the best programmer but I think I made and example here
Ofc is not the best I made it larger for you to understand, there are some bugs like when asked for book if u give bigger then 2 will break but I let you fix it ;D
import sys, os, time, re
class LibraryBook(object):
def __init__(self, title, year, author, borrow):
self.title = title
self.year = year
self.author = author
self.borrow = borrow
def borrow_add(self, amount: int):
self.borrow += amount
def left(self):
return self.borrow
def get_title(self):
return self.title
def borrow_sell(self, amount: int):
self.borrow -= amount
def get_book_info(self):
val = f'''
Book Title: {self.title}
Book Year: {self.year}
Book Author: {self.author}
Left in stock: {self.borrow}
'''
return val
book1 = LibraryBook('Prison Break', 2016, 'My House', 8)
book2 = LibraryBook('Hello', 1999, 'NO one', 10)
###########
#That is so you can do book3,4,5 etc.. without write in print all books on hand ;D
books = re.findall('book.', (str(globals().copy())).replace("'", ''))
books_titles = [eval(f'{o}.get_title()') for o in books]
##########
user_lib =[]
#You can use that in a function (def) and call it when you need it
while True:
os.system('cls')
option = int(input('''
Select an option
1 - Borrow a book
2 - Return a book
3 - See info on available books
4 - See my lib
5 - Exit
>>> '''))
if option == 1:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
option_3 = int(input('How much?: '))
if int(eval(f'book{option_2}.left()'))-option_3 >= 0:
if x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.title'), user_lib)):
user_lib[user_lib.index(x[0])]['amount'] +=option_3
else:
user_lib.append({'name': eval(f'book{option_2}.get_title()'), 'amount': option_3})
print(f'You borrowed {option_3} books')
eval(f'book{option_2}.borrow_sell({option_3})') #Remove from store
else:
print(f'We have {eval(f"book{option_2}.left()")} books left...')
time.sleep(1) # wait 1 second for user to read then reset
elif option == 2:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
if len(x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.get_title()'), user_lib))) > 0:
option_3 = int(input('How much?: '))
if user_lib[pos:=user_lib.index(x[0])]['amount'] -option_3 >= 0:
user_lib[pos]['amount'] -= option_3
if user_lib[pos]['amount'] == 0:
user_lib.pop(pos)
print(f'You returned {option_3} books')
eval(f'book{option_2}.borrow_add({option_3})') # Add them back to shop
else:
print(f"You don't have enogh books, you have only: {x[0]['amount']}")
time.sleep(1) # wait 1 second for user to read then reset
else:
print("You don't any books of thta kind")
time.sleep(1)
elif option == 3:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
print(eval(f'book{option_2}.get_book_info()'))
input('Press enter to continue...')
elif option == 4:
print("\n".join(f"Book Name:{user_lib[o]['name']}\nAmount I have:{user_lib[o]['amount']}" for o, i in enumerate(user_lib)) if user_lib != [] else "You don't have any books")
elif option == 5:
sys.exit(1)
else:
print('Invalid number')
time.sleep(1) # wait 1 second for user to read then reset

How to loop same variable with different result

Hi I've got a school project which requires me to code a program that asks a user for their details it will then ask what them what size pizza they want and how many ingredients. It will then ask if they want another pizza. It will repeat this until they say no or they have six pizzas.
I don't really know how to explain my issues but I don't know how to loop the code so it asks for another pizza and each one has a different size and amount of toppings. I also don't know how I would print it.
Sorry if this is asking a lot or its confusing to understand or if the code is just painful to look at ahaha.
Thanks in advance.
CustomerName = input("Please input the customers name: ")
CustomerAddress = input("Please input the customers address: ")
CustomerNumber = input("Please input the customers number: ")
while True:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ")
try:
PizzaSize = str(PizzaSize)
if PizzaSize == "Small" or "Medium" or "Large":
break
else:
print("Size not recognized")
except:
print("Invalid input")
if PizzaSize == "Small":
SizeCost = 3.25
elif PizzaSize == "Medium":
SizeCost = 5.50
elif PizzaSize == "Large":
SizeCost = 7.15
print(SizeCost)
while True:
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
ExtraToppings = float(ExtraToppings)
if ExtraToppings >= 0 and ExtraToppings <= 4:
break
else:
print("Please insert a number over 0")
except:
print("Input not recognised")
if ExtraToppings == 1:
ToppingCost = 0.75
elif ExtraToppings == 2:
ToppingCost = 1.35
elif ExtraToppings == 3:
ToppingCost = 2.00
elif ExtraToppings >= 4:
ToppingCost = 2.50
else:
print("Number not recognized")
print(ToppingCost)
``
First of all, you should put the code from the second while loop in the first. There is no need for two while true loops. Then instead of
while True:
just put
pizza_count = 0 # how many pizzas they have
wantsAnotherPizza = True
while pizza_count < 6 and wantsAnotherPizza: # while they have less than 6 pizzas and they want another one
pizza_count += 1 # increase pizza_count as they order another pizza
# ... your code here from both of the while loops
x = input("Do you want another pizza? (Y/N)")
if x == "N" or x == "n":
global wantsAnotherPizza
wantsAnotherPizza = False:
You can modify your code like this. I thing you can simply your conditionals by using dictionaries. Try this
from collections import defaultdict
customer_order = defaultdict(list)
customer_order['CustomerName'] = input("Please input the customers name: ")
customer_order['CustomerAddress'] = input("Please input the customers address: ")
customer_order['CustomerNumber'] = input("Please input the customers number: ")
pizza_size ={
'small':3.25,
'medium': 5.50,
'large': 7.15
}
toppins= {'1': 0.75,
'2':1.35,
'3':2.00,
'4':2.50,
}
order = int(input("How many orders would you like to make: "))
while order:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ").lower()
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
if PizzaSize in pizza_size:
size_cost= pizza_size[PizzaSize]
if ExtraToppings:
ToppingCost= toppins[ExtraToppings]
else:
print("Number not recognized")
continue
customer_order['order'].extend([{'size':PizzaSize,'toppings': ToppingCost}])
order -= 1
else:
print("Size not recognized")
continue
except Exception as msg:
print("Invalid input", msg)
continue
else:
print('Your order is complete')
print(customer_order)

When I print my list instead of using the names in the list the output shows the index numbers. Python 2D-Lists

Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated.
#Define Vars
import locale
locale.setlocale( locale.LC_ALL, '')
order_total = 0.0
price = 3.5
fmt_price = locale.currency(price, grouping=True)
qty = int(0)
#cookie list
cookie_list = list()
cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split()
order_list = list()
#cookie choices
def disp_items():
print("Please choose one of our flavours. Enter the item number to choose")
for c in range(len(cookie_list)):
print("{}. \t{}".format(c+1, cookie_list[c]))
print()
#Menu Choices
def disp_menu():
choice_list = ["a", "d", "m", "q"]
while True:
print("\nWhat would you like to do?")
print("a = add an item")
print("d = delete an item")
print("m = display the meal so far")
print("q = quit")
choice = input("\nmake a selection: ")
if choice in choice_list:
return choice
else:
print("I dont't understand that entry. Please Try again.")
# Math Function**********************
def calc_tot(qty):
#this function is qty * price
return qty * 3.5
def disp_order():
print("\nGirl Scout Cookie Order for", cust)
print()
print("Itm\tName\tQty\tPrice")
print("---\t----\t----\t----")
order_total_items = 0 #accumulator
order_price = 0
for c in range(len(order_list)):
detail_list = [" ", 0]
detail_list.append(order_list)
print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price))
order_total_items += order_list[c][1]
order_price += price
print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price))
print("-" * 30)
#ADD Process
def add_process():
valid_data = False
while not valid_data:
disp_items()
try:
item = int(input("Enter item number: "))
if 1 <= item <= len(cookie_list):
valid_data = True
else:
print("\nThat was not a vaild choice, please try again.")
except Exception as detail:
print("error: ", detail)
#Valid Qty
valid_data = False
while not valid_data:
try:
qty = int(input("Enter Quantity: "))
if 1 <= qty <= 10:
valid_data = True
else:
print("\nThat was not a valid quantity, please try again.")
except Exception as detail:
print("Error; ", detail)
print("Please try again")
#Function call for multiplication
item_total = calc_tot(qty)
fmt_total = locale.currency(item_total, grouping=True)
#User Choice
print("\nYou choose: {} boxes of {} for a total of {}".format(qty,
cookie_list[item-1],
fmt_total))
print()
#verify inclusion of this item
valid_data = False
while not valid_data:
incl = input("Would you like to add this to your order? (y/n): ")
print()
if incl.lower() =="y":
#2-D List
inx = item - 1
detail_list = [inx, qty]
order_list.append(detail_list)
valid_data = True
print("{} was added to your order".format(cookie_list[inx]))
elif incl.lower() == "n":
print("{} was not added to your order".format(cookie_list[inx]))
valid_data = True
else:
print("That was not a vaild response, please try again")
#Delete function
def del_item():
if len(order_list) == 0:
print("\n** You have no items in your order to delete **\n")
else:
print("\nDelete an Item")
disp_order()
valid_data = False
while not valid_data:
try:
choice = int(input("Please enter the item number you would like to delete: "))
if 1<= choice <= len(order_list):
choice = choice - 1
print("\nItem {}. {} with {} boxes will be deleted".format(choice +1,
order_list[choice][0],
order_list[choice][1]))
del order_list[choice]
valid_data = True
except Exception as detail:
print("Error: ", detail)
print("Please try again")
#Main program
# Banner
print("Welcome to the Girl Scout Cookie")
print("Order Program")
cust = input("Please enter your name: ")
while True:
choice = disp_menu()
if choice == "a":
add_process()
elif choice == "d":
del_item()
elif choice == "q":
break
disp_order()
disp_order()
print("Thank you for your order")
Here's the output
Girl Scout Cookie Order for *****
Itm Name Qty Price
--- ---- ---- ----
1. **0** 1 3.5
2. **0** 1 3.5
3. **4** 5 3.5
Your Order Contains 7 items for total of 10.5
Under name there should be a name of a girl Scout Cookie and not the index number, how do i fix this?
Many Thanks.
When you print the order in disp_order() you should print from cookie_list[c] in the second column. And print the whole item instead off just the first letter.
print("{}.\t{}\t{}\t{}".format(c+1, cookie_list[c], order_list[c][1], price))
The cookie names are not of equal length, so you'll have to adjust for that.

Storing Every Single Inputs and Then Displays In Order

Is there actually a way to store every different input for n number of inputs and then displays all of them all together in correct order for example:
The User Inputs Record Number, Name, Employee Type, Number Of Days Worked For n number of users
After n number of users, it displays the following all at once:
Record Number: 1
Employee Name: Alexander
Employee Type: C
Days Worked:5
Pay(RM):2500.00
Record Number: 2
Employee Name: Bella
Employee Type: V
Days Worked:10
Pay(RM):1000.00
Record Number: 3
Employee Name: Tom
Employee Type: S
Days Worked:20
Pay(RM):5000.00
Or is it only possible to display one by one? Here is my current code
print("{0:^15s}{1:^25s}".format("Employee Type", "Employee Rate (per day)"))
print("{0:^15s}{1:>15s}".format("C", "RM 500.00"))
print("{0:^15s}{1:>15s}".format("S", "RM 250.00"))
print("{0:^15s}{1:>15s}".format("V", "RM 100.00"))
print()
numEmployee = 1
confirmation = 0
while confirmation != "Y":
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while numEmployee == str():
print("No Input Has Been Detected. Please Input Number Of Employee(s) In An Integer")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while eval(numEmployee) <= 0:
print("Please Enter A Valid Number Of Employees")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
confirmation = input("Are You Sure You The Number Of Employee Is Correct? Enter Y to Continue or any other key to reenter The Correct Number:")
confirmation = confirmation.upper()
print()
numEmployee = eval(numEmployee)
#for recordNum in range (1, numEmployee + 1):
recordNum = 1
finalTotalC = 0
finalTotalS = 0
finalTotalV = 0
while recordNum <= numEmployee:
print("Record Number: ", recordNum)
recordNum = recordNum + 1
name = input("Employee Name: ")
while name == str():
print("Please Enter A Name")
name = input("Employee Name: ")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType == str():
print("No Input Has Been Detected. Please Input An Employee Type")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType != "C" and employeeType != "S" and employeeType != "V":
print("Employee Type Is Invalid. Please Enter C,S or V Only")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
daysWorked = input("Days Worked: ")
while daysWorked == str():
print("No Input Has Been Detected. Please Input Number Of Days Worked In That Month")
daysWorked = input("Days Worked: ")
while eval(daysWorked) < 0 or eval(daysWorked) > 31:
print("Please Enter The Number Of Days In A Range Of 0 until 31 Only")
daysWorked = input("Days Worked: ")
daysWorked = eval(daysWorked)
if employeeType == "C":
EMPLOYEERATE = 500.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalC = daysWorked*EMPLOYEERATE
finalTotalC = finalTotalC + totalC
print()
if employeeType == "S":
EMPLOYEERATE = 250.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalS = daysWorked*EMPLOYEERATE
finalTotalS = finalTotalS + totalS
print()
if employeeType == "V":
EMPLOYEERATE = 100.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalV = daysWorked*EMPLOYEERATE
finalTotalV = finalTotalV + totalV
print()
You need to store the data somewhere, as you are receiving it. I would suggest a list (https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) of dicts (https://docs.python.org/2/tutorial/datastructures.html#dictionaries) might be appropriate for your case. Then you can iterate over the list after you're done (in order to print).

Categories