I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
def main_menu(subtotal):
while True:
print("1) Appetizers")
print("2) Option 2")
print("3) Option 3")
print("4) Option 4")
print("5) Option 5")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 5 or choice < 1:
print("Please choose an option from 1 to 5")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 1:
appetizers(subtotal)
"""
elif choice == 2:
option_2(subtotal)
elif choice == 3:
option_3(subtotal)
elif choice == 4:
option_4(subtotal)
elif choice == 5:
end(subtotal)
return subtotal
"""
def appetizers(subtotal):
while True:
print("1) Option 1")
print("2) Option 2")
print("3) Option 3")
print("4) Return to Main Menu")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
product_amount = 1
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 4 or choice < 1:
print("Please choose an option from 1 to 4")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 4:
return subtotal
else:
while True:
try:
product_amount = int(input("How many would you like? "))
break
except ValueError:
print("Please enter whole numbers only.")
while product_amount > 100000 or product_amount < 1:
print("Please choose an option from 1 to 100,000")
product_amount = int(input("How many would you like? "))
if choice == 1:
subtotal = subtotal + (product_amount * 4.99)
elif choice == 2:
subtotal = subtotal + (product_amount * 2.99)
elif choice == 3:
subtotal = subtotal + (product_amount * 8.99)
For this project's sake, I don't want to use global variables. I only want to use the subtotal variable as a parameter throughout the program and continuously alter its value throughout the program and make calculations with it. I want to do this by passing it through other functions.
Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:
# ...
if choice == 1:
subtotal = appetizers(subtotal)
Related
def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue
I've been attempting to code this program for the past half a month or so but I'm stumped and I need to make substantial progress soon to meet my deadline, any help/advice would be appreciated. Apologies for the bad formatting, thanks for any help you can provide.
def main():
choice = printMenu()
print(choice)
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4]: Exit")
def choice = int(input("Enter your choice: "))
while choice !=0:
elif choice== 1:
print("$52,324")
elif choice== 2:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice== 3:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
if sum <= "52,324"
print("You're eligible for NRAS!")
else
print ("Sadly, you're not eligible.")
elif choice== 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
I have corrected most of the mistakes and the code works fine. I have also added comments to highlight the changes I made.
But there a lot of questionable things that were going on in this code. I suggest you to look into python syntax properly.
def add_num(a,b):
sum = a+b
return sum
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4] Exit")
ch = int(input('Enter your choice : ')) # added a variable to read the choice.
return ch # then return this choice when this function is called.
def choice(choice):
while choice != 0:
if choice== 1: # changed the elif to if.
print("$52,324")
break # added a break due to infinite loop
elif choice == 2:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice == 3:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
SUM = add_num(num1, num2) # calling the add_num function here.
if SUM <= 52324: # changed this to int type instead of a string.
print("You're eligible for NRAS!")
else:
print ("Sadly, you're not eligible.")
elif choice == 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
def main():
ch = menu()
choice(ch)
if __name__ == "__main__": # this is how you call a main() in python.
main()
I am trying to create an ATM that asks for a user name to log in and then for each user have three separate accounts to pick from. Within each of those accounts allow them to deposit, withdraw, and view balance. My problem is I am not very good with lists and I believe that is what is needed. I can not get the code to log in as a new user once I have already gone threw the code. example: I create a user Bob and log in and deposit money. Then I log out of Bob and want to create a new user Tim. when I create Tim it wont let me log it. It will keep giving me the same menu every time I put in Tim.
I believe I need to create a list of users, then a list for each user and I do not understand how to do so. Seeing from my code I just use set values for the funds in each account. Could this be a problem with why the main log in wont allow me to use another user?
user_list = []
data_list = []
index = -1
user_input = 0
user_account = 0
credit_input = 0
checking_input = 0
saving_input = 0
while user_input != 3:
print("1: Login\n2: New User\n3: Exit")
user_input = int(input("Please pick an option: "))
if user_input == 1:
username = input("Login: ")
while username not in user_list:
username = input("No user, try again: ")
index = user_list.index(username)
while user_account != 4:
print("Accounts:\n\n1: Credit\n2: Checking\n3: Savings\n4:Exit ")
user_account = int(input("Please pick an option: "))
if user_account == 1:
credit_funds = 0
while credit_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Credit Account Balance")
print("4: Exit")
credit_input = int(input("Pick an option: "))
if credit_input == 1:
number = int(input("Deposit amount: "))
credit_funds += number
print("Deposit of $", number)
elif credit_input == 2:
number = int(input("Withdraw amount: "))
while number > credit_funds:
print("\nInsufficient Funds")
break
else:
credit_funds -= number
print("\nSuccessful Withdraw of $", number)
elif credit_input == 3:
print("Avalable balance: $", credit_funds)
elif user_account == 2:
checking_funds = 0
while checking_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Checking Account Balance")
print("4: Exit")
checking_input = int(input("Pick an option: "))
if checking_input == 1:
amount = int(input("Deposit amount: "))
checking_funds += amount
print("Deposit of $", amount)
elif checking_input == 2:
amount = int(input("Withdraw amount: "))
while amount > checking_funds:
print("\nInsufficient Funds")
break
else:
checking_funds -= amount
print("\nSuccessful Withdraw of $", amount)
elif checking_input == 3:
print("Avalable balance: $", checking_funds)
elif user_account == 3:
saving_funds = 0
while saving_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Saving Account Balance")
print("4: Exit")
saving_input = int(input("Pick an option: "))
if saving_input == 1:
number3 = int(input("Deposit amount: "))
saving_funds += number3
print("Deposit of $", number3)
elif saving_input == 2:
number3 = int(input("Withdraw amount: "))
while number3 > saving_funds:
print("\nInsufficient Funds")
break
else:
saving_funds -= number3
print("\nSuccessful Withdraw of $", number3)
elif saving_input == 3:
print("Avalable balance: $", saving_funds)
elif user_input == 2:
username = input("Please pick a username: ")
while username in user_list:
username = input("Pick another please: ")
user_list.append(username)
When the user 'logs out' (presses 4 when logged in) you set user_account to 4 (an exit condition). It is never unset after that. Therefore when another user tries to login, the program tests user_account != 4, fails that test, and never enters the while loop (while user_account != 4). I suspect the same will happen for all other exit conditions.
I suggest resetting the value of any inputs to 0 after taking the appropriate action. Alternatively, use while True: and explicitly break when an exit condition is reached.
For example:
while True:
print("1: Login\n2: New User\n3: Exit")
user_input = int(input("Please pick an option: "))
if user_input == 1:
print("Option 1 selected")
# DO SOMETHING
elif user_input == 2:
print("Option 2 selected")
# DO SOMETHING
elif user_input == 3:
break
users={};stop='r'
def login(name,users):
if name in users.keys():
return True
return False
def create():
name=input('please write your name')
users[name]=0
def main(users):
print('Welcome to my ATM\n')
buff=input('SELECT one of the following:\nC)create account\nL)login')
if(buff=='C' or buff=='c'):
create()
elif(buff=='L' or buff=='l'):
name=input('name: ')
buff2=login(name,users)
if(buff2==False):
print('your name is not in account list')
elif(buff2==True):
buff=input('SELECT:\nA)cash report\nD)delete account')
if(buff=='A' or buff=='a'):
print(users[name])
elif(buff=='D' or buff=='d'):
k=users.pop(name)
print('finished! ')
while(stop=='r'):
buff3=input("press 's' to stop ATM otherwise press enter to continue ...")
if(buff3=='s'):
break
main(users)
I wish this works.
for an assignment, I made a menu and must have it work in a way to execute multiple functions. However, the problem is that when I use the menu and put in an answer that doesn't exist, I cannot get it to work correctly. So when I re-enter an option number for "Incorrect option, try again: ", I do not get the number re-evaluated to execute. Since my code is far from finished, right now I want to be able to choose "4" as an input and get "Incorrect option, try again" as an output and input "1" into this to get the output "Choose the level of difficulty".
def main_menu():
print(10*"=","GAME",10*"=",'\n')
print("1. Choose level of difficulty ")
print("2. Start Game")
print("3. Exit the Game",'\n')
print("Current Difficulty: /5")
print("Highest Score Reached:",'\n')
option=input("Enter an option: ")
return option
def user_input():
while True:
try:
if option==1:
difficulty()
break
elif option==2:
start()
break
elif option==3:
exit()
break
except:
option=input("Incorrect option, try again: ")
def difficulty():
d=int(input("Choose level of difficulty: "))
if 1<=d<=5:
start()
else:
int(input("Incorrect option, try again: "))
#difficulty()
return d
Here a is modified version of your code which I believe does what you are looking for.
def main_menu():
print(10 * "=", "GAME", 10 * "=", '\n')
print("Current Difficulty: /5")
print("Highest Score Reached:", '\n')
while True:
print("1. Choose level of difficulty")
print("2. Start Game")
print("3. Exit the Game", '\n')
try:
option = int(input("Enter an option: "))
if option == 1:
difficulty()
elif option == 2:
start()
elif option == 3:
return
else:
print("Incorrect option, try again!")
except ValueError:
print("Invalid option.")
def difficulty():
try:
d = int(input("Choose level of difficulty: "))
if 1 <= d <= 5:
print(d)
start()
else:
print("Incorrect option, try again.")
except ValueError:
print("Invalid value.")
def start():
print("Starting game...")
if __name__ == "__main__":
main_menu()
Let me know if anything is misunderstood or mistaken.
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