If statement code not reaching either branch - python

2 people ask for a 1,000,000 loan, one who has good credit only has to pay a 10% deposit, the other with bad credit has to pay a 20% deposit.
I thought, couldn't I make this from an input statement? It asks the input questions (where I then respond good) and then it states "process finished with exit code 0" which I guess means that there is nothing for Python to code. Here is what I've done, what I want to happen is if you type "good" then the answer will = 10,000 but if you type "bad" then you will be given the answer 20,000.
price = 1000000
prompt1 = input('What is your credit rating, good or bad')
if prompt1=='Good':
print(1000000 * 0.1)
elif prompt1 == 'Bad':
print(1000000 * 0.2)

Edited from what Tamerjar suggested
The reason you are not able to run this code, is that the words taken from the input statement do not match the function.
So you can change the format of your code as below
I'm using the ".lower()" function in order to take the input data and transform it to be all small letters. Please let me know if this answers your question.
price = 1000000
prompt1 = input('What is your credit rating, good or bad')
prompt = prompt1.lower()
if prompt=='good':
print(price * 0.1)
elif prompt == 'bad':
print(price * 0.2)
else:
print("Wrong input word")
I added this else statement just in case a wrong word was typed into the input. In order to handle those kinds of errors.

Related

TypeError: ">” not supported between instances of "str' and int‘

I know I’m missing something with this code. Can someone please help me? I’m new to coding and I’ve struggling with this all day. I don’t want to keep emailing my instructor so maybe I can get help from here. I’m trying to get it to run through the if statements with user input and then calculate the amount but I don’t know what I’m missing.enter image description here
You should post code you're asking about as text in your question.
Going over your code with some comments:
print("Welcome") # no issue here, although Python default is single quotes, so 'Welcome'
print = input("Please enter company name:")
After that last line, print is a variable that has been assigned whatever text was entered by the user. (even if that text consists of digits, it's still going to be a text)
A command like print("You total cost is:") will no longer work at this point, because print is no longer the name of a function, since you redefined it.
num = input("Please enter number of fiber cables requested:")
This is OK, but again, num has a text value. '123' is not the same as 123. You need to convert text into numbers to work with numbers, using something like int(num) or float(num).
print("You total cost is:")
The line is fine, but won't work, since you redefined print.
if num > 500:
cost = .5
This won't work until you turn num into a number, for example:
if int(num) > 500:
...
Or:
num = int(num)
if num > 500:
...
Also, note that the default indentation depth for Python is 4 spaces. You would do well to start using that yourself. Your code will work if you don't, but others you have to work with (including future you) will thank you for using standards.
Finally:
print = ("Total cost:, num")
Not sure what you're trying to do here. But assiging to print doesn't print anything. And the value you're assigning is just the string 'Total cost:, num'. If you want to include the value of a variable in a string, you could use an f-string:
print(f"Total cost: {num}")
Or print them like this:
print("Total cost:", num) # there will be a space between printed values

Why won't my branched conditions execute? And, how do I get the program to repeat itself?

I'm trying to do an assignment for MIT OCW (it's a self-development class, not a for-credit class, so don't worry, I'm not cheating on anything).
This is what I have so far:
#This program calculates how many months it will take to buy my dream home
print("Welcome to the dream home calculator.")
total_cost=input("To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")
try:
float(total_cost)
if total_cost>1000000:
print("That's quite a pricey home!")
elif total_cost>=200000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
except:
print("Please enter only a number, with no commas.")
total_cost
But, no matter what number I input, I don't get any of the text such as "That's a decently-priced home" and the program goes straight to "Please enter only a number, with no commas."
Also, if the user inputs something other than a number, I want the program to ask for the total cost of the home again. How do I get it to do that?
Thank you!
EDIT: NEVERMIND! I figured it out! float(total_cost) didn't actually turn total_cost into a floating point. To solve that, I did: total_cost=float(total_cost)
Still, what about the second question?
About the second question, you can try using a while loop.
# This program calculates how many months it will take to buy my dream home
print("Welcome to the dream home calculator.")
input_flag = False
while input_flag == False:
total_cost = input(
"To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")
# if the total_cost is a number string, the input_flag will become True
# Then it will escape the loop
input_flag = total_cost.isnumeric()
try:
total_cost = float(total_cost)
if total_cost > 1000000:
print("That's quite a pricey home!")
elif total_cost >= 200000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
except:
print("Please enter only a number, with no commas.")
total_cost
You could do it like that:
def main():
"""Calculate how many months it will take to buy my dream home."""
print('Welcome to the dream home calculator.\n')
# Ask for input
print(
'To start, please write down the cost of your dream home. '
'Use only numbers, and do not use commas.'
)
while True:
total_cost_str = input('>>')
try:
total_cost = float(total_cost_str)
except ValueError:
print("That's the wrong input, try again!")
continue
else:
break
# Evaluate result:
if total_cost > 1_000_000:
print("That's quite a pricey home!")
elif total_cost >= 200_000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
if __name__ == '__main__':
main()
Notice that I moved the if-clauses out of the try ... except-block. As you're actually just trying to convert the input to float, it's good practice to keep the exception-handling as narrow as possible.
Now you can be sure that you have a valid floating-point number after the try ... except-block, which makes debugging a lot easier.
Also notice that your exception-clause was too broad. If you're converting to float, the only exception you're concerned with is ValueError, as that one is raised if float() is unable to convert your input.
If you just put except, you might (in some cases that are a little more complex) actually catch a different exception that should not go unnoticed.

