It's a beginner python program where we are given a menu and user gets to choose which item from 1-5 and 6 to exit. If they choose 6, it would terminate the code, don't ask any other questions and do not show the bill.
I thought placing it at the "elif choice == 6" would work but then it ends the whole code without considering the other previous choices
def get_inputs():
'''get input of each of the burger choices of the user and how much did they want'''
count = 0
quantity1 =quantity2=quantity3=quantity4=quantity5 = 0
flag = True
while flag:
check_choice = True
while check_choice:
try:
choices=int(input("Enter kind of burger you want(1-5 or 6 to exit): ").strip())
if choices <=0:
print("Enter a positive integer!")
else:
check_choice = False
except:
print("Enter valid numeric value")
check_quantity = True
while check_quantity and choices != 6:
try:
quantity = int(input("Enter quantity of burgers wanted: "))
if quantity <=0:
print("Enter a positive integer!")
else:
count +=1
check_quantity = False
except:
print("Enter valid numeric value")
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
flag = False
check_staff = True
while check_staff and count !=0:
try:
tax = int(input("Are you a student? (1 for yea/0 for no)"))
check_staff = False
except:
print("Enter 1 or 0 only")
return quantity1,quantity2,quantity3,quantity4,quantity5,tax
def compute_bill(quantity1,quantity2,quantity3,quantity4,quantity5,tax):
'''calculate the total amount of the burgers and the total price of the purchase'''
total_amount = tax_amount = subtotal = 0.0
student_tax = 0
subtotal = (quantity1 * DA_PRICE) + (quantity2 * BC_PRICE) + (quantity3 * MS_PRICE) + (quantity4 * WB_PRICE) + (quantity5 * DCB_PRICE)
if(tax == 0):
tax = float(STAFF_TAX)
tax_amount = subtotal *(tax/100)
total_amount = subtotal + tax_amount
elif(tax == 1):
total_amount = subtotal+student_tax
return tax_amount, total_amount, subtotal
Expected: when starting the program and pressing 6, it will terminated without asking any other questions and also without showing the bill
Expected: code would get user's input and then when pressing 6, it will continue on to comput_bill function and compute/print the bill
Actual results: when pressing 6 at the beginning, in get_inputs, in the return statement, the local variable "tax" is referenced before assignment
You can just do the loop and when you get a 6 you exit the loop. If there has been no inputs, then skip the student check and the bill calculation.
This is much cleaner than trying to use flag variables to check whether you should print.
Using sys.exit. Is quite a brutal way to terminate your program. It's usually best to delegate the decision to terminate to the outermost functions in your application. It's also better to let the program terminate naturally by reaching the end of the program.
You might use sys.exit for things like incorrect command line arguments.
# example prices.
unitprices = {
1: 7.89, # DA_PRICE
2: 11.00, # BC_PRICE
3: 9.50,
4: 15.85,
5: 21.00
}
STAFF_TAX = 0.2
def calcbill(units, istaxable, unitprices=unitprices, taxrate=STAFF_TAX):
subtotal = 0
for u in units:
subtotal += unitprices[u]
if istaxable:
tax_amount = subtotal * (taxrate / 100)
else:
tax_amount = 0
return (subtotal + tax_amount, tax_amount)
entries = []
print("Enter kind of burger you want(1-5 or 6 to exit): ")
while True:
try:
choice = int(input("what is the next burger? "))
if choice == 6:
break
elif 0 < choice < 6:
entries.append(choice)
else:
print('invalid choice')
except:
print('not a number')
if entries:
while True:
s = input('Are you a student? ').lower()
if s in ('y', 'yes', 'true'):
isstudent = True
break
elif s in ('n', 'no', 'false'):
isstudent = False
break
else:
print('not a valid value')
total, tax = calcbill(entries, not isstudent)
print(f'the bill was ${total:.2f} which includes ${tax:.2f} tax')
As far as I understood from the expected output, you want to exit the code in the following scenarios:-
(1) At the beginning of the code, when there is no value in the kind of the burger, just exit the code, without prompting the user to input again.
(2) After saving some values in the burger count, if the user pressed 6, then also it should not ask the user for the price calculation logic.
If my understanding is right, then you should update your code in the following manner:-
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
check_choices = False
flag = False
import sys
sys.exit()
And the output is as follows:-
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 2
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 4
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$
Related
I don't understand why I can't connect the processSale method to the sellProduct method. I think that the classes and other methods don't need any change because I only followed the criterias that were given to me.
#candy machine
class CashRegister:
def __init__(self, cashOnHand = 500,):
if cashOnHand < 0:
self.cashOnHand = 500
else:
self.cashOnHand = cashOnHand
def currentBalance(self):
return self.cashOnHand
def acceptAmount(self, cashIn):
self.cashOnHand += cashIn
class Dispenser:
def __init__(self, numberOfItems = 50, productCost = 50):
if numberOfItems < 0:
self.numberOfItems = 50
else:
self.numberOfItems = numberOfItems
if productCost < 0:
self.productCost = 50
else:
self.productCost = productCost
def getCount(self):
return self.numberOfItems
def getProductCost(self):
return self.productCost
def makeSale(self):
self.numberOfItems -= 1
class MainProgram:
def showMenu(self):
global userInput
print("**** Welcome to Eros' Candy Shop ****")
print("To select an item enter")
print("""1 for Candy
2 for Chips
3 for Gum
4 for Cookies
0 to View Balance
9 to Exit""")
userInput = int(input("Enter your choice: "))
def sellProduct(self, useDispenser = Dispenser(), useRegister = CashRegister()):
try:
self.useDispenser = useDispenser
self.useRegister = useRegister
if self.useDispenser.getCount != 0:
print(f"It costs {self.useDispenser.getProductCost} cents")
cash = int(input("Please enter your payment: "))
change = cash - self.useDispenser.getProductCost
if change < 0:
print("Insufficient money!")
print(f"You need {self.useDispenser.getProductCost - cash} cents more")
return
else:
print(f"Your change is {change} cents")
self.useRegister.acceptAmount(self.useDispenser.getProductCost)
self.useDispenser.makeSale
return
elif self.useDispenser.getCount == 0:
print("The product you chose is sold out! Try the other itmes")
return
except ValueError:
print("You entered an incorrect value. Please use the numbers on the menu only")
def processSale(self):
Register = CashRegister()
Candy = Dispenser()
Chips = Dispenser()
Gum = Dispenser()
Cookies = Dispenser()
while True:
self.showMenu
if userInput == 1:
self.sellProduct(Candy, Register)
elif userInput == 2:
self.sellProduct(Chips, Register)
elif userInput == 3:
self.sellProduct(Gum, Register)
elif userInput == 4:
self.sellProduct(Cookies, Register)
elif userInput == 0:
print("Current Balance is" + str(Register.currentBalance))
elif userInput == 9:
break
mainProgram = MainProgram()
mainProgram.showMenu()
How do i use sellProduct method on userInput 1-4. I get confused when applying the properties of a class and how to connect them. Can you point out what mistakes I made and what other improvements I can do.
here are some points you can improve :
When you call your methods do not forget the parenthesis :
self.useDispenser.getCount()
self.useDispenser.getProductCost()
Create an infinite loop to continuously ask for input within showMenu and delete the one within processSale (for example):
def showMenu(self):
global userInput
userInput = 0
print("**** Welcome to Eros' Candy Shop ****")
while userInput != 9:
print("To select an item enter")
print(MENU)
userInput = int(input("Enter your choice: "))
if userInput < 9:
self.processSale()
But please update the whole program accordingly.
Hope it helps !
empmangpro = True
employees = []
while empmangpro == True:
try:
empcount = len(employees)
print("--------------------Employee Management System--------------------")
print("")
print("There are "+str(empcount)+" employees in the system.")
print("")
print("------------------------------------------------------------------")
print("1. Add new employee")
print("2. View all employees")
programselection = int(input("Please select your option number: "))
if programselection == 1:
employee = []
employee.append(input("First and Last Name: "))
employee.append(input("Social Security Number: "))
employee.append(input("Phone Number: "))
employee.append(input("Email Address: "))
employee.append(input("Salary:$"))
employees.append(employee)
elif programselection == 2:
i = 0
j = 0
empstr = ""
while i < int(empcount):
while j < 5:
empstr = empstr + employees[i][j]
if j != 4:
empstr = empstr + ", "
j += 1
if i+1 != int(empcount):
empstr = empstr + "\n"
j = 0
i += 1
print(empstr)
print[employees]
elif programselection < 3:
empmangpro = False
else:
print("Please enter valid information")
except ValueError:
print("Please enter valid information")
continue
I have option 1 working where you can add multiple employees to the system, but when I select option 2, nothing happens. It is supposed to print all the employees that I add. What did I do wrong here? I only have been programming for less than a month, so I have still have lots to learn. What am I missing or did wrong?
Is not very clear what you are trying to do at option 2. Try commenting your code in the future. The tabbing in your post was not accurate so I made some guesses. Maybe this will help you with your problem:
empmangpro = True
employees = []
while empmangpro == True:
try:
empcount = len(employees)
print("--------------------Employee Management System--------------------")
print("")
print("There are "+str(empcount)+" employees in the system.")
print("")
print("------------------------------------------------------------------")
print("1. Add new employee")
print("2. View all employees")
programselection = int(input("Please select your option number: "))
if programselection == 1:
employee = []
employee.append(input("First and Last Name: "))
employee.append(input("Soci1al Security Number: "))
employee.append(input("Phone Number: "))
employee.append(input("Email Address: "))
employee.append(input("Salary:$"))
employees.append(employee)
elif programselection == 2:
i = 0
j = 0
empstr = ""
while i < empcount:
print(str(employees[i])+"\n")
i += 1
elif programselection > 2:
empmangpro = False
print("Stopping programm")
else:
print("Please enter valid information")
except ValueError:
print("Please enter valid information")
continue
Also if you want to stop the program use elif programselection > 2: instead of elif programselection < 3:.
You said option 1 works. OK (I see some indentation issues).
For option 2, I'll be honest I did not quite follow your code. If you want option 2 to print all employees, I suggest to create an Employee class. That way, you can print(employee) anywhere.
Can put this into employee.py:
class Employee:
def __init__(self, name): # can add all you need social security, ...
first, last = name.split(' ')
self.first = first # add a new line per new parameter
self.last = last
def __str__(self):
# here you can add all of your logic
# to properly format social security, phone number, etc.
# just be sure to return a string, and not print a string!
return f'{self.last}, {self.first}'
Then in your main file:
import employee # put at top of file
employees = [Employee('John Doe'), Employee('Jane Doe')] # sample data
for e in employees:
print(e)
Output:
Doe, John
Doe, Jane
As for incorrectly spaced:
if programselection == 1:
employee = []
# ...
employees.append(employee)
elif programselection == 2:
And:
except ValueError:
print("Please enter valid information")
continue
I have made a program that adds up the orders of a fast food menu. I need to add a running subtotal after I have made an order. As I am a python novice, I am not quite sure what to do. I also need to make sure my order dictionary is modified, but am unsure how to do so.
I thought about making a loop with a range to keep the total but I do not want a range as I want the program to be able to take as many orders as possible.
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
bcount = 0
fcount = 0
dcount = 0
while True:
print("Please make a selection:")
print("1. Burger = $5.00")
print("2. Fries = $3.50")
print("3. Drink = $1.00")
print("4. Quit")
choice = int(input('Please order: '))
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
elif choice == 2:
amount = int(input("Enter number of Fries: "))
fcount += amount
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
dcount += amount
elif choice == 4:
sub = (bcount * 5.00) + (fcount * 3.50) + (dcount * 1.00)
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(bcount))
print('Number of Fries: {0}'.format(fcount))
print('Number of Drinks: {0}'.format(dcount))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
The expected result is after each order, the program would give me a running subtotal.
Example: after an order of a burger is entered would look like:
Your subtotal is: $5.00
Then the next order is an order of fries and a drink
Your subtotal is: $9.50 (adding the burger from the previous order)
One way to do this is to add a variable called subtotal in the beginning called subtotal. Attached one example for the burger that can be applied to the rest. I agree with previous commenter regarding reset of variables instead of break.
subtotal=0
bcount = 0
fcount = 0
dcount = 0
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
subtotal+=(amount*5)
print("Your total is: ",subtotal)
I assume, for option 1 - 3, you need to show the subtotal and for option 4 you need to show the full report.
I have updated the code as following:
added calculate_sub_total method.
displayed subtotal for option 1-3.
separated the if-elif-else to two partitions.
Used the menu dictionary to fetch prices for items both in sub total calculation and in displaying the menu.
Used the order dictionary to keep track of the number of items as intended. Removed bcount, dcount, fcount variables as they are not needed anymore.
Updated code:
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
def calculate_sub_total():
return (order["burger"] * menu["burger"]) + \
(order["fries"] * menu["fries"]) + \
(order["drink"] * menu["drink"])
while True:
print("Please make a selection:")
print("1. Burger = ${}".format(menu["burger"]))
print("2. Fries = ${}".format(menu["fries"]))
print("3. Drink = ${}".format(menu["drink"]))
print("4. Quit")
choice = int(input('Please order: '))
show_subtotal = False
if choice == 1:
amount = int(input("Enter number of Burgers: "))
order["burger"] += amount
show_subtotal = True
elif choice == 2:
amount = int(input("Enter number of Fries: "))
order["fries"] += amount
show_subtotal = True
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
order["drink"] += amount
show_subtotal = True
sub = calculate_sub_total()
if show_subtotal:
print('Subtotal: {:0.2f}'.format(sub))
if choice == 4:
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(order["burger"]))
print('Number of Fries: {0}'.format(order["fries"]))
print('Number of Drinks: {0}'.format(order["drink"]))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
Output:
I was creating a banking interface and I wanted yearly interest to be applied every 10 seconds (as part of a modified time scale).
import time
customers = 100
savings = []
fixdeposit = []
ask_user_type = """
What is your user type?
(type 1 if you're an employee)
(type 2 if you're a customer)
"""
employee_function_options = """
What function would you like to carry out?
(type 1 for total savings value)
(type 2 for a specific savings value)
(type 3 for total fixed deposit value)
(type 4 for a specific fd's value)
(type 5 to add a customer)
(type 6 to remove a customer)
(type 7 to end program)
"""
customer_function_options = """
What function would you like to carry out?
(type 1 for withdrawal)
(type 2 for deposit)
(type 3 for savings account balance)
(type 4 to create fixed deposit)
(type 5 to end fixed deposit)
(type 6 for fixed deposit value)
(type 7 to end program)
"""
for i in range (100):
savings.append(1000)
fixdeposit.append(0)
while 1 == 1:
time.sleep(10)
savings = [i * 1.04 for i in savings]
fixdeposit = [i * 1.07 for i in fixdeposit]
user = int(input(ask_user_type))
while 1==1:
if user == 1:
function = int(input(employee_function_options))
if function == 1:
print (sum(savings))
function = int(input(employee_function_options))
elif function == 2:
saving_account = int(input("What is the chosen account's number?"))
print (savings[saving_account])
function = int(input(employee_function_options))
elif function == 3:
print (sum(fixdeposit))
function = int(input(employee_function_options))
elif function == 4:
fd_no = int(input("What is the chosen fd's number?"))
print(fixdeposit[fd_no])
function = int(input(employee_function_options))
elif function == 5:
no_new_customers = int(input("How many new customers do you want to add?"))
for i in range(no_new_customers):
savings.append(1000)
fixdeposit.append(0)
print ("Task Completed")
function = int(input(employee_function_options))
elif function == 6:
account_deleted = int(input("What is the number of the account to be deleted?"))
savings[account_deleted] = 0
fixdeposit[account_deleted] = 0
print ("Task Completed")
function = int(input(employee_function_options))
elif function == 7:
print ("program ended")
user = int(input(ask_user_type))
else:
print("Error")
function = int(input(employee_function_options))
elif user == 2:
function = int(input(customer_function_options))
if function == 1:
account_no = int(input("What is your account number?"))
withdrawal_amount = float(input("How much money do you want to withdraw?"))
savings[account_no] = savings[account_no] - withdrawal_amount
withdrawal_amount = 0
function = int(input(customer_function_options))
elif function == 2:
account_no = int(input("What is your account number?"))
deposit_amount = float(input("How much money do you want to deposit?"))
savings[account_no] = savings[account_no] + deposit_amount
deposit_amount = 0
function = int(input(customer_function_options))
elif function == 3:
account_no = int(input("What is your account number?"))
print(savings[account_no])
function = int(input(customer_function_options))
elif function == 4:
account_no = int(input("What is your account number?"))
fd_amount = float(input("How much money do you want in your fd?"))
fixdeposit[account_no] = fd_amount
fd_amount = 0
function = int(input(customer_function_options))
elif function == 5:
account_no = int(input("What is your account number?"))
savings[account_no] = savings[account_no] + fixdeposit[account_no]
fixdeposit[account_no] = 0
function = int(input(customer_function_options))
elif function == 6:
account_no = int(input("What is your account number?"))
print(fixdeposit[account_no])
function = int(input(customer_function_options))
elif function == 7:
user = int(input(ask_user_type))
else:
print("Error")
function = int(input(customer_function_options))
else:
print("Error")
user = int(input(ask_user_type))
I used time.sleep() but it seems to me that it prevents the user interface from working too.
Does anyone know any workarounds or ways to limit the time.sleep() function to the loop for interest?
Try using threading, move the part that updates savings and fixdeposit to another thread. This is working example, I only truncated some parts of your code that didn't change, you will see updating printed every 10 seconds:
import threading
import time
customers = 100
savings = []
fixdeposit = []
ask_user_type = ...
employee_function_options = ...
customer_function_options = ...
for i in range (100):
savings.append(1000)
fixdeposit.append(0)
def regular_update():
global savings, fixdeposit
while True:
time.sleep(10)
print('updating')
savings = [i * 1.04 for i in savings]
fixdeposit = [i * 1.07 for i in fixdeposit]
my_thread = threading.Thread(target=regular_update, args=())
my_thread.start()
user = int(input(ask_user_type))
... everything here as in your code
Your while loop never breaks to allow other parts of your program to run.
while 1 == 1:
time.sleep(10)
savings = [i * 1.04 for i in savings]
fixdeposit = [i * 1.07 for i in fixdeposit]
Because of the condition 1 == 1 in your while-loop, it executes forever beause there is no way for the program to break from the loop internally. This means that your time.sleep(10) runs indefinitely.
Update:
Assuming you want a valid input from the user (depending on what you define as valid), you can do one of the following:
number = (int)(input("Enter a number: "))
# 3 is just chosen here as a representative value
# The loop will run until 3 is received as input
while number != 3:
number = (int)(input("Enter a number: "))
print("Exited loop")
Or you can use the break statement to exit a loop when a condition is met:
# 3 is just chosen here as a representative value
# The loop will run indefinitely, but if 3 is received as input, it will break the loop (force it to exit)
while 1 == 1:
number = (int)(input("Enter a number: "))
if number == 3:
break
print("Exited loop")
Python 3.5
I have a project for a class to create a Roulette wheel minigame and I'm having issues. I set the initial cash to $100 and let the user play roulette. After they've given their wager and it's time to tally up the cash for the next round, I'm having issues setting the new cash value. Basically, I need to add the winnings/losings to the value of cash so that it's accurately updated for the next round. I know that declaring cash as a global variable is wrong, but we haven't learned the proper way to do it and haven't had time to check it out for myself. Anyways, the issue is near the bottom. Thank you for any help! -
import math
import random
def main():
global cash
print('Welcome to Roulette! We\'ll start you with $100')
cash = 100 #set to 100 for intitial
menu()
def menu():
print('Place your bet! ',cash,'bucks!', '''
=======================================
1. Bet on Red (pays 1:1)
2. Bet on Black (pays 1:1)
3. First 12 (pays 2:1)
4. Middle 12 (pays 2:1)
5. Last 12 (pays 2:1)
6. Choose any number (pays 35:1)
7. Cash out
Please enter your choice: ''')
menuChoice = int(input())
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if cash > 0 and menuChoice != 7: #Determine if quit or broke
if menuChoice == 6:
number = int(input('Please choose a number from 0-36!')) #Get their specific number
while number < 0 or number > 36: #Validation
number = int(input('Please enter a number from 0-36'))
wager = int(input('How much would you like to bet? '))
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print('Press any key to spin the wheel! ')
input()
print(menuChoice, wager)
##
## ball = random.randint(0,36)
ball = 19 #set to 19 for testing. REMOVE AND RESET BALL!!!!!!!!!!!!!!!!!
if ball == 0:
color = ('green')
elif ball % 2 == 0:
color = ('black')
else:
color = ('red')
print('Your ball was',ball, 'and landed on the color',color)
#Determine if winner
if menuChoice == 1 and color == 'red':
winner = True
odds = 1
elif menuChoice == 2 and color == 'black':
winner = True
odds = 2
elif menuChoice == 3 and ball >= 1 and ball <= 12 :
winner = True
odds = 2
elif menuChoice == 4 and ball >= 13 and ball <= 24:
winner = True
odds = 2
elif menuChoice == 5 and ball >= 25 and ball <= 36:
winner = True
odds = 2
elif menuChoice == 6 and ball == number:
winner = True
odds = 35
else:
winner = False
odds = 0
#End determine if winner
if odds == 0:
pass
else:
amount = wager * odds #Get amount won/lost
print(amount)
if winner == True:
cash += amount #<~~~~~~~~~~~~~Problem Area
print('Congratulations! You won', wager,'dollars!')
print('Your total is now :',cash,'dollars.')
else:
cash -= wager
print('Sorry! You lost',wager,'dollars. Better luck next time!')
print('Your total is now :',cash,'dollars.')
input('Press a key to go back to the menu!')
print('====================================================================')
#New round
menu()
else:
print('Thank you for playing! ')
exit
main()
You could create your own python class, with the methods you already have. Than you can declare cash a class variable, with the parameter self. With self.cash you can than access the variable in every method. If that does not help please comment this answer with your issue.