After compilation error:
Traceback (most recent call last):
File "python", line 29, in <module>
File "python", line 26, in trip_cost
TypeError: 'int' object is not callable
The following is the code for the expenditure calculation application that I wrote. There are four arguments passing inside trip_cost function in the end but four parameters defined in the function definition.
def hotel_cost(nights):
return 140 * nights
def spending_money(money):
return money
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "LosAngeles":
return 475
def rental_car_cost(days):
cost = 40
if days >= 7:
return (cost * days - 50)
elif days >= 3 < 7:
return (cost * days - 20)
elif days < 3:
return (cost * days)
def trip_cost(city,days,spending_money):
total_trip_cost = plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(days) + spending_money(spending_money)
return total_trip_cost
print trip_cost("LosAngeles",5,600)
Your local variable spending_money is over-writing the function spending_money() in your trip_cost function's scope.
Since the spending_money() function doesn't do anything, you could just add it directly.
def trip_cost(city,days,spending_money):
total_trip_cost = plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(days) + spending_money(spending_money)
return total_trip_cost
on this part of the code, you are calling for the function spending_money(spending_money), the problem is that the variable and the function are named alike, so python asumes that you are calling the function inside the function??? why do humans do this to me, i feel confused, said python.
a good tip and solution is to change the variable name or function name.
try:
def trip_cost(city,days,travelling_cash):
total_trip_cost = plane_ride_cost(city) + rental_car_cost(days) +hotel_cost(days) + spending_money(travelling_cash)
return total_trip_cost
cheers mate!
Related
So I'm really new to this (3 days) and I'm on code academy, I've written this code for one of the activities but when I run it it displays maximum recursion depth error, I'm running it in the python console of code academy and simultaneously on my own ipython console. The hint on the page is not helpful, can anybody explain how to fix this?
Thanks
def hotel_cost(nights):
return (nights * 140)
def plane_ride_cost(city):
if plane_ride_cost("Charlotte"):
return (183)
if plane_ride_cost("Tampa"):
return (220)
if plane_ride_cost("Pittsburgh"):
return (222)
if plane_ride_cost("Loas Angeles"):
return (475)
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)
Maybe:
def plane_ride_cost(city):
if city == "Charlotte":
return (183)
if city == "Tampa":
return (220)
if city == "Pittsburgh":
return (222)
if city == "Los Angeles":
return (475)
The error was:
The plane_ride_cost(city) called plane_ride_cost("Charlotte") in every recursion step.
Not the best, but a better approach:
def hotel_cost(nights):
return nights * 140
plane_cost = {
'Charlotte' : 183,
'Tampa' : 220,
'Pittsburgh' : 222,
'Los Angeles' : 475,
}
def plane_ride_cost(city):
if city not in plane_cost:
raise Exception('City "%s" not registered.' % city)
else:
return plane_cost[city]
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)
Can this be called a recursive function ? It does reduce in one way but not in a (amount - 1) type of way...
EDIT:
Also how is it possible to write a recursive function without using return?
def wow(amount):
if amount <= 0:
print "Don't be so negative!"
elif amount == 1:
return "Wow!"
else:
return amount * "Wow! \n"
amount = int(raw_input("How many 'Wow!' do you wanna see : "))
print wow(amount)
No, this is not a recursive function. A recursive function has to call itself. This page explains and shows examples of recursive functions.
This would be a recursive function.
def wow(amount):
if amount <= 0:
return
else:
print("Wow! \n")
return wow(amount - 1)
And a full-fledged solution that turns your code into a recursive function would be.
def wow(amount):
if amount <= 0:
return "Don't be so negative!"
elif amount == 1:
return "Wow!"
else:
return inner_wow("", amount)
def inner_wow(wow_str, amount):
if amount == 0:
return
else:
wow_str += "Wow! \n"
return wow(wow_str, amount - 1)
In response to your second question. All functions have to return something. Even if you don't tell them to return something they still returns None.
I wrote this code in python 2.7 to find Fibonnaci series. But there is error in my code:
File "Fib.py", line 2, in <module>
class Fib:
File "Fib.py", line 21, in Fib
for n in Fib(4):
NameError: name 'Fib' is not defined
Can anyone resolve this bug?
class Fib:
def __init__(self,max):
self.max = max
def __iter__(self):
self.a=0
self.b = 1
return self
def __next__(self) :
fib = self.a
if fib > self.max :
raise StopIteration
a,b=b,self.a+self.b
return fib
for n in Fib(4):
print n
Disclaimer: I cannot reproduce your error from the code you posted (see below for my guess work). However, I still get errors, so I'll fix them.
From your posted code:
I get:
Traceback (most recent call last):
File "a.py", line 17, in <module>
for n in Fib(4):
TypeError: instance has no next() method
It seems, if your targeting python 2.7, that you got mixed up with python 3. The __next__ method was introduced in python 3 (in PEP 3114, if your interested). In python 2, use next. Also, as self must be used to access instance member variables, a,b=b,self.a+self.b should be self.a, self.b = self.b, self.a + self.b. This makes your code:
class Fib:
def __init__(self, max):
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def next(self):
fib = self.a
if fib > self.max :
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
for n in Fib(4):
print n
Which produces the output:
0
1
1
2
3
Note that changing the next to __next__ and changing print n to print(n) makes this work in python 3 (but then not python 2. If you want both you need to forward next to __next__ and use brackets for print).
Guessed actual code:
Judging from your error, your original code probably looked like:
class Fib:
def __init__(self,max):
self.max = max
def __iter__(self):
self.a=0
self.b = 1
return self
def __next__(self) :
fib = self.a
if fib > self.max :
raise StopIteration
a,b=b,self.a+self.b
return fib
for n in Fib(4): # Note that this makes the loop part of the class body
print n
Indenting the for loop makes it part of the class body, and as the class name is a name not yet accessible, it raises a NameError. For a simpler example, try (it gives a similar error):
class A:
print A
Therefore, the error you experience is most likely just an indentation mixup. Nice idea using an iterator, though.
Easier method to implemented fibonacci series:
known = {0:0, 1:1}
def fibonacci(n) :
if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res
Fibonnaci Series with recursion
def fib(term_num):
if term_num == 0 or term_num ==1:
return term_num
return fib(term_num-2) + fib(term_num-1)
for x in range(1,11):
print(fib(x))
Output Below:
1
1
2
3
5
8
13
21
34
55
First off I am getting this error
File "E:\New folder (7)\maingame.py", line 64, in play print self.introduction AttributeError: 'game' object has no attribute 'introduction'
I am not to sure as to what it means because I am pulling the self.introduction from the previous class..
I am also getting an
File "E:\New folder (7)\maingame.py", line 96, in <module>
game.play()
TypeError: play() takes exactly 2 arguments (1 given)
error, but can't for the life of me find what argument it is looking for, I simply want it to work.
from random import random
class place(object):
def __init__(self, title, description, events):
self.title = title
self.description = description
self.events = events
class event(object):
def __init__(self, probability, message, healthChange):
self.probability = probability
self.message = message
self.healthChange = healthChange
def process(self):
if random() < self.probability:
print self.message
return self.healthChange
return 0
class textadventure():
def __init__(self):
super(textadventure, self).__init__()
self.introduction = """
Welcome player, you are a lone traveler in space whom has set out to find glories beyond measure.
Unfortunately for you the dread pirate Roberts has attacked. You must defeat him.
"""
commandDeck = place('Command Deck', "You are now in the command center, here you can drive the ship and fire its weapons.",(
event(0.7, "The pirate ship fires at you! You take damage to your engines!", -10),
event(0.2, "One of the pirates manages to beam onto your ship! He shoots you before beaming away!",0),
))
engineRoom = place('Engine Room', "You are now in the main engine room here you can repair damage to the ship",(
event(0.7, "The pirate ship fires at you! You take damage to your engines!", -10),
))
restQuarters = place('Resting Quarters', "Here you can take a rest and heal your self",(
event(1.0, 'You are able to patch up your wounds and get back to the battle',0),
event(0.5, "The pirate ship fires at you! You take damage to your engines!", -10),
))
commandDeck.transitions = (engineRoom, restQuarters),
engineRoom.transitions = (commandDeck, restQuarters),
restQuarters.transitions = (commandDeck, engineRoom),
self.location = commandDeck
pirateHp = 50
class game(object, textadventure):
def __init__(self):
super(game, self).__init__()
self.health = 100
def location(self):
if self.location == commandDeck:
choice = raw_input('would you like to fire on the enemy ship?')
if choice == 'yes':
print 'You have hit the pirates!'
pirateHp -= 10
else: choice == 'no'
elif self.location == engineRoom:
choice = raw_input('Would you like to repair the engines?')
if choice == "yes":
event(1, "You repair what you can of the engines.", 10)
def __init__(self):
self.health = 100
def play(self, textadventure):
print textadventure.introduction
while True:
print (self.location.description)
for event in self.location.events:
self.health += event.process()
if self.health <= 0:
print ("Your ship has been destroyed!")
pause
exit(1)
print ('Your ships health is at %d percent' % self.health)
self._transition()
def _transition(self):
transitions = self.location.transitions
print ('you can go to: ')
for (index, transition) in enumerate(transitions):
print (index + 1, transition.title)
choice = int(raw_input('Choose one '))
if choice == 0:
exit(0)
else:
self.location = transitions[choice - 1]
def pirateShip(Object):
if pirateHp == 0:
print "You have defeated the pirates! Congradualations!"
pause
exit(1)
game = game()
game.play(game)
'game' object has no attribute 'introduction'
You should call the init of your super class when initializing game. In your current code, textadventure.init is never called which is why introduction is never added to textadventure.
Game should also not inherit from object (it does that through textadventure).
class game(textadventure):
def __init__(self):
super(game, self).__init__()
self.health = 100
def play(self):
print self.introduction
Should do the trick.
TypeError: play() takes exactly 2 arguments (1 given)
You never use your textadventure argument in play. Removing this should get things working.
The following code triggers a value error:
from pygame import *
init()
from random import *
t = True
f = False
inventory = []
class block(object):
def __init__(self,break_time,break_content,color):
self.break_time = break_time
self.break_content = break_content
self.color = color
def brek(self):
inventory.append(self.break_content)
end = block(1-0,None,(0,0,0))
gem = block(10,"agem",(0,0,100))
stone = block(3,"cobble",(100,100,100))
iron = block(5,"iron_ore",(25,50,100))
dirt = block(2,"dirt",(139,69,19))
locations = [a for a in range (60)]
unervise = {}
def generate(x_axis):
global unevise
global locations
for a in range(60):
global unevise
global locations
if a == 0 or a == 1:
unevise[(locations[a],x_axis)] = end
if a in range(2,35):
if a in range(2,10) and randint(1,10) == 1:
unevise[(locations[a],x_axis)] = gem
elif a in range(2,30) and randint(1,5) == 1:
unevise[(locations[a],x_axis)] = iron
else:
unevise[(locations[a],x_axis)] = stone
if a in range(35,40):
unevise[(locations[a],x_axis)] = dirt
Here's the error:
Traceback (most recent call last):
File "C:/Users/Ben/Documents/Python Files/My first comp openable.py", line 46, in <module>
generate(a)
File "C:/Users/Ben/Documents/Python Files/My first comp openable.py", line 28, in generate
unevise[(locations[a],x_axis)] = end
NameError: global name 'unevise' is not defined
But the value is clearly defined, thrice in my program, twice globaling it inside the function.
I probably have overlooked some major key point- sorry.
You define unervise, not unevise:
unervise = {}
Also, there's no need for the multiple global declarations.