I am a novice python code writer and i am starting small with a fuel conversion program. The program asks for your name and then converts a miles per gallon rate or a kilometers per litre rate. Currently, the program runs fine until it gets to the convert to MPG line. then once you press y, it does nothing. funny thing is, no syntax error has been returned. please help as i cannot find anything on it :(
import time
y = 'y', 'yes', 'yep', 'yea', 'ye'
n = 'n', 'no', 'nup', 'nay'
name = str(input("Hey, User, whats your name? "))
time.sleep(1.5)
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
time.sleep(1.5)
str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if y is True:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = (galls/miles)
print("The MPG Rate is: ", int(mpgc))
time.sleep(2)
print("test print")
if y is (not True):
input(str("Would you like to convert KPL instead? (y/n): "))
time.sleep(1.5)
if y is True:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = ( litres / kilometers )
print("The KPL Rate is: ", int(kplc))
time.sleep(3)
exit()
if y is not True:
print("No worries")
time.sleep(1.5)
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
time.sleep(1.5)
print("Have a good day!")
time.sleep(1.5)
exit()
else :
print("Sorry, invalid response. Try again")
exit()
elif not y:
print("Please use y/n to answer" )
time.sleep(2)
elif not n:
print("Please use y/n to answer" )
time.sleep(2)
sorry if you think that is bad but i just started python and i need some help :)
Severely trimmed down and indentation fixed (I think....)
if y is True and similarly if y is not True make no sense here.
Also, speaking of is.. is and == may be work as equivalent expressions sometimes for checking for "equality", but not necessarily. == checks for equality whereas is checks for object identity. You should use == for checking for equality between two objects. Except for None in which case it's generally preferred to use is instead of == for this.
You're converting to str in a bunch of places unnecessarily. They're already strings.
In your mpg conversion you already have a floating point number (possibly an int). There's no need to convert to an int here. Suppose mpg is < 1. Then int casting will make this return zero
Your math is also backwards. miles per gallon. Similarly, kilometers per gallon.
name = input("Hey, User, whats your name? ")
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
mpg = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if mpg in y:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = miles / galls
print("The MPG Rate is: ", mpgc)
else:
kpl = input("Would you like to convert KPL instead? (y/n): ")
if kpl in y:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = kilometers / litres
print("The KPL Rate is: ", kplc)
else:
print("No worries")
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
print("Have a good day!")
The is keyword in python checks if two variables point to the same location in memory. y will never point to the same memory location as the singleton True because it's value is a string. I suspect what you mean to do is something like
inp = str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if inp in y:
...
You cannot directly take y as pressed from the keyboard, you have to take it as an input(Pressing enter would be required), store it, check if it satisfies the conditions, then apply the logic.
I see you tried to define y and n as a tuple (deliberately or not), In that case I assume you also want to take those other words as yes or or too.
In that case you can apply this logic;
inp = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if inp in y: # Check if inp corresponds any of the words defined in y
# Things to do if `yes` or anything similar entered.
Some notes:
You don't need to use str() after you take input if you are using
Python3 (Which seems you are). Because input() returns string.
In somewhere you did something like this:
input(str("Would you like to convert KPL instead? (y/n): "))
Which is even more reduntant because the value you entered is already
a string.
You also didn't assign some inputs to any variable throughout the
code. You should assign them If you are to use them later.
Please take care of these issues.
Related
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.
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).
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.
So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work correctly.
I've tried something like:
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.
An optimized version of #JamesRusso code :
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = int(input("Enter the watts of appliance, or total watts of appliances"))
hours = int(input("Enter the number of hours that appliance(s) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below you should add more error testing and messages for negative numbers, etc.
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:
hours = 0
while True:
hours = input("How many hours per day? ")
#first make sure they entered an integer
try:
tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
Basically, it starts by going into an 'infinite' loop. It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay. If the data was bad in any way, it informs the user and restarts the loop with the continue. hours = 0 is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.
Edit: adding an idea to the example code that I thought of after seeing #Ohad Eytan's answer
The input you get from the user is a string type, but you compare it to int type. That's an error. You should cast the string to int first:
hours = int(input("How many hours per day? "))
# ----^---
Then you can do something like:
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
If you don't sure the user will input a number you should use a try/catch statemant.
Except from this you should validate you indent the code correctly
I can't figure out why this is getting an error that states that 'Yes' is not specified. What does that mean? Why won't this work? The fuelEconomy input statement works and the function works as well. For some reason I can't get the while statement to accept the 'Yes' input to execute the function.
# This program is to calculate fueld economy
def main ():
fuelEconomy = input ("Do you want to calculate your fuel economy? ")
print (fuelEconomy)
while fuelEconomy == Yes:
Economy ()
fuelEconomy = input ("Do you want to calculate another?")
#This function is the input and calculation for the program
def Economy ():
mileage = int (input ("Input mileage "))
gallons = int (input ("Input gallons used "))
economy = mileage/gallons
print ('Your economy is', economy, 'MPG')
main ()
It needs to be a string.
while fuelEconomy == 'Yes':
However your code still won't actually work, because that is now an infinite loop as the value of fuelEconomy cannot change within the loop. You probably meant for the next line to also be inside the loop.