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 ,
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.
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.
I wanted to know if there was any way to end a conditional early. For example, when I run the code and enter all values in between 0-100 the program does what it's supposed to. However, let's say I put a negative number as input #3. The program keeps on going until the very end, then I get "Invalid input. Enter a number between 0-100". I'm wondering if there is any way I can get that message as soon as I enter a number that's not in between 0-100. I'm a complete beginner, so I really don't know what I'm doing.
def e5():
stdnt1 = float(input("Enter the first grade: "))
stdnt2 = float(input("Enter the second grade: "))
stdnt3 = float(input("Enter the third grade: "))
stdnt4 = float(input("Enter the fourth grade: "))
stdnt5 = float(input("Enter the fifth grade: "))
if(0 <= (stdnt1 and stdnt2 and stdnt3 and stdnt4 and stdnt5) <= 100):
avrg = (stdnt1 + stdnt2 + stdnt3 + stdnt4 + stdnt5) / 5
print("The groups average is", avrg)
grades = [stdnt1, stdnt2, stdnt3, stdnt4, stdnt5]
grades.sort()
print("The lowest grade is", grades[0])
else:
print("Invalid input. Enter number between 0-100")
I would recommend writing a function that takes the input and processes it.
def get_input(prompt):
response = float(input(prompt))
if 0 <= response <= 100:
return response
raise ValueError("Invalid input - enter number between 0-100")
This also has the advantage of simplying the first 5 lines of your function.
def e5():
stdnt1 = get_input("Enter the first grade")
# ...
You could also change the function to continue to ask the user using a while loop for valid input.
Hopefully this is enough to get you started.
Yes. Perform some preliminary checks as soon as you get the input. Example:
stdnt3 = float(input("Enter the third grade: "))
if not (0 <= stdnt3 and stdnt3 <= 100):
raise SystemExit("Error: value is not between 0 and 100.")
stdnt4 = float(input("En...
Edit
Note that your if-condition doesn't work as you expect. This:
if(0 <= (stdnt1 and stdnt2 and stdnt3 and stdnt4 and stdnt5) <= 100):
Will be (logically) turned into:
# Step 1
booleanValue = stdnt1 and stdnt2 and stdnt3 and stdn4 and stdnt5 # a True or False
# Step 2
if 0 <= (booleanValue) <= 100
# Step 3
if (0 <= booleanValue) <= 100
# Step 4
if TrueOrFalse <= 100
TrueOrFalse will be True (casting usually to the number 1) or False (casting usually to the number 0). That means that the if-condition will always evaluate to True and your else will never get called. Instead, check each value individually, either with multiple if statements, or in a single if statement:
if (0 <= stdnt1 and stndt1 <= 100) and (0 <= stndt2 and stndt2 <= 100) and ...
Divide up your problems. You're trying to achieve two separate things here:
Validate your inputs
Calculate an average
Write separate functions for each of these... well.. functions!
def validate_grade(grade):
if grade < 0 or grade > 100:
raise InvalidGrade() # This is a custom exception, I'll explain momentarily
return grade
So this function will check if a given number is between 0 and 100 inclusive, if not it will raise an exception. In this case it's a custom exception, so that we can catch it only if this particular case occurs. In all other circumstances, normal Python exceptions will be raised.
Let's define that exception.
class InvalidGrade(Exception):
pass
It really is just a standard exception with a different name! Easy but very helpful, here's how:
try:
stdnt1 = validate_grade(float(input("Enter the first grade: ")))
stdnt2 = validate_grade(float(input("Enter the second grade: ")))
stdnt3 = validate_grade(float(input("Enter the third grade: ")))
stdnt4 = validate_grade(float(input("Enter the fourth grade: ")))
stdnt5 = validate_grade(float(input("Enter the fifth grade: ")))
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(stdnt1, stdnt2, stdnt3, stdnt4, stdnt5)
Great! Now it will gather input, raise an exception if any one of those inputs is invalid, otherwise it will execute the yet-to-be-defined calculate_grades function. But before we do that, we have some very repetitive code to clean up.
Lets ask ourselves what we're really repeating with these 5 grades. The only difference between each line is "first", "second", "third", etc.
Aha! We could create a list of grade names, and then python can loop over that list to build a list of grade values.
grade_names = ["first", "second", "third", "fourth", "fifth"]
try:
grade_values = [validate_grade(float(input("Enter the %s grade: " % name)))
for name in grade_names]
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(*grade_values)
First we simply define a list of grade names by creating a list of strings.
Then inside the try block we use something called a list comprehension. It is simply a statement that gets evaluated for each item in a list, in this case that statement is the function validate_grade which happens to take the results of input then float as its parameters, and returns a value which is what will be saved in our grade values list.
Then, instead of passing each item one by one to calculate_grades, the * tells python to expand the list's elements as parameters for the function. Now if you were to say, add or remove a grade, you only have to change your code in one place.
Now for the final piece, lets define calculate_grades
def calculate_grades(*args):
avrg = sum(args) / len(args)
print("The groups average is", avrg)
print("The lowest grade is", min(args))
The whole solution together
GRADE_NAMES = ["first", "second", "third", "fourth", "fifth"]
class InvalidGrade(Exception):
pass
def validate_grade(grade):
if grade < 0 or grade > 100:
raise InvalidGrade()
return grade
def calculate_grades(*args):
print("The groups average is", sum(args) / len(args))
print("The lowest grade is", min(args))
try:
grade_values = [validate_grade(float(input("Enter the %s grade: " % name)))
for name in GRADE_NAMES]
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(*grade_values)
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...