Understanding how to calculate the total with variable assignments - python

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.

Related

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.

Python 3.6.2 loop not working like I wanted it too

I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.

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).

I'm writing a fuel conversion program and its not working :(

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.

Whats a way for me to have code in a script but not ran until asked to?

I'm wondering how in python I'd be able to write code, and not have it executed until a certain input is inputted by the user, for example,
a = 1
raw_input("type a if you want to run '1'")
but instead of having '1' in this example, it would be code. And not run until the user inputs 'a'
Okay: here is the part of my game I'm working on:
balance = 2500
FinalPrice = 0
buy = input("Marijuana plants cost 200$ ea, opium seeds cost 300$")
while (buy != "o") and (buy != "m"):
buy = input("That's not on the market! type 'm' if you want to buy Marijuana and 'o' if you want opium!")
if buy =="o":
o = input("How many opium seeds? Press c to cancel")
if o =="c":
input("You cancelled the trade. Type in a command to do something else")
elif buy =="m":
m = input("How many Marijuana plants? Press c to cancel")
if m=="0":
m = input("invalid number, input again")
elif m =="c":
input("You cancelled the trade. Type in a command to do something else")
mprice = (m*200)
print(mprice)
FinalPrice-=FinalPrice
FinalPrice+=mprice
mbuy = input("This is the final price, press b to buy or c to cancel")
if mbuy =="c":
input("You cancelled the trade. Type in a command to do something else")
elif mbuy =="b":
if mprice > balance:
print("Not enough money! Sell more drugs to earn more money.")
elif mprice < balance:
print("you bought", m , "Marijuana plants for", mprice , "$")
input("What do you want to do next?"
I want to move all of this code to have it when the user types in an input, for example "buy" it executes this code, but only then and I don't want to have to copy + paste it after every input when i ask the user what they want to do next
You want to declare a function.
def buy():
#paste all your code in here
Now whenever you want to run the function, all you have to do is call it. You can define lots of other functions the same way and call them too, without copying and pasting any code.
command = input("Type buy if you want to buy, and sell if you want to sell.")
if command == 'buy':
buy()
elif command == 'sell':
sell()
I highly recommend you read the documentation already linked in the comments. It's better programming practice to pass balance and FinalPrice as parameters into the function and return them at the end, and even better practice to define separate variables for each price, but reading the documentation will probably help more than asking here.

Categories