Is there a cleaner and more efficient way to make these BMI & Fat% calculators in Python?

I'm new to python (and coding in general & SOF). I recently picked it up after going through some online HTML, CSS tracks on Treehouse and really enjoy it until now. Apart from the hobby aspect my general bigger goal is to be able to write my own web applications/programs related to my field of work & study (healthcare).
So.. My question is related to this piece of code I wrote today. It's a general BMI calculator and also includes a fatpercentage estimator (based on a few variables that need to be provided). It's by no means a 100% accurate fat% calculator (you'd need a DXA-scan to get a better idea), although it works fine for the general public.
Questions:
1) How do I make sure that a user can input multiple things into the height prompt? Some users might want to add 187 and others will put in 1.87. How do I account for this and make sure the calculator still works?
2) Do I need to write all those print statements in my functions or is there a cleaner/better way to write these functions?
3) If I want the user to be able to select the imperial or metric system? How do I do this and do I need to make 2 extra functions for these?
Thanks in advance and here is the code (ps. don't mind the "strange" print messages :) ):
# BMI calculator & fatpercentage estimator
#VARS
gender = input("What is your gender? Male or female? ")
age = input("How old are you? ")
length = float(input("What is your length in meters? Input should be: 1.80 for example. "))
weight = int(input("How much do you weigh (in KG)? "))
userinput_fatpercentage = int(input("What is your fatpercentage?\nReturn 0 (zero) if you don't know and want to calculate. "))
bmi = round(weight/(length*length), 2)
# BMI CALC
def bmi_calulation():
if bmi <= 18.5:
print("Your Body Mass Index is:", bmi, "start eating, skinny.")
elif bmi > 18.5 and bmi < 25:
print("Your Body Mass Index (BMI) is: ", bmi, "you are a normal person, thank god.")
elif bmi > 25 and bmi < 30:
print("Your Body Mass Index (BMI) is: ", bmi, "mind you... You are overweight. Drop some weight.")
elif bmi > 30:
print("Your Body Mass Index (BMI) is: ", bmi, "Hnnngggg..! You are insanely overweight. Stop eating right away!")
else:
print("There was an error with your input. Try again.")
# FAT% ESTIMATOR
def fatpercentage_calculation():
if userinput_fatpercentage == 0 and gender.lower() == 'male':
print("Your fatpercentage is: ")
print(round((1.2 * float(bmi) + (0.23 * float(age) - (10.8 * 1) - 5.4)), 2))
elif userinput_fatpercentage == 0 and gender.lower() == 'female':
print("Your fatpercentage is: ")
print(round((1.2 * float(bmi) + (0.23 * float(age) - (10.8 * 0) - 5.4)), 2))
elif userinput_fatpercentage == userinput_fatpercentage:
print("Your fatpercentage is: {}.".format(userinput_fatpercentage))
else:
print("Something went wrong. Try again. ")
#Output
bmi_calulation()
fatpercentage_calculation()
1) You don't have to worry about inputs 1.87 vs 187 since you specified the format in the prompt as meters. It would be the user's fault if they put in cm in this case. Another design would be to ask the user before the height question whether they would want to use meters or cm, let them choose, and then internally in your code only use one (convert if they chose the other).
2) The parts that are repeating you can print before the if statements, and then print the details inside the if statements based on the case. If you don't want newlines between the two parts, you can use
print('.', end='')
to print without creating a newline.
3) Again, you can simply prompt the user for this. To avoid writing 2 similar codes to account for 2 systems, you can internally convert the user choice into one of them, and calculate everything (then you can convert back for printing).

