Transaction_Code == "W", "w", "D" or "d"
if not, it should be running Process_Invalid_Code(Previous_Balance)
What is happening, however is if input for Transaction_Code != "W", "w", "D" or "d", it then continues to run the "What is your previous balance?" and "How much is the transaction amount?" input...
ONLY THEN, after you give input for those does it run Invalid_Transaction_Code
What I WANT to happen is for it to throw Invalid_Transaction_Code ("Invalid Transaction Code!") etc. BEFORE without wasting the users time asking for Previous Balance and Transaction..
Does that make sense?
Here is the code
#The main function definition
def main():
Name = input("What is your name? ")
Account_ID = input("What is your account ID? ")
Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ")
Previous_Balance = float(input("What is your previous balance? "))
Transaction_Amount = float(input("How much is the transaction amount? "))
if Transaction_Code == "W" or Transaction_Code == "w":
Withdrawal_Process(Previous_Balance, Transaction_Amount)
elif Transaction_Code == "D" or Transaction_Code == "d":
Deposit_Process(Previous_Balance, Transaction_Amount)
else:
Process_Invalid_Code(Previous_Balance)
#Defines the Deposit Process
def Deposit_Process(Previous_Balance, Transaction_Amount):
New_Balance = Transaction_Amount + Previous_Balance
Print_Function(New_Balance)
#Defines the Withdrawal Process
def Withdrawal_Process(Previous_Balance, Transaction_Amount):
if Transaction_Amount > Previous_Balance:
print("Invalid Transaction: Not Sufficient Funds!")
New_Balance = Previous_Balance
Print_Function(New_Balance)
else:
New_Balance = Previous_Balance - Transaction_Amount
Print_Function(New_Balance)
#The Invalid Code Function Definition
def Process_Invalid_Code(Previous_Balance):
New_Balance = Previous_Balance
print ("Invalid Transaction Code!")
print ("Please type W or w for Withdrawal")
print ("or type D or d for Deposit")
Print_Function(New_Balance)
#Defines the Print Function
def Print_Function(New_Balance):
print ("Your balance is now $", format(New_Balance, '.2f'))
#Call the main function
main()
Since all of your desired actions need Previous_Balance you must ask for it in any case:
def main():
# never used, lets ask anyway
Name = input("What is your name? ")
# we need this information at a minimum
Previous_Balance = float(input("What is your previous balance? "))
Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ")
# if its a withdrawal/deposit, find the amount and account
if Transaction_Code.upper() in "WD":
# we never use this Account_ID ...
Account_ID = input("What is your account ID? ")
Transaction_Amount = float(input("How much is the transaction amount? "))
if Transaction_Code.upper() == "W":
Withdrawal_Process(Previous_Balance, Transaction_Amount)
else:
Deposit_Process(Previous_Balance, Transaction_Amount)
else:
# they've entered a bad code
Process_Invalid_Code(Previous_Balance)
You may want to also try and use raw_input() as oppose to input() where necessary or cast the output using variable_name to get rid of tracback error.
Related
Right now I have working code that successfully asks the user if they would like to continue on with the program after each input. What I would like to do, however, is instead to allow the user to type the string "exit" at any time to terminate the program. That way I do not need to ask the user after each input and I can instead place a print line at the start letting them know to type "exit" at any time to quit.
min_zip = "00001"
max_zip = "99999"
Y = ["YES", "Y"]
def cont_confirm():
"""
Repeats after every question asking the user
if they would like to continue or not.
"""
proceed = input("Do you want to continue with the voter Registration? ")
if proceed.upper() not in Y:
print("Exiting program.")
sys.exit(0)
def main():
# Loading variables
f_name = ""
l_name = ""
age = oldest_age + 1
citizen = ""
state = ""
zipcode = -1
# Main body
print("****************************************************************")
print("Welcome to the Python Voter Registration Application.")
cont_confirm()
# Ensures name is alpha characters
while not f_name.isalpha():
f_name = input("What is your first name? ")
cont_confirm()
# Ensure name is alpha characters
while not l_name.isalpha():
l_name = input("What is your last name? ")
cont_confirm()
# Validates within age range
while (age < 0 or age > oldest_age):
print("What is your age? (18-100) ")
age = float(input())
if age < 18:
print("You are not old enough to vote. Exiting program.")
sys.exit(0)
cont_confirm()
# Validates citizen status
citizen = input("Are you a U.S. Citizen? ")
if citizen.upper() not in Y:
print("You are not a U.S. Citizen. Exiting program.")
sys.exit(0)
cont_confirm()
# Validates state residence and ensures the input matches one of the 50 U.S. state codes
while state not in state_abb:
state = str.upper(input("What state do you live? (ex. Texas = TX) "))
cont_confirm()
# Validates zipcode as a digit and ensures it is within the min/max
valid_zip = False
while not valid_zip:
zipcode = input("What is your zipcode? ")
if zipcode.isdigit():
if int(min_zip) <= int(zipcode) <= int(max_zip):
valid_zip = True
# Finally, prints all input info and ends.
print("Thank you for registering to vote. Here is the information we received: ")
print(f"Name: {f_name} {l_name}")
print(f"Age: {int(age)}")
print(f"U.S. citizen: {citizen}")
print(f"State: {state}")
print(f"Zipcode: {zipcode}")
print("Thanks for trying the Voter Registration Application. Your voter",
"registration card should be shipped within 3 weeks.")
print("****************************************************************")
main()
def input_with_exit(message):
i = input(message)
if i == "exit":
exit() # or sys.exit(0)
else:
return i
And replace all instances of input outside of this method with input_with_exit.
I have create functions to simulate ATM system, when asking the user to make deposit everything goes well but the problem is when the user make a withdraw. If the amount is greater than the balance I have the new balance in negative value. And need some help to correct this behavior.
My functions:
def show_balance(balance):
print(f"Current Balance: ${balance}")
def deposit(balance):
amount = input("Enter amount to deposit: ")
amount = float(amount)
result = balance + amount
return result
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
result = balance - withdraw
return result
Here is when using the functions:
# Display ATM menu to user
while True:
option = input("Choose an option: ")
if option == "1":
account.show_balance(balance)
elif option == "2":
balance = account.deposit(balance)
account.show_balance(balance)
elif option == "3":
balance = account.withdraw(balance)
account.show_balance(balance)
while True:
if balance < 0:
print("You do not have this money?")
break
else:
print("Please, provide a valid option")
Now when adding 50 using option "2" everithing works well. When the withdraw is < the balance (55) it just return a nagative value (-5). I want to print the massage: "You do not have this money?", but also keep the balance to the right amount (50 -55) => balance remain 50 and ask the user to try again.
#AKX -> Based on your precious advice, I have fixed the function doing the following:
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
if withdraw <= balance:
result = balance - withdraw
return result
elif withdraw > balance:
print("You do not have this money?")
return balance
to learn Python I'm working on a small terminal upgrade game. The user enters a number that is added to a random integer to get a score (called "Films Produced" in game). The problem I can't seem to fix is every time the player goes to the menu and back then back to entering more numbers the previous number is deleted instead of added on to the new one.
Here is the code:
print("TERMINAL FILM by Dominick")
print("---------------------")
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score = user_input
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game()
def game():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game()
else:
filmClicker()
game()
So I want the player to be able to insert a number, the number gets added to another number by the computer, and then a final number is spit out. I got all that working. But it doesn't save when you do that multiple times. Which I don't want, I want it to stack each time you do it.
Sorry if I poorly explained it, I can answer more about it if needed. Any help is appreciated.
UPDATE:
I removed the score = "input" variable and declared it out of any function. But it's still not saving. Here is a better answer as to what I want it to do:
In the picture below I start at the game menu. I then decide to make films, I do it 5 times. But then when I go back to the menu and check my balance, the balance equals the last time I made films and not the TOTAL films. What I want it to do is add up all of the films. So in this case 48 + 49 + 9 + 38 + 25 instead of having just the last set (which is 25 in this case), to get a total balance which can be displayed by going to the menu and typing "B."
Here is the current code:
import random
score = 0
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
SECOND UPDATE:
Updated Code:
import random
score = 0
# PRINT BLANK LINE
def press_enter():
press_enter = print(input(""))
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score += user_input
produced = random.randint(1, 50)
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score += produced
print("")
print(">> You produced:", produced, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
In the picture below it's printing how much the player is producing from that turn but I also am testing the score (which is what the 6 and 49 stand for). It's scaling weird like that, where it adds a certain amount after every turn. Any way to fix this?
I think you are looking for the += operator.
Keep the score = 0 at the top of the file to initialize the variable, then use score += user_input to keep a running tally. This is the same as writing score = score + user_input.
In your filmClicker function, you should remove the following line:
score = user_input
By assigning to it, you've essentially erased its previous value which is why it doesn't accumulate between rounds.
For saving data, You can Use Files in python
For Saving:
f=open("data_game.txt","w")
f.write(<your score>)
f.close()
For Reading:
f=open("data_game.txt","r")
score=f.read()
print(score)
f.close()
This is my atm, it has a pin code protection thing and can basically run like a normal atm, however i need to make it so it remembers you and your balance everytime you log out and in etc. ive tried doing this with a blank text file(nothing is in the text file) and linked it into my code (as you can see) but it doesnt work, im not sure what i have to add etc. any help?
balance = float(0)
userInput = None
path = 'N:\ATM.txt'
username = 'some_username'
with open(path, 'r') as file:
for user in file.readlines():
if user == username:
print("welcome back")
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
totalTrails = 3;
currentTrail = 0;
status = 1;
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"
You are opening the file in 'r' mode, which means read only, you should use 'r+' if you want to read and write in it.
You are not writing anything to the file - that's done by write() method - in your case
file.write("string I want to write to the file");
After you are done writing to the file, close it - file.close()
Im trying to create a pin protection thing for my ATM and you can enter a code etc. It then asks you for it however I want it so if you enter the wrong passcode it says incorrect try again and you cant continue into the main program. Maybe there could be a certain amount of tries? and also don't I have to write to a file if I want to save stuff? but nevermind that unless you know how I could use it in my code....
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
code = raw_input("Please enter a 4 digit pin to use as your passcode: ")
code = int(input('Please enter the 4 digit pin on your card:'))
if code == (code): print("correct pin!")
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
# take the code as a string
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
#validate that the code is a number and is 4 digit
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
# set trails and trail counter
totalTrails = 3;
currentTrail = 0;
status = 1;
# take input from user and compare codes
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "$" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"