Limiting time.sleep() function to one loop in python - python

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

Related

How do I apply the sellProduct method to each choice in the menu?

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 !

How to combine guesses/credits

How do I combine my guesses and credits in my python guessing game? for example, if it took me 6 guesses with the first attempt then when I press y to do the game again and it took me 10 guesses how can I get those two to combine for 16 total guesses, same thing with credits (sorry if its a bad explanation) Heres what I have so far:
import random
# this function is for the welcome part of my code or the part where I give instructions on how to play
def game_intro():
print(" ---- G U E S S I N G G A M E ----")
print("\n L E T S P L A Y ")
print("""\nThe adjective of this game is to solve guess a 3 digit combination,
and it is your job to guess numbers 100-999 to find that combination!!""")
print("Credits")
print("1-4 guesses: up to 60 credits")
print("5-10 guesses: 10 credits")
print("if guesses more than 10 no credits")
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
num_of_guess = 0
while not done:
try: # anything other than a number between 100, 999 gets an error
user_input = int(input("\nEnter a guess between 100-999: "))
num_of_guess += 1
if user_input == i:
print('you got it right in ', str(num_of_guess), 'tries')
print(creditScore())
new_game_plus()
elif user_input < i: # if player guess lower than I tell player
print("To low")
elif user_input > i: # if player guess higher than tell players
print("to high")
elif user_input not in range(100, 999):
print("Invalid. Enter a number between 100-999")
num_of_guess += 1
except ValueError:
print("Invalid. Enter a number between 100-999")
def new_game_plus():
global done, num_of_guess
new_game = input("Do you want to start a new game? press y for yes n for no: ")
if new_game == "y":
check_range_main()
else:
done = True
def statistics(new_game): # statistics for games after players finish
global total_games, num_of_guess
if new_game == "n":
print()
total_games += 1
num_of_guess += num_of_guess
print("P O S T G A M E R E P O R T")
print()
print(f"total {total_games} games played.")
print('total guesses', num_of_guess)
print("your average guess per game is", num_of_guess / total_games)
def creditScore():
global credit, done
credit = num_of_guess
if 1 <= num_of_guess <= 4:
print("game credits", 60 / credit)
elif 5 <= num_of_guess <= 10:
print("game credits", 10)
else:
print("no credits")
#print("total credits", )
# def functions matches() that computes and returns the number of matching digits in a guess, you may assume that the
# combination and the guess are unique three-digit numbers.
# def play_one_game():
# global done
# i = random.randint(100, 999)
# while not done:
# try:
# user_input = int(input("\nEnter a guess between 100-999: "))
# if user_input == i:
# print("Nice Job")
# done = True
#
# elif user_input > i:
# print("input to high")
#
# elif user_input < i:
# print("input to low")
#
# elif user_input not in range(100, 999):
# print("invalid input a number in range of 100,999")
#
# except ValueError:
# print("invalid. input a number between 100,999")
# this is where all the different functions go
def main():
game_intro()
check_range_main()
new_game_plus()
statistics("n")
creditScore()
# play_one_game()
if __name__ == '__main__':
main()
Put out the num_of_guess = 0 from inside the check_range_main()
...
num_of_guess = 0 # stores how many guess I have made
total_games = 1 # stores how many games I played
done = False # set done to False
credit = 0
num_of_guess = 0
def check_range_main():
global num_of_guess, credit # global for getting stuff outside functions
i = random.randint(100, 999) # generate number at random
while not done:

Where to place sys.exit() for termination of code

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]$

Python: i want to make a variable that stores decrementing my 'limit' variable but it's not decrementing

(Python beginner Problem)::: I want to make a variable that store my limit variable but I just want to decrement it while looping. it's like that i want to make life left for the user.
import random
limit = 5
i = 1
while i <= limit:
decrement_00 = limit #Problem1
decrement_00 = decrease - 1
num = random.randint(1,6)
user = int(input("enter a number: "))
if user == num:
print("You're correct")
break
else:
print("Try again.")
print(f"You only have {decrement_00} left.")
i = i + 1
Try this :
import random
limit = 5
i = 1
while i <= limit:
#decrement_00 = limit #Problem1
limit = limit - 1
num = random.randint(1,6)
user = int(input("enter a number: "))
if user == num:
print("You're correct")
break
else:
print("Try again.")
print(f"You only have {limit} left.")
#i = i + 1
Solution: If you want to show the remaining iterations(limit), you can simply print (limit - i) instead of using extra variables.
Now comes to the problem in your code, you are printing decrement_00 to show to the user, just review the following two lines and you will understand the mistake.
decrement_00 = limit #Problem1
decrement_00 = decrease - 1
Hint:
Ever initialized decrease?
will decrement_00's value change?

Python Positioning correctly in a while loop

My current code works but when the option menu appears, and i select an option, its supposed to repeat from the selection again, however my code restarts from the start where it asks to enter a number rather than entering an option.
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
So it means that I need to reposition my code within the while loop, or take the input stage to a different position?
You need a nested loop
(tried to change your original code as little as possible) I changed it to include your options menu within a while loop (in addition to another break statement outside the while loop, to make sure the program doesn't repeat itself (unless you want it to...)).
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
choice = -1 # new
while(choice != 0): # new
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
break # new
keep in mind this COULD be a good deal more robust, and there exists no functionality for handling options selected outside the ones specified (though should someone enter a 5 or something it will just repeat)
Sometimes I find it cleaner to have your cope loop forever with while True and to break out of it as necessary. I also try to reduce nesting where possible, and I don't like to use exception handling for a valid input choice. Here's a slightly reworked example:
amount = 0
total = 0
while True:
n = input("Enter a number: ")
if n == "":
break
amount = amount+1
total = total + int(n)
average = total/amount
while True:
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break

Categories

Resources