I want the user to select a number 1-7 and then check if that this is true, if not then they input a number again.
I am able to check this but if a wrong number is chosen it will ittirate the process 3 times even if a correct value is entered.. I have tried many different solutions to no avail. I just want to check the value until its right and then return the correct value to the game.
board = [['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ ', '5️⃣ ', '6️⃣ ', '7️⃣']]
ROWS = 7
COLUMNS = 7
def print_board():
'''
Prints out the game board
'''
for row in range(0, ROWS):
for col in range(0, COLUMNS):
print(board[row][col], end=' ')
print(" ")
def place_chip(col, player):
'''
Places chip in the first empty slot from the bottom in a column
'''
col = col - 1
for rows in range(ROWS-1, -1, -1):
if board[rows][col] == '⚪':
board[rows][col] = player
break
def validate_input(x):
while True:
if x < 1:
x = int(input(f'Column {x} does not exist. Please choose column 1-7: '))
return x
elif x > 7:
x = int(input(f'Column {x} does not exist. Please choose column 1-7: '))
return x
else:
break
return x
def play_game():
print_board()
x = int(input('Player 1 select a column(1-7): '))
validate_input(x)
place_chip(validate_input(x), '🔴')
print_board()
play_game()
Another approach, for a console game, is that the loop iterates, instead of three times, until a correct number is obtained, between 1 or 7 or the user indicates -1 (for example) in case he wants to end game!
Related
I wanted to create an analogue of the banking system in the terminal.I'm a beginner, I can't give an id for him to find also by name .couldn't solve getting_information_account ,find_an_account. I would also like to make a transfer between clients and withdraw the transaction,,couldn't make it through id
from random import randint
import datetime
now = datetime.datetime.now()
class bank():
def __init__(self):
self.name_k = []
self.card_numbers = []
self.pin_numbers = []
self.name_k=[]
self.data_k=[]
self.balances=[]
self.id_k=[]
def main_screen(self):
print(
"1. create_account\n"
"2. deleting_account\n"
"3. getting_information_account\n"
# "4.transactions_between_account\n"
"5. find_an_account\n"
"0. Exit"
)
main_menu_selection = str(input(":"))
if main_menu_selection == "1":
self.create_account()
if main_menu_selection == "2":
self.deleting_account()
if main_menu_selection == "3":
self.getting_information_account()
if main_menu_selection == "4":
self.transactions_between_account()
if main_menu_selection == "5":
self.find_an_account()
if main_menu_selection == "0":
print("\n")
return "Bye!"
def create_account(self):
credit_card_number = "400000" + format(randint(0000000000, 9999999999), '010d')
pin_number = format(randint(0000, 9999), '04d')
name_k=format(input("name"))
data_k=now.strftime("%d-%m-%Y %H:%M ")
id_k=format(randint(0000000000, 10000), )
self.data_k.append(data_k)
self.name_k.append(name_k)
self.id_k.append(id_k)
self.card_numbers.append(credit_card_number)
self.pin_numbers.append(pin_number)
print("\n")
print("Your card has been created")
print("name:",name_k)
print("you id:",id_k)
print("number card:")
print(credit_card_number)
print(" pin-code:")
print(pin_number)
print("\n")
self.account_balance()
def deleting_account(self):
print("\n")
print("number card:")
ent_card_number = int(input())
print("pin-code:")
ent_pin_number = int(input())
if str(ent_card_number) in self.card_numbers and str(ent_pin_number) in self.pin_numbers:
print("\n")
print("You have successfully deleted the client's account!")
self.main_screen()
else:
print("\n")
print("Incorrect PIN code of the card!")
print("\n")
self.main_screen()
def account_balance(self):
print(
"\n1.Your balance\n"
"2. exit\n"
)
account_balance_selection = str(input())
if account_balance_selection == "1":
balances=format(randint(0, 10000))
self.balances.append(balances)
print("\n")
print("balance:",balances )
self.account_balance()
elif account_balance_selection == "2":
print("\n")
print("You have successfully logged out!")
print("\n")
self.main_screen()
def find_an_account(self):
pr_id=int(input("Enter Id:"))
if str(pr_id) in self.id_k:
print(self.name_k)
def getting_information_account(self):
pr_name = str(input("Enter the client's name :"))
if str(pr_name) in self.name_k:
print(f'clients name:{self.name_k[1]} id-:{self.id_k}number card:{self.card_numbers} date of map creation:{self.data_k} card balance:{self.balances}')
print(bank().main_screen())
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
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")
creating a pizza ordering program for IT class, almost finished with it but I'm currently stuck with a problem that I can't seem to fix or don't know how to. As the user is finished choosing their pizza it was suppose to add up the total cost of the pizza they have chosen but the problems is they don't add up the instead the price stays the same
Name:Jack
Telephone:47347842
ORDER:
['2. Hawaiian pizza', 8.5]
['1. Pepperoni pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
Total Price: 8.50
Here's the price list that they have to choose from
['1. Pepperoni pizza', 8.5]
['2. Hawaiian pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
['4. Cheese pizza (with choice of sauce)', 8.5]
['5. Ham and cheese pizza', 8.5]
['6. Beef & onion pizza', 8.5]
['7. Vegetarian pizza', 8.5]
['8. BBQ chicken & bacon aioli pizza', 13.5]
['9. Boneless pizza (italian style anchovy with no bones)', 13.5]
['10. Pizza margherita', 13.5]
['11. Meat-lover’s pizza', 13.5]
['12. Tandoori pizza', 13.5]
I don't know if the problems lies in this code but it seem like it is. I originally I tried using 'cost.append' but it only came up with an error like this
unsupported operand type(s) for +: 'int' and 'str'
def Choice_of_pizza():
for i in range(1,pizza_no
+1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
cost.append(MENU[pizza_kind-1][0][pizza])
customerOrder.append(MENU[pizza_kind-1][pizza])
global total_cost
total_cost = sum(cost) #Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
So I went and replace it with 'cost=+customerOrder[i][1]' but even then it somewhat works with the names of the pizza being added but not the prices unto the customer details.
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza(
The intended goal was, as the user input there choice one by one it takes out the name and places the price into the cost list but it doesn't seem to do that.
here's the original full code
#----------------------------important stuff-----------------------------------
#time delay
import time
#loop system for the details section
running = True #Loop
import re
Delivery_cost = 3.0
cost=[]
customerOrder=[]
customer_name=[]
customer_name_2=[]
customer_telephone_2=[]
house_no=[]
street_name=[]
#------------------------------menu list --------------------------------------
MENU =[
['1. Pepperoni pizza', 8.50], ['2. Hawaiian pizza', 8.50], ['3. Garlic cheese pizza (with choice of sauce)', 8.50],['4. Cheese pizza (with choice of sauce)', 8.50], ['5. Ham and cheese pizza', 8.50], ['6. Beef & onion pizza', 8.50], ['7. Vegetarian pizza', 8.50], ['8. BBQ chicken & bacon aioli pizza', 13.50], ['9. Boneless pizza (italian style anchovy with no bones)', 13.50], ['10. Pizza margherita', 13.50],['11. Meat-lover’s pizza', 13.50],['12. Tandoori pizza', 13.50]
]
#-----------------------------details------------------------------------
def pick_or_deli():
global delivery
delivery = input("P - pick up / D - delivery:")
delivery = delivery.upper() #Changes the letter inputted to an uppercase
if delivery == "D": #statement if person choosed delivery
while running == True:
global customer_name #This can be called when printing out final order and details
customer_name = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name = customer_name.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone
customer_telephone = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global house_no
house_no = input("House number:")
if not re.match("^[0-9 /]*$", house_no): #Checks whether input is numbers only
print("Please use numbers only")
elif len(house_no) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global street_name
street_name = input("Street name:")
if not re.match("^[a-zA-Z ]*$", street_name): #Checks whether input is letters only
print("Please use letters only")
elif len(street_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
street_name = street_name.title()
break #Breaks the loop when valid input has been entered
elif delivery == "P": #statement for if person choosed pickup
while running == True:
global customer_name_2
customer_name_2 = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name_2): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name_2 = customer_name_2.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone_2
customer_telephone_2 = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone_2): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
else:
print("Please enter P or D")
pick_or_deli()
pick_or_deli()
#-----------------------------order script-------------------------------------
print('''\nWelcome to ~~~~~ Dream Pizza ~~~~~
To pick an order from the Menu pick the designated number that is next to the product.\n
From 1 for Pepperoni pizza.\n
Or 2 for Hawaiian pizza.\n
and so on.\n
The delivery cost is $3\n
To cancel the order throughout press 0 and it will reset itself.\n
But first decide how many pizza you want.\n''')
time.sleep(3.0)
#--------------menu text and design can be called again------------------------
def menu_design():
print(*MENU, sep = "\n")\
menu_design()
#------------------deciding how many pizzas they want---------------------------
def order():
global pizza_no
while True:
try: #Validating the inputs
pizza_no = int(input('''\nNo. of pizzas you want (min 1 - max 5):\n'''))
if pizza_no < 1:
print("Please order between 1 - 5 pizzas") #Checks whether input is between 1 and 5
continue
if pizza_no > 12:
print("Please order between 1 - 5 pizzas")
continue
else:
break #Breaks the loop when valid input has been entered
except ValueError: #Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
order()
#--------------------------------picking pizza-----------------------------------
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
#-----------------------------------reciept---------------------------------------
def customerDetails(): #Prints customer order and details
if delivery == "D": #if person choosed delivery
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name: {}' .format(customer_name))
print ('Telephone: {}' .format(customer_telephone))
print ('Address:')
print (house_no, street_name)
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: $ {:.2f}' .format(total_cost))
print ('Total Price + Delivery Cost: $ {:.2f}' .format(Combined_Total))
else: #if person choosed pickup don't have to speccify
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name:{}' .format(customer_name_2))
print ('Telephone:{}' .format(customer_telephone_2))
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: {:.2f}' .format( total_cost))
customerDetails()
#-----------confrimation of customers order proceed or cancel---------------------
print ("")
def confirm(): #Confirms details of customer and order
confirmation = input("Y - confirm order / N - cancel order:")
confirmation = confirmation.upper() #Changes the letter inputted to an uppercase
if confirmation == "Y": #if Y is entered, order is confirmed
print("DETAILS CONFIRMED")
elif confirmation == "N": #if N is entered, order is cancelled
print("DETAILS CANCELLED - order has been reset")
customerOrder[:] = []
cost[:] = []
menu_design()
order()
Choice_of_pizza()
customerDetails()
confirm()
else:
print("Please enter Y or N") #If anything other than Y or N is entered, it will ask again
confirm()
confirm()
#----statement im customer would like to order more or finalised there order---
print ("")
def order_more(): #Placing another order
order_more = input("Z - order more / x - exit program:")
order_more = order_more.upper() #Changes the letter inputted to an uppercase
'''cost[:] = []'''
if order_more == "Z":
menu_design() #Calls the functions - will run the code that the def defines
order()
Choice_of_pizza()
customerDetails()
confirm()
print ("")
print ("THANK YOU FOR YOUR SHOPPING AT DREAMS PIZZA")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
elif order_more == "X":
print ("")
print ("THANK YOU FOR YOUR ORDER")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
else:
print ("Please enter X or Z") #If anything other than X or Z is entered, it will ask again
order_more()
order_more()
Also why I only have one list? it is because I was required to only use one
Code Issues:
For addition assignment the syntax is:
x += y # this assigns x to (x + y)
Not:
x = +y # this assign x to y
Glbols are not causing a problem in your code, but are usually frowned upon and negatively reflect on programming skills i.e. Why are Global Variables Evil?.
Choice_of_pizza function fix
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
cost = 0
for i in range(len(customerOrder)):
cost += customerOrder[i][1]
global total_cost # globals are discouraged
total_cost=0
#Sum of the pizzas
global Combined_Total # globals are discouraged
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost += cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost += cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
the if condition is not running even if the condition is true. On line 29 there's a function set_row and on line 31 there's a function set_col. On Line 58 there's an if statement which checks if guess_row1 is equals to set_row and guess_col1=set_col even the condition is true if statement does not run else always run
from random import randint
user1 = {
"name":input("Enter your name"),
"board":[]
}
user2 = {
"name":input("Enter your name"),
"board":[]
}
def set_board(user):
for x in range(5):
user["board"].append(["O"]*5)
def print_board(user):
for row in user["board"]:
print(" ".join(row))
print("")
print("Let's start")
print("")
set_board(user1)
set_board(user2)
print("This is {}'s board".format(user1["name"]))
print_board(user1)
print("")
print("This is {}'s board".format(user2["name"]))
print_board(user2)
def set_row(user1):
return randint(0, len(user1["board"])-1)
def set_col(user1):
return randint(0, len(user1["board"])-1)
print("")
print("Answer for {}".format(user1["name"]))
print(set_row(user1))
print(set_col(user1))
print("")
def set_row2(user2):
return randint(0, len(user2["board"])-1)
def set_col2(user2):
return randint(0, len(user2["board"])-1)
print("Answer for {}".format(user2["name"]))
print(set_row2(user2))
print(set_col2(user2))
print("")
for turnu1 in range(3,0,-1):
print("turn's left for {} ".format(user1["name"]) + str(turnu1))
print("")
guess_row1 = int(input("Enter the row "))
guess_col1 = int(input("Enter the col "))
print("")
if guess_row1==set_row(user1) and guess_col1==set_col(user1):
print("your right")
else:
print("Wrong answer")
When you call and print the random numbers for user 2:
print(set_row2(user2))
print(set_col2(user2))
then those numbers are generated by randint() and never stored anywhere.
The calls for user 1 then will be new random numbers:
if guess_row1==set_row(user1) and guess_col1==set_col(user1):
and not correspond with the first set of calls. If you meant those to be equal, then store the random values you picked first:
user2_row = set_row2(user2)
user2_col = set_col2(user2)
so you can test against them later:
if guess_row1 == user2_row and guess_col1 == user2_col: