def trip_cost(city,days,spending_money):
days = input("Enter amount of days for car hire")
city = input("City name")
days = input("Nights staying")
spending_money = input("Spending money")
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money
print((trip_cost(city,days,spending_money)))
I keep getting an error saying that city is not defined. I am new to Python so I am sorry if this is question that is easy to answer. All the variables already have their set functions. Here is city's one just in case it helps
def plane_ride_cost(city):
if city=="Charlotte":
return 183
elif city=="Tampa":
return 220
elif city=="Pittsburgh":
return 222
elif city=="Los Angeles":
return 475
else:
return input("Please try again")
Also this is an altered code from Code Academy
def trip_cost():
days = int(input("Enter amount of days for car hire"))
city = input("City name")
nights = int(input("Nights staying"))
spending_money = int(input("Spending money"))
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days) + spending_money
print(trip_cost())
Get rid of the parameters; you do not need them since you will get it from user input via the input() function.
I used the int function to convert the input of numbers which are strings to integers.
In your print((trip_cost(city,days,spending_money))) call, where is city coming from? It looks like it is outside any of the functions so you need to declare it somewhere as something. And even when you do so, you will get the same error for days and spending_money. These need to be declared before they are printed.
Either that or actually pass in values to your trip_cost call in the print statement :)
Also, looking at the code more closely, it looks like your trip_cost method does not even need any arguments. you are creating the variables when asking for input so it looks like they are redundant as parameters.
Related
#Please help me
def computepay(h, r):
if h>40:
reg=40*r
otp=(h-40.0)*1.5*r
else:
pay = h*r
return pay
hrs = input("Enter Hours:")
rate= input('enter rate per hour: ')
fh = float (hrs)
fr = float (rate)
p = computepay(fh, fr)
print("Pay", p)
If I understand your code correctly, your code is not pasted well, if h > 40 pay is not assigned any value, pay only is assigned a value in the else
That's why you get that error
To answer the the question about "pay" being referenced before being assigned, your code is running through the if statement portion of the line where you define computepay(). You never add reg and otp into a variable called pay, which is what I assume you're trying to do.
Also, in your else statement, you make pay = hr, which does not exist, since python will parse hr as one variable and not two, be sure to use asterisks for everything to parse correctly.
How I would type out the computepay() definition would look like this:
def computepay(h, r):
if h>40:
reg=40*r
otp=(h-40.0)*1.5*r
pay=reg+otp
else: pay = h*r
return pay
The main function below return pay is fine, though. This should run perfectly, good luck!
I'm writing a program that will greet somebody (given name) and then ask them how many hours they worked and how much their hourly pay is. The program runs but is not spitting back the correct math. I'm getting this for my answer... you earned<function wage at 0x00EA9540>
I have already tried calling payment but not getting an answer with that either.
def greet(greeting):
name = input("Hi, whats your name?")
return greeting + name
print(greet ("Hey "))
hourly = input("How much is your hourly wage?")
hours = input("How many hours did you work this week?")
def wage(hourly, hours):
if hours > 40:
payment = 40 * hourly
payment = payment + hourly * (hours-40) * 1.5
return payment
else:
return hours * hourly
print("you earned" + str(wage))
You missed the parameters to the wage function.
in your case, it just prints the memory address of the function wage...
you need to change the print call with the correct parameters to the wage function:
print("you earned" + str(wage(hourly, hours)))
You need to call the wage function with the parameters:
print("you earned" + str(wage(hourly, hours)))
Otherwise you are simply printing the string representation of the wage function object, and that doesn't really make much sense.
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 have this function below, which I have done something wrong in somewhere.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:
try:
int(i)
return int(quantity)
valid = True
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
return True
return False
To run through, the function is called from the main part of the program like so: quantity = quantityFunction(product)
The return False at the bottom of the code is to do with if product is None, which is needed after a bit of code in another function but has had to go in this function.
If the user input for quantity is a number, all works fine. If it is anything else, the Value Error is printed and you can enter another input. If you put another letter etc in, it repeats again, if you put a number in, it accepts it.
However, it does not return the number you inputted after the letters. It just returns 0.
I suspect this is something to do with how I am repeating the code, i.e. the code should loop back to the start of the function if it hits the Value Error.
Any Ideas?
You said:
the code should loop back to the start of the function if it hits the Value Error.
Then you should not use return statements, otherwise the function will terminate, returning True or False.
Few issue:
1) return statement returns control to the calling function.
2) You are looping over the input, which is wrong.
3) valid=True isn't executed at all.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
#valid = True (since it is never run)
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
#return True
return False
quantityFunction("val")
Note : Use raw_input() in case of Python 2.7 and input() in case of 3.x
Try this (some formatting included too, but the functionality should be the same):
def determine_quantity(product): # descriptive function name
if not product: # avoiding nesting
return False
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity) # try to convert quantity straight away
except ValueError:
print("We didn't recognise that number. Please try again.")
# nothing here means we simply continue in the while loop
Ideally, you'd take product out. A function should do as little as possible, and this check is better off somewhere else.
def determine_quantity():
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
except ValueError:
print("We didn't recognise that number. Please try again.")
First, let's address the code. Simply stated, you want a function that will loop until the user enters a legal quantity.
product doesn't do much for the function; check it in the calling program, not here. Let the function have a single purpose: fetch a valid quantity.
Let's work from there in the standard recipe for "loop until good input". Very simply, it looks like:
Get first input
Until input is valid
... print warning message and get a new value.
In code, it looks like this.
def get_quantity():
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
while not quantity_str.isdigit():
print("We didn't recognise that number. Please try again.")
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
return quantity
As for coding practice ...
Develop incrementally: write a few lines of code to add one feature to what you have. Debug that. Get it working before you add more.
Learn your language features. In the code you've posted, you misuse for, in, return, and a function call.
Look up how to solve simple problems. try/except is a more difficult concept to handle than the simple isdigit.
You should try this..
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
if quantity.isdigit():
return int(quantity)
valid = True
else:
print("We didn't recognise that number. Please try again.")
continue
return False
quantity = quantityFunction("myproduct")
I'm creating a program to match a particular year to an Olympic location.
I.e. if the user inputs a year, it finds the location where the Olympic games took place that year (1904 - Athens, Greece..) etc.
It keeps telling me i have positional errors in my code, however:
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module> findLocation()
TypeError: findLocation() missing 3 required positional arguments:
'yearList', 'locList', and 'year'
Here is my program:
def getData():
print("All the events")
print("")
yearList = []
locList = []
readFile = open('olympics.txt', 'r')
for line in readFile:
year, loc = line.split("\t")
loc = loc.replace("\n", "")
yearList.append(year)
locList.append(loc)
return yearList,locList
def findLocation(yearList, locList, year):
i=0
location=""
while i<len(locList):
if yearList[i] == year:
year = yearList[i]
elif yearList[i] !=year:
return print ("That was incorrect")
i += 1
return location
Getting data works successfully, but my findLocation function seems to be out of whack and i dont know how to fix it.
Here is an excerpt of the text file containing the Olympic events.
1896 Athens, Greece
1900 Paris, France
1904 St. Louis, Missouri USA
1906 Athens, Greece*
1908 London, England
1912 Stockholm, Sweden
1916 Not held**
1920 Antwerp, Belgium
Can someone help me please?
The reason findLocation does not yield a result is because you are iterating over all the years/locations, and if the first one is incorrect you return from the function (return print ("That was incorrect"))
UPDATE: Included an example main method describing how to call the functions
Something like this should work better:
def getData():
print("All the events")
year_to_location = {}
with open('olympics.txt', 'r') as f:
content = f.readlines()
for line in content:
year, loc = line.split("\t")
year_to_location[year] = loc.strip()
return year_to_location
def findLocation(year_to_location, year):
if year in year_to_location:
return year_to_location[year]
else:
print("That was incorrect")
if __name__ == '__main__':
year_to_location = getData()
print(findLocation(year_to_location, "1900"))
Note: I replaced the year_list and loc_list with a dictionary year_to_location instead and simplified the findLocation quite a bit. I also added a with open('olympics.txt') as f statement which is a slightly better way of handling files (it assures that the file handler gets closed when done)
You could also just remove return from return print ("That was incorrect") and your code should work as is.
but my findLocation function seems to be out of whack
You are right about that. Your logic needs to be changed there. However, next time, please add a little more information of what you expected and what you got. That will help us. Now on to the logic:
def findLocation(yearList, locList, year):
i=0
location=""
while i<len(locList):
if yearList[i] == year:
return locList[i]
elif int(yearList[i]) > int(year):
print "That was incorrect"
return
i += 1
print "Year was incorrect"
return
Now this function needs to be called with three arguments. Two from your getdata and one from the user to print the location:
year_list, loc_list = getData()
year = raw_input("Enter the year to search:")
findLocation(year_list, loc_list, year)
Having said that your code is non idiomatic and that it could be rewritten in a shorter, clearer way, let's try to analyze your problem.
Your error is motivated by a mismatch between the function signature and your usage, but even if it was called correctly it won't return the correct location... this is your code
def findLocation(yearList, locList, year):
i=0
location=""
in the line above you set location, and it is never reassigned, so you're going to return the null string, irrispective of the rest of your code
while i<len(locList):
if yearList[i] == year:
year = yearList[i]
the test above is tautological, if two objects are equal (i.e., their values are equal) you assign one's value to the other object... you've not changed anything
elif yearList[i] !=year:
return print ("That was incorrect")
the test above is not what you want, because 1. you don't want to exit from your function until you've tested all the possible Olympyc years and 2. return print(...) returns the value returned by the print function, i.r., None.
i += 1
return location
Staying close to your coding style, I'd go like this
def find_location(y_list, l_list, year):
i = 0
while i<len(y_list):
if year == y_list[i]:
# the following statement exits the function,
# returning the Olympics location for the year
return l_list[i]
i = i+1
return ''
If you know about the zip builtin, the following is more compact and expressive
def f(y_l, l_l, year):
for y, l in zip(y_l, l_l):
if year==y: return l
return ""
The real solution of your problem is to use a different data structure instead of the paired lists, namely a dict but it seems to me that you were not introduced to it...