Here are the functions in question:
def ATM():
global mode
pinNum = input('Please enter your 4 digit secret code: ')
userBalance = float(dict2[pinNum])
while mode == 0:
if pinNum in dict1:
greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum]))
if greet == '1':
balance(userBalance)
elif greet == '2':
withdraw(userBalance)
elif greet == '3':
deposit(userBalance)
elif greet == '4':
mode = 1
def balance(userBalance):
print('Your current balance is {}.'.format(userBalance))
def deposit(userBalance):
amount = input('Please enter the amount you wish to be deposited: ')
userBalance += float(amount)
return userBalance
def withdraw(userBalance):
amount = input('Please enter the amount you wish to withdraw" ')
if userBalance - float(amount) < 0:
print('You do not have sufficient funds.')
else:
userBalance -= float(amount)
I am having trouble making adjustments to the balance when I call the deposit or withdraw function within ATM(). I am thinking I may not be returning the data correctly in the deposit and withdraw functions. This program is simulating an ATM for reference and dict1 and dict2 are defined outside the functions. Any help is appreciated.
I think that this can help you:
def ATM():
global mode
pinNum = input('Please enter your 4 digit secret code: ')
userBalance = float(dict2[pinNum])
actions = {
'1': balance,
'2': withdraw,
'3': deposit
}
while mode == 0:
if pinNum in dict1:
greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum]))
if greet == '4':
break
else:
userBalance = actions.get(greet)(userBalance) or userBalance
def balance(userBalance):
print('Your current balance is {}.'.format(userBalance))
def deposit(userBalance):
amount = input('Please enter the amount you wish to be deposited: ')
userBalance += float(amount)
return userBalance
def withdraw(userBalance):
amount = input('Please enter the amount you wish to withdraw" ')
if userBalance - float(amount) < 0:
print('You do not have sufficient funds.')
else:
userBalance -= float(amount)
return userBalance
Related
I want it so that my current balance will be the as the amount withdrawn for the next loop.
Enter pin:123
1 – Balance Inquiry
2 – Withdraw
3 – Deposit
X – Exit
Enter your choice:2
Hi name1.
Your current balance is 50000
Enter amount to withdraw: 400
Transaction Successful
Your current balance is 49600
Enter pin:123
1 – Balance Inquiry
2 – Withdraw
3 – Deposit
X – Exit
Enter your choice:2
Hi name1.
Your current balance is 50000 *** Problem ***
Enter amount to withdraw:
This is currently my code. (sorry for the messy code as I am a beginner)
pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]
def main():
while True:
pin_input = input('Enter pin:')
try:
n = int(pin_input)
except:
break
if n in pin:
print('1 – Balance Inquiry')
print('2 – Withdraw')
print('3 – Deposit')
print('X – Exit')
choice = input('Enter your choice:')
c = int(choice)
if choice == 'X':
print('Thank you for banking with us!')
break
else:
pol = pin.index(n)
if c == 1:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
elif c == 2:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
withdraw = int(input('Enter amount to withdraw: '))
if withdraw > balance[pol]:
print('Not enough amount')
else:
difference = balance[pol] - withdraw
print('Transaction Successful')
print(f'Your current balance is {difference}')
elif c == 3:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
deposit = int(input('Enter amount to deposit: '))
sums = deposit + balance[pol]
print('')
print(f'Your current balance is {sums}')
main()
welcome to Python. I see what is your problem. When you handle the withdrawal you create a new variable and performed the subtraction you just displayed the new result and never updated it.
So to solve it you need to replace this code:
difference = balance[pol] - withdraw
print(f'Transaction Successful.\nYour current balance is {difference}')
with:
balance[pol] -= withdraw
print(f'Transaction Successful.\nYour current balance is {balance[pol]}')
I took the liberty to edit your code a bit and make it more "professional" but also so that you could read and understand it (I added comments for you to read).
pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]
def main():
while True:
try:
pin_input = int(input('Enter pin:'))
except ValueError: #It's bad practice to leave it just as "except".
break
if pin_input in pin:
print('1 – Balance Inquiry')
print('2 – Withdraw')
print('3 – Deposit')
print('X – Exit')
choice = input('Enter your choice:')
#As you can see, I have removed the conversion because no one will care if it is int or str, it's happening behind the scene.
if choice == 'X':
print('Thank you for banking with us!')
break
#You don't need the else statement because if the choice would be 'X' it would automatically exit.
pol = pin.index(pin_input)
if choice == '1':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
elif choice == '2':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
withdraw = int(input('Enter amount to withdraw: ')) #Assuming the user will write an integer.
if withdraw > balance[pol]:
print('Not enough amount')
break # Let's just add that here (easier to read) and we don't need the else statement anymore.
balance[pol] -= withdraw
print(f'Transaction Successful.\nYour current balance is {balance[pol]}')
elif choice == '3':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}')#Using \n to downline instead of using two prints.
deposit = int(input('Enter amount to deposit: ')) #Assuming the user will write an integer. the user
sums = deposit + balance[pol]
print(f'\nYour current balance is {sums}') #\n instead of a whole print function.
if __name__ == "__main__": #Use this script as the main script.
main()
Nice work, keep up with this good job!
Also, I want to add my own way of creating an ATM machine. I hope that one day when you will learn and have more knowledge you would open this again and try to understand this. (This code will work only in py-3.10 or higher)
Code:
class ATM:
def __init__(self, pin) -> None:
self.pin = pin
def Balance(self) -> str:
return f"{data[self.pin][1]}, Your balance is: {data[self.pin][0]}"
def Withdraw(self) -> str:
try:
withdraw = int(input('Enter amount to withdraw: '))
if withdraw > data[self.pin][0]:
return f"{data[self.pin][1]}, Looks like you can't withdraw {withdraw}$ due to lower balance.\nYou can withdraw up to {data[self.pin][0]}$."
data[self.pin][0] -= withdraw
except ValueError:
return f"{data[self.pin][1]}, Looks like there was an error with your request to withdraw. Please try again."
return f"{data[self.pin][1]}, You've successfully withdrawn {withdraw}$. Your remaining balance is: {data[self.pin][0]}$."
def Deposit(self) -> str:
try:
deposit = int(input('Enter amount to Deposit: '))
data[self.pin][0] += deposit
except ValueError:
return f"{data[self.pin][1]}, Looks like there was an error with your request to deposit. Please try again."
return f"{data[self.pin][1]}, You've deposited {deposit}$ into your account. Your balance right now is {data[self.pin][0]}"
if __name__ == "__main__":
data = {
123 : [50000, "name1"],
456 : [2000, "name2"],
789 : [500, "name3"]
}
options = {
1 : "Balance Inquiry",
2 : "Withdraw",
3 : "Deposit",
'X' : "Exit"
}
running = True
while running:
try:
pin = int(input("Enter your pin: "))
if pin in data:
user = ATM(pin)
else:
print(f"User {pin} Doesn't exist. Please check your input and try again.")
continue
for key, value in options.items():
print(f"Press '{key}' for {value}")
while True:
action = input("Please enter your action: ")
match action:
case '1':
print(user.Balance())
break
case '2':
print(user.Withdraw())
break
case '3':
print(user.Deposit())
break
case 'X' | 'x':
running = False
break
case _:
print("This action doesn't exist. Please try again.")
continue
except ValueError:
print("There is an error in the given pin. Please try again.")
continue
I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)
First of im sorry about bombarding my post with a bunch of code, but im putting it here hoping that it will help you guys understanding my question better.
I am trying to figure out why my IDE is unwilling to execute the first function of my code. Obviously im doing something wrong, but im to unexperienced to see it for myself. All help would be greatly appriciated.
If you have any further comments or tips on my code feel free contribute.
import random
print("Press '1' for New Single Player Game - Play against computer component: ")
print("Press '2' for New Two Player Game - Play against another person, using same computer: ")
print("Press '3' for Bonus Feature - A bonus feature of choice: ")
print("Press '4' for User Guide - Display full instructions for using your application: ")
print("Press '5' for Quit - Exit the program: ")
def choose_program():
what_program = int(input("What program would you like to initiate?? Type in the 'number-value' from the chart above: "))
if what_program == 1 or 2 or 3 or 4 or 5:
program_choice = int(input("Make a choice: "))
if (program_choice > 5) or (program_choice < 1):
print("Please choose a number between 1 through 5 ")
choose_program()
elif program_choice == 1:
print("You picked a New Single Player Game - Play against computer component")
def single_player():
start_game = input("Would you like to play 'ROCK PAPER SCISSORS LIZARD SPOCK'?? Type 'y' for YES, and 'n' for NO): ").lower()
if start_game == "y":
print("Press '1' for Rock: ")
print("Press '2' for Paper: ")
print("Press '3' for Scissors: ")
print("Press '4' for Lizard: ")
print("Press '5' for Spock: ")
elif start_game != "n":
print("Please type either 'y' for YES or 'n' for NO: ")
single_player()
def player_one():
human_one = int(input("Make a choice: "))
if (human_one > 5) or (human_one < 1):
print("Please choose a number between 1 through 5 ")
player_one()
elif human_one == 1:
print("You picked ROCK!")
elif human_one == 2:
print("You picked PAPER!")
elif human_one == 3:
print("You picked SCISSORS!")
elif human_one == 4:
print("You picked LIZARD!")
elif human_one == 5:
print("You picked SPOCK!")
return human_one
def computers_brain():
cpu_one = random.randint(1, 5)
if cpu_one == 1:
print("Computers choice iiiiiis ROCK!")
elif cpu_one == 2:
print("Computers choice iiiiiis PAPER!")
elif cpu_one == 3:
print("Computers choice iiiiiis SCISSORS!")
elif cpu_one == 4:
print("Computers choice iiiiiis LIZARD!")
elif cpu_one == 5:
print("Computers choice iiiiiis SPOCK!")
return cpu_one
def who_won(human, cpu, human_wins, cpu_wins, draw):
if human == 1 and cpu == 3 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 2 and cpu == 1 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 3 and cpu == 2 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 4 and cpu == 2 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 5 and cpu == 1 or cpu == 3:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == cpu:
print("Human & computer think alike, such technology")
draw = draw.append(1)
else:
print("Computer have beaten it's master, incredible..")
cpu_wins = cpu_wins.append(1)
return
def end_score(human_wins, cpu_wins, draw):
human_wins = sum(human_wins)
cpu_wins = sum(cpu_wins)
draw = sum(draw)
print("Humans final score is: ", human_wins)
print("Computers final score is: ", cpu_wins)
print("Total draws: ", draw)
def main():
human = 0
human_wins = []
cpu = 0
cpu_wins = []
draw = []
finalhuman_wins = 0
finalcpu_wins = 0
finaldraw = 0
Continue = 'y'
single_player()
while Continue == 'y':
human = player_one()
cpu = computers_brain()
who_won(human, cpu, human_wins, cpu_wins, draw)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
end_score(human_wins, cpu_wins, draw)
main()
elif program_choice == 2:
print("You picked a New Two Player Game - Play against another person, using same computer")
elif program_choice == 3:
print("You picked the Bonus Feature - A bonus feature of choice")
elif program_choice == 4:
print("You picked the User Guide - Display full instructions for using your application")
elif program_choice == 5:
print("You picked to Quit - Exit the program")
return program_choice
elif what_program != 1 or 2 or 3 or 4 or 5:
print("To initiate a program you need to type in the appropriate number to initiate this program, either 1, 2, 3, 4 & 5 ")
choose_program()
Outout in IDE:
Press '1' for New Single Player Game - Play against computer component:
Press '2' for New Two Player Game - Play against another person, using same computer:
Press '3' for Bonus Feature - A bonus feature of choice:
Press '4' for User Guide - Display full instructions for using your application:
Press '5' for Quit - Exit the program:
Process finished with exit code 0
Thank you in advance for your help :)
I am trying to make a bank program. I have finished most of my code but I am stuck on one thing. Every time I try to deposit or withdraw and enter a character different from a number, my program crashes. I just wanted to know how I could use a try and except statement to make this not crash. My code is attached below.
def printmenu():
print("======================")
print("Welcome to Dons Bank")
print("What can I do for you?")
print("1 - Withdraw Funds")
print("2 - Deposit Funds")
print("3 - Show Balance")
print("4 - Quit")
def main():
myBalance = 1000
userChoice = 0
invalidcharac = True
printmenu()
while invalidcharac:
try:
userChoice = int(input("Please choose one of the above options: "))
invalidcharac = False
except ValueError:
print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
while userChoice != 4:
if userChoice == 1:
amount = int(input("Amount to withdraw: "))
while myBalance - amount < 0:
print("Sorry: you don't have that much money in your account.")
amount = int(input("Amount to withdraw: "))
myBalance = myBalance - amount
print("New balance: ", myBalance)
elif userChoice == 2:
amount = int(input("Amount to deposit: "))
myBalance = myBalance + amount
print("New balance: ", myBalance)
elif userChoice == 3:
print("Balance: ", myBalance)
elif userChoice == 4:
continue
else:
print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
print("Thank you. Goodbye!")
main()
As always, you can tweak the messages
def printmenu():
print("=" * 20)
print("Welcome to Dons Bank")
print("What can I do for you?")
print("1 - Withdraw Funds")
print("2 - Deposit Funds")
print("3 - Show Balance")
print("4 - Quit")
print("=" * 20)
def main():
myBalance = 1000
userChoice = 0
# invalidcharac = True
printmenu()
while True:
try:
userChoice = int(input("Please choose one of the above options: "))
except ValueError:
print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
continue
if userChoice == 1:
try:
amount = int(input("Amount to withdraw: "))
while myBalance - amount < 0:
print("Sorry: you don't have that much money in your account.")
amount = int(input("Amount to withdraw: "))
myBalance = myBalance - amount
print("New balance: ", myBalance)
except:
print("Invalid option. Reset to menu.")
continue
elif userChoice == 2:
try:
amount = int(input("Amount to deposit: "))
myBalance = myBalance + amount
print("New balance: ", myBalance)
except:
print("Invalid option. Reset to menu.")
continue
elif userChoice == 3:
print("Your balance is: ", myBalance)
elif userChoice == 4:
break
else:
print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
print("Thank you. Goodbye!")
main()
How would you encrypt using 2 keys instead of 1 key? It is for school.
So it would ask how much to shift the code by, then ask how many times to shift again, which would shift it even further.
def runProgram():
def choice():
userChoice = input('Do you wish to Encrypt of Decrypt? Enter E or D: ').lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getPees():
try:
userpees = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getpees()
else:
if userpees < 1 or userpees > 26:
print("Invalid Option. Please try again.")
getpees()
else:
return userpees
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
def getpranslated(userChoice, message, pees):
pranslated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
pranslated += chr(num)
else:
for character in message:
num = ord(character)
num -= key
pranslated += chr(num)
return pranslated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
pees= getPees()
sqq= getTranslated(userChoice, message, key)#Runs function to translate message, using the choice, message and key variables)
spp= getTranslated(userChoice, message, pees)
dranslatedMessage = sqq + spp
print( 'hi' + int(spp), int(sqq) )
runProgram()