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
Related
Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!
I found this code, and I'm having trouble understanding the lines 'user_hand = rps[int(user_input) - 1]' , 'com_hand = choice(rps)' , ' if rps_dict[user_hand]['strong'] == com_hand:' , 'print_result(**game_result)' , '
Why should I subtract 1 from user_input? Why put rps inside brackets next to choice? Why do you win 'if rps_dict[user_hand]['strong'] == com_hand ? Why if user_hand equal to com_hand? It doesnt make sense to me.. I know '**game_result' means it's a kwark, but I dont know why I need to declare it as a kwarg. I'm sorry if these questions seem stupid, but I'm frustrated.
from random import choice
rps = ('rock', 'paper', 'scissors')
rps_dict = {
'rock': {'strong': 'scissors', 'weak': 'paper'},
'paper': {'strong': 'rock', 'weak': 'scissors'},
'scissors': {'strong': 'paper', 'weak': 'rock'}
}
def print_result(user_score, com_score, win, lose, tie):
print('Result:', end=' ')
if user_score > com_score:
print('You win!')
elif user_score < com_score:
print('You lose...')
else:
print('Draw.')
print('--------------------')
# Print scores
print(f'Your score: {user_score}')
print(f'Computer score: {com_score}')
print('--------------------')
# Print statistics
print(f'Win: {win}')
print(f'Lose: {lose}')
print(f'Tie: {tie}')
def play(rounds):
game_result = {
'user_score': 0,
'com_score': 0,
'win': 0,
'lose': 0,
'tie': 0
}
while rounds > 0:
user_input = input(
'Enter your choice (1: Rock, 2: Paper, 3: Scissors, 0: Quit): ')
# Check whether the input is in the options
if user_input in ('1', '2', '3'):
rounds -= 1
user_hand = rps[int(user_input) - 1]
com_hand = choice(rps)
# user_hand is strong against com_hand
if rps_dict[user_hand]['strong'] == com_hand:
game_result['user_score'] += 1
game_result['win'] += 1
result = 'You win!'
# user_hand is weak against com_hand
elif rps_dict[user_hand]['weak'] == com_hand:
game_result['com_score'] += 1
game_result['lose'] += 1
result = 'You lose...'
# Tie
else:
game_result['tie'] += 1
result = 'Tie.'
print(
f'You -> {user_hand}. Computer -> {com_hand}. {result}')
elif user_input == '0':
break
else:
print('Invalid input!')
print()
print_result(**game_result)
if __name__ == "__main__":
print('Welcome to Rock-Paper-Scissors Game!')
try:
rounds = int(input('How many rounds you want to play? '))
play(rounds)
except ValueError:
print('Please input a valid number!')
This is an interesting question, and I'll do my best to discuss the lines that you said you have trouble with:
user_hand = rps[int(user_input) - 1]
The user_hand variable is used to store the choice the user inputs. user_input is the text the user directley entered. This will be saved as a string, so the code stransforms it into an integer with the int class. Next, it subtracts one from the user input (computers count from zero rather than 1). Then, it grabs the element from the list that has that index. For example, if I entered one, it would grab the list item at index 0 ("rock").
com_hand = choice(rps)
This line here is used to gather the computer's choice. As you can see from the first line, the choice function from the random module is imported directly. This allows you to use the function without specifying the module it came from. The choice function selects a random item from the specified list, which is the same rps list as before.
if rps_dict[user_hand]['strong'] == com_hand:
The if statement here gathers data from the rps_dict and compares it to the computer's hand. The rps_dict is a dictionary that contains data on which hand beats or loses to another. To translate the if statement into simpler english, it means if the hand the user's hand would beat (which can be found with rps_dict[user_hand]["strong"]), is the computer's hand, the user will win. In addition, to avoid confusion, the == operator check's for equality, and doesn't assign the variable to com_hand.
print_result(**game_result)
Here you said that you don't understand why the parameters are passed in this way. You don't really need to do it in this format, but the person who created the script decided to (possibly as it is simpler to read).
Thank you, and if you have any other questions, please comment and I'll do my best to answer them!
I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')
I am writing this code for class I have and I need some help adding exception handling. Basically what I need help with is fitting the exception handling around my user inputs so if the user inputs anything other than what is specified it'll loop back and ask the user to input the correct answer. I also need to have an exception handling with one of my functions. This is my code so far.
symbol_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CVX', 'DIS', 'GS', 'HD', 'IBM', 'INTC']
price_list = [150.75, 98.65, 340.53, 129.77, 111.77, 111.42, 175.37, 177.89, 119.83, 47.74]
invest_dict = {'AAPL': 150.75, 'AXP': 98.65, 'BA':340.53, 'CAT' :129.77, 'CVX' :117.77, 'DIS' :111.42, 'GS':175.37, 'HD':177.89, 'IBM': 119.83, 'INTC':47.74}
print("...............................Lab 8.........................")
def Greeting():
print("The purpose of this project is to provide Stock Analysis.")
def Conversions(investment_amount):
investment_amount = float(investment_amount)
Euro = float(round(investment_amount / 1.113195,2) )
Pound = float(round(investment_amount / 1.262304,2) )
Rupee = float(round(investment_amount / 0.014316,2) )
print("The amount you invest in euro is: {:.2f}" .format(Euro) )
print("The amount you invest in pounds is: {:.2f}" .format(Pound) )
print("The amount you invested in Rupees is: {:.2f}" .format(Rupee) )
def minimum_stock():
key_min = min(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The lowest stock you can buy is: ",invest_dict[key_min])
def maximum_stock():
key_max = max(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The highest stock you may purchase is: ",invest_dict[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in price_list if i>=50 and i <=200]
return(sorted(new_list))
answer = 'yes'
while answer:
print(Greeting())
investment_amount = float(input("Please enter the amount you want to invest:$ "))
if investment_amount!='':
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
print(Conversions(investment_amount))
for i in invest_dict:
i = investment_amount
if i <25:
print("Not enough funds to purchase stock")
break
elif i>25 and i <=250:
print(minimum_stock())
break
elif i >= 250 and i <= 1000:
print(maximum_stock())
break
print("This is the range of stocks you may purchase: ", invest_range(investment_amount))
answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
print("Thank you for investing.")
break
The archetypical way of doing this is something along the lines of
while True:
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
break
except ValueError:
print("Please enter a dollar amount (a floating-point number)")
print("Thank you for investing: ${:,.2f}".format(investment_amount))
Alternatively, if you're willing to import stuff, the click module has a method to do something like this:
investment_amount = click.prompt('Please enter the amount you want to invest: $', type=float)
which will keep asking the user until the input is of the correct type. For your later prompt, asking for yes/no, click.confirm() can do that for you as well.
You can try this error handling where input is taken:
while answer:
print(Greeting())
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
print("Please enter a valid amount...")
continue
print(Conversions(investment_amount))
Hope this will help.
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