Understanding how to calculate the total with variable assignments

I am new to programming and trying to get a head start on my class next semester. I am trying to show the total cost and then print it. Where am I going wrong?
print('Would you like a rental car?')
rental = (input('Yes or No? '))
if rental.lower() == yes:
car = float(input('Dollar Amount?'))
else:
print('Thank You!')
print('Would you need a flight?')
flight = (input('Yes or No '))
if flight.lower() == yes:
plane = float(input('Dollar Amount? '))
else:
print('Thank You!')
print('Would need a hotel?')
hotel = (input('Yes or No? '))
if hotel.lower() == yes:
room = float(input('Dollar Amount? '))
sum = travel (room + plane + car)
print('This is the total amount that it may cost you, ' + travel '!')
Problem 1
Fix your indentation. Python uses indentation to define what block code is executed in (i.e. in an if statement, or after it). Here's what you should do:
Select all (cmd / ctrl + a), and then keep pressing (cmd / ctrl + [) to de-indent. Do this until nothing is indented.
On any line you want in an if / else statement, press the TAB key at the start of that line.
Problem 2
The input function (which gets user input) returns a string. You then try to compare this to an undefined variable yes. Replace the yes in your if statements with "yes" or 'yes' to ensure you are comparing two strings.
Problem 3
Remember to end all of your strings, with a closing quotation mark. You forgot one printing "Thank You" after the "Would you need a flight?" question.
Replace: print('Thank you.) with print('Thank you.')
Problem 4
Second-to-last line, you define sum, which is never used. Then, you try to use the undefined travel function to add up your three variables. This line of code, in general, makes no sense. I am assuming that you meant this:
travel = (room + plane + car)
Problem 5
You can't concat floats / ints to strings.
This should be the final line:
print('This is the total amout that it is may cost you, '+str(travel)+'!')
Also, you forgot the concat operator (+) when appending the exclamation mark.
Final Code:
Here is the working version of your code:
print('Would you like a rental car?')
rental = (input('Yes or No? '))
if rental.lower() == 'yes':
car = float(input('Dollar Amount?'))
else:
print('Thank You!')
print('Would you need a flight?')
flight = (input('Yes or No '))
if flight.lower() == 'yes':
plane = float(input('Dollar Amount? '))
else:
print('Thank You!')
print('Would need a hotel?')
hotel = (input('Yes or No? '))
if hotel.lower() == 'yes':
room = float(input('Dollar Amount? '))
travel = (room + plane + car)
print('This is the total amout that it is may cost you, ' + str(travel)+ '!')
Recommendations:
This works, but it could be better. Here are a few recommendations, which will help you not only with this project, but also with further ones:
You can combine your print and input functions together, since input basically prints and then waits for input. To format it like you have now, simply include a newline character, \n. For example, instead of
print('Would you like a rental car?')
rental = (input('Yes or No? '))
you could do
rental = input("Would you like a rental car?\nYes or No?")
These lines could actually be simplified further. You don't need to define the variable rental, but instead you can just use its' output directly in the if statement, i.e.
if input("Would you like a rental care?\nYes or No?").lower() == "yes" :
...
Learn to use try / catch statements to catch errors. When entering the amount for a travel expense, the user has to type a number. But what if they type a string instead? Your program would crash. Learn how to use try / catch statements to prevent this from happening (https://docs.python.org/3/tutorial/errors.html)
There's not really much apart from that. These were all just beginners mistakes, and soon you'll be writing good code that works well :D
I was also impressed to see how you handled the "yes" / "no" user input by converting the answers to lower case and then checking them, which is something that a lot of people of your skill level neglect to do.

Variables don't change after being run through a function

I'm writing a small game in python in which certain events happen and effect variables which need to stay in certain parameters. I have the main file and then another file which has all of the events in them. Some of the values are changed in the function then supposed to change the overall values in main (Sorry if that doesnt make sense)
Here's the part in main:
while (army > -100 and army < 100 and people > -100 and people < 100 and church > -100 and church < 100 and affairs > -100 and money < 100 and money > -100):
os.system('clear')
#Top Bar. Should Stay throughout game.
print("[-]==[King: " + king + "]==[Years in power:" + str(years) +"]==[Army: " + str(army) + "]==[People: " + str(people) + "]==[Church: " + str(church) + "]==[Foreign Affairs: " + str(affairs) + "]==[Economy: " + str(money) +"]==[-]")
print(people)
event1(army, people, church, affairs, money, years)
That loops until one of the parameters falls below 0 then there's losing conditions
Right now there is only one event, and it's not quite finished, but I only need one thing to at least see a change in the values.
Here that:
def event1(army, people, church, affairs, money, years):
#Feilds are Flooding
print("")
print("Sire! The Feilds in the eastern baronies are flooding! What should we do?")
print("")
print("Choices:")
print("1: The rain will pass, do nothing. (~Money, People)")
print("2: Have the Royal Builders build flood protection! (~Money, People)")
print("")
c=input("Your choice sire: ")
while True:
if c > 2:
print("")
print("Please chose a valid option")
print("Your choice sire: ")
continue
if c == 1:
time.sleep(2)
print("")
print("You do nothing, your people starve from flooded feilds (-People, +Money)")
money = money+20
people = people-20
years = years+1
raw_input("Press Enter to go to the next year")
return money
return years
return people
break
After it runs the event the values people, money and years are all supposed to change, but when it loops, nothing changes.
Any help is appreciated! Thank you!
Those are local variables. As soon as you leave the method scope, the value is lost, unless you return and actually use the returned values.
In your caller, assign your variables with the new returned values:
money, years, people = event1(army, people, church, affairs, money, years)
and in event1, perform only one return (others are unreachable) of the tuple containing the 3 values you want to return (which is unpacked to the 3 upper level eponymous variables):
return money, years, people
YOU DO NOT NEED THE RETURN!!!!!!!!!!!!!!!!!!!! COMPLETELY REMOVE IT! READ THIS! (should help)
The return in fact ruins your command, and there is a really easily explainable way to understand how it works.
First I need to explain something, because I am kind of confused about your code. Return is used to make the value of your command whatever you have returned. Return is used like this:
def AddThreethousandTwohundredSeventyNineToNum(num):
num = num + 3279
return num
and then
print AddThreethousandTwohundredSeventyNineToNum(4)
It should print "3283". (3279 + 4)
print printThreethousandTwohundredSeventyNineToNum(2)
It will print "3281".
You can also do cool things like:
if AddThreethousandTwohundredSeventyNineToNum(x) == y:
DoSomething
All return does is make the value OF THE FUNCTION whatever you want it to be. In the last code, the function looks for what I made num, and sees that it is 4 or 2, so it does num = num + 3279, so num gets increased by 3279 (3273 or 3271). When you do return num, it makes THE FUNCTION equal num.
That means what you have done is changed all those beatiful values in lines 21-23 (money, people, etc.) and technically that is all you had to do. However, when you returned the numbers, you made your command not only change those values, but also become a number, and obviously you cant just have a number lying around in your command. Or else the interpreter will not understand.
I hope I was clear enough, and if not, please please PLEASE tell me (please).

Categories