So I created a procedure which would ask the user the amount of money they want to with draw from their checking account. And if do the procedure the checking should subtracted by the amount withdrawed. But when I used global it did not change the value of the variable even after the procedure.I already have established the all the variables
my code is here:
checking = 10000
savings = 10000
user_ammount_w = 0
user_currency_w = ""
def withdraw_saving (amount, country):
global checking
if country == "HKD":
if checking >= amount:
checking = checking - amount
print("The amount of money left in your checking is", checking)
else:
print("Your request of", "$"+ str(amount), country, "is greater than the amount in your
checking account this withdraw will not work")
user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
if user_choice == "1":
user_currency_w= input("Which currency would you like to withdraw from. For testing purposes
its only HKD")
user_amount_w= int(input("How much money do you want to withdraw"))
withdraw_saving (user_ammount_w, user_currency_w)
When you call your function again recursivly you are allwyas passing the amount to be subtracted as 0 as you are passing in user_ammount_w which you set globally as 0. instead i suspect you want to pass in user_amount_w which is the variable name which you have used to capture the user input.
checking = 10000
savings = 10000
user_ammount_w = 0 #<----this is the value you passing to your function
user_currency_w = ""
def withdraw_saving (amount, country):
global checking
if country == "HKD":
if checking >= amount:
checking = checking - amount
print("The amount of money left in your checking is", checking)
else:
print("Your request of", "$"+ str(amount), country, "is greater than the amount in your checking account this withdraw will not work")
user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
if user_choice == "1":
user_currency_w= input("Which currency would you like to withdraw from. For testing purposes its only HKD")
user_amount_w= int(input("How much money do you want to withdraw")) #<--you never pass this value.
withdraw_saving (user_ammount_w, user_currency_w)
withdraw_saving(20, 'HKD')
However using globals is not a good idea and there is probably a better way to design this.
Related
I am working on my first project where I ask users if they are want to calculate an investment or bond. Within this I've tried to nest another if/elif/else statement after they input investment or bond to get the user to input the necessary information for either for me to make the calculation but Python is registering an error for when I want to ask users about the bond calculation. I've tried to make it as clear as possible below:
import math
#Menu Option for Users
print("Investment: Calculate the amount of interest you'll earn on your investment")
print("Bond: Calculate the amount you'll have to pay on your home loan")
type = input("Please input either Investment or Bond to proceed:")
#casefold removes case sensitivity so user can input with or without caps.
#Investment Calculation
if type.casefold() == "Investment":
#if user inputs investment, they need to input the following information
money = input("Please input your deposit amount: ")
ir = input("Please input your interest rate as a percentage: ")
time = input("Please input how long you plan to invest for in years: ")
interest = input("Please input if you would like simple or compound interest: ")
#initialisations
simple_ir_calc = 0
comp_ir_calc = 0
if interest.casefold() == "simple":
simple_ir_calc = money (1 + ((ir/100) * time))
print(f"You will make {simple_ir_calc} on your investment")
elif interest.casefold() == "compound":
comp_ir_calc = money * math.pow((1+ (ir/100)), time)
print(f"You will make {comp_ir_calc} on your investment")
else:
print("Error. Either enter simple or compound.")
#Bond calculation
elif type.casefold() == "Bond":
#user inputs info needed to calc bond
pv = input("Please enter the present value of your property: ")
ir_b = input("Please input the interest rate as a percentage: ")
time_m = input("Please enter the number of months needed to repay the bond: ")
repayment = 0
repayment = ((ir_b/12) * pv) / math.pow(1 - (1 +(ir_b/12)), (-time))
print(f"You will have to pay {repayment} each month.")
else:
print("Error. Either input investment or bond.")
I tried to fix the indentations - so now the only 2 problems that python highlights is the expressions on line 34 and 44.
Also as a sidenote the bond repayment formula is meant to be X = (ir.pv)/(1-(1+ir)^(-time))
I just included -time at the end but I have no idea if my formula works within python
I know this is probably riddled with errors, so if you see anything else please let me know! I am very new to both python and stackoverflow so sorry for so many questions within one :(
I think this sorts out the indentation but only you know your intentions. A general comment - the code all fails if the user does not enter precisely one of your expected answers. You should pick up input errors. This might be easiest using 'Enter 1 for A, 2 for B etc'.
import math
#initialisations
simple_ir_calc = 0
comp_ir_calc = 0
#Menu Option for Users
print("Investment: Calculate the amount of interest you'll earn on your investment")
print("Bond: Calculate the amount you'll have to pay on your home loan")
choose = input("Please input either Investment or Bond to proceed:")
#casefold removes case sensitivity so user can input with or without caps.
print(choose.casefold())
#Investment Calculation
if choose.casefold() == "investment":
#if user inputs investment, they need to input the following information
money = input("Please input your deposit amount: ")
ir = input("Please input your interest rate as a percentage: ")
time = input("Please input how long you plan to invest for in years: ")
interest = input("Please input if you would like simple or compound interest: ")
if interest.casefold() == "simple":
simple_ir_calc = money (1 + ((ir/100) * time))
print(f"You will make {simple_ir_calc} on your investment")
elif interest.casefold() == "compound":
comp_ir_calc = money * math.pow((1+ (ir/100)), time)
print(f"You will make {comp_ir_calc} on your investment")
else:
print("Error. Either enter simple or compound.")
#Bond calculation
elif choose.casefold() == "bond":
#user inputs info needed to calc bond
pv = input("Please enter the present value of your property: ")
ir_b = input("Please input the interest rate as a percentage: ")
time_m = input("Please enter the number of months needed to repay the bond: ")
repayment = ((ir_b/12) * pv) / math.pow(1 - (1 +(ir_b/12)), (-time_m))
print(f"You will have to pay {repayment} each month.")
else:
print("Error. Either input investment or bond.")
Looks like indents are totally messed.
It should look like that:
# Condition
if a == 0:
b = 1
elif a == 1:
b = 2
else:
# Nested conditions
if c:
b = 3
else:
b = 9
I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I enter another value it gets added onto a previous input. Code is below:
Purchase = int(input("How much was your purchase? "))
credit_balance = 0
credit_limit = 2000
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total == credit_limit:
print("You have reached your credit limit!", Total)
You'll need to introduce a while loop to keep it going. Try this:
credit_limit = 2000
credit_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total >= credit_limit:
print("You have reached your credit limit!", Total)
Note that this will keep it going indefinitely. You'll need to add logic for the user to input a command to exit. You can use something like:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? Or type Exit to exit."))
Then:
if Purchase == 'Exit':
exit()
Edit:
Here's a version that retains the balance each time. The key difference is that a variable can equal its previous value plus a change. I rewrote a few things for clarity.
credit_limit = 2000
current_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
current_balance = current_balance + Purchase
print("Your account value right now: ", current_balance)
if current_balance == credit_limit:
print("You have reached your credit limit!", current_balance)
You can get user input infinitely if you use a while loop:
credit_balance = 0
credit_limit = 2000
while True:
purchase = int(input("How much was your purchase? "))
credit_balance += purchase # add purchase to credit_balance
print("Your account value right now: ", credit_balance)
if credit_balance >= credit_limit:
print("You have reached/exceeded your credit limit!", Total)
A good exercise would be to add some logic to ensure purchases don't exceed the credit limit.
import random, time
def main():
AIMoney = 0
AINumGen = '0'
PlayerMoney = 0
Round = 1
PlayerChoice = ""
Result = ""
if Round == 1:
print ("You are in prison for the robbing of a world famous museum. You have the choice of either betraying (by confessing your partner's involvement) your partner, or colluding. (sticking to a story, so you both keep the money as initially intended.) Your goal is to get the most money by the end, keeping your reward from the heist together. You wil play ten rounds against an A.I, attempting to beat them and this tricky game. This means there are four results in total, and you both have two options per instance:")
print ("")
print ("If both of you collude, you both stay out of prison, and you both gain a reward by splitting the amount of money you make in half. If you both collude the entire time throughout every round, it will always end in a tie for both of you. Result: +100 money for each of you.")
print ("")
print("If both of you betray each other, you both receive no penalty, but neither of you get anything out of it. +0 money for both of you. Having 0 or negative points at the end of the game will result in a loss.")
print("")
print ("If you collude, but the other person betrays you, you will be punished severely by the person taking all of the valuables. Since you put in money to even commit the heist initally, you lose money in this situation, and are put into prison for your crimes.")
print("")
if Round == 10:
print("The game has ended. Final Result:")
print("AI's Money:" + AIMoney)
print("Your Money:" + PlayerMoney)
exit
User = input("Type C to collude with your partner, and B to betray your partner.")
if User == 'C':
AINumGen == random.randint(1, 10)
Round = Round + 1
if AINumGen < '4':
Result = Result + "betrayed you."
print ("You chose to collude with your partner and they " + Result)
PlayerMoney = PlayerMoney - 200
elif AINumGen > '4':
Result = Result + "colluded with you."
print("You chose to collude with your partner and they " + Result)
print("Your money after this round: " + str(PlayerMoney))
if User == 'B':
Result = Result
Round = Round + 1
print("You chose to betray your partner and they" + Result)
print("Your money after this round: " + str(PlayerMoney))
if User == 'Debug':
main()
if Round != 10:
User = input("Type C to collude with your partner, and B to betray your partner.")
main()
else:
print("Invalid Input")
main()
I'd also appreciate any help with the rest, as the variable Round never seems to be changed -- Even if the code is run nine or so times to get the end of the game result, it doesn't do anything. I have a feeling it has something to do with the order of the operations.
Since you are calling the main() function again, the variable Round is getting reinitialized and that's why the part is being called there..
Not sure about the other variables but you need to keep a check on what you need to initialize each time when the condition is being called.
try keeping the variables out of the main function
Here is a short breakdown of what is happening:
You call main() and set Round = 1.
You play the game once.
If Round != 10 (which it is now), you print the question again, then call main().
main() sets Round as 1 again, making the loop indefinite.
You have 2 options:
Go for a for loop if you always will have 10 rounds. After 10 rounds are over, you can show the result.
Go for recursion if you can have indefinite amount of rounds. The change you will do here is pass the round number as an argument to the function. If round is 1, print the instructions and if you want to end the game, pass some specific number (eg 10) to the function.
so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,
I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)