why am i getting NameError when accessing a function - python

I couldn't figure out why I'm getting a NameError when trying to access a function inside the class.
This is the code I am having a problem with. Am I missing something?
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if cubesum(num) == num:
return True
return False
[i for i in range(1000) if ArmstrongNumber.Armstrong(i)] # this return NameError
Error-message:
NameError Traceback (most recent call last)
<ipython-input-32-f3d39f24a48c> in <module>
----> 1 ArmstrongNumber.Armstrong(153)
<ipython-input-31-fd21586166ed> in Armstrong(num)
10
11 def Armstrong(num):
---> 12 if cubesum(num) == num:
13 return True
14 return False
NameError: name 'cubesum' is not defined

Use classname before method:
class ArmstrongNumber:
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if ArmstrongNumber.cubesum(num) == num:
return True
return False
print([i for i in range(1000) if ArmstrongNumber.Armstrong(i)])
Unlsess you pass self to the functions those functions are not instance methods. Even if you define that within class you still need to access them using classname.

this should be your actual solution if you really want to use class
class ArmstrongNumber(object):
def cubesum(self, num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(self, num):
if self.cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(self, num):
if self.cubesum(num) == num:
return True
return False
a = ArmstrongNumber()
print([i for i in range(1000) if a.Armstrong(i)])
output
[0, 1, 153, 370, 371, 407]
2nd method:
if you dont want to use class then use static methods like this
def cubesum(num):
return sum([int(i)**3 for i in list(str(num))])
def PrintArmstrong(num):
if cubesum(num) == num:
return "Armstrong Number"
return "Not an Armstrong Number"
def Armstrong(num):
if cubesum(num) == num:
return True
return False
# a = ArmstrongNumber()
print([i for i in range(1000) if Armstrong(i)])

Related

Python - Update a function/return assigned to a var

Code first so you'll understand what I'm talking about :
goal = False
count = 0
def function():
if goal==True:
return True
else:
return False
def func():
if dict1["A"]==True:
return True
else:
return False
dict1 = {"A":function()}
dict2 = {"B":func()}
list = [dict1,dict2]
goal = True
for i in list:
count = 0
for x,y in i.items():
if y==True:
count+=1
if count==len(i):
print("Works")
else:
print(i)
>>>{"A":False}
>>>{"B":False}
This is not my current code, but it is the actual issue. This is where I'm asking, how can I update the values in the dicts. Should I do something like :
for i in list:
for x,y in i.items():
y()
?
My current project is used in Ren'Py (.rpy) but as I'm using python blocks, the code works exactly as normal Python.
Within a class named Event, my elements are exactly as it follows:
def ev_check(self):
if self.done==False:
self.count = 0
for x,y in self.conditions.items():
if y==True:
self.count+=1
else:
pass
if self.count==len(self.conditions):
self.valid = True
else:
self.valid = False
else:
self.valid = False
def own_office():
if Promotion_1.done==True: #Once the event is played, .done gets True
return True
else:
return False
def times_worked(x):
if You.worked < x:
return False
else:
return True
Promotion_1.conditions = {"Work 2 times" : times_worked(2)}
Meet_Tigerr.conditions = {"Own office" : own_office()}
#External event that adds a value to the data named You.worked to get it to 2
print(Promotion_1.conditions["Work 2 times"])
>>> False
Expected result : True
Result : False
You can create your custom dict and have this feature. You may try something like this:
class MyDict(dict):
def __getitem__(self, item):
val = super().__getitem__(item)
if callable(val):
return val()
return val
It will work exactly like a dict, except that it will call the callable values for you every time.
d = MyDict()
d['m'] = 1
d['m']
Out[28]: 1
task
Out[33]: <function __main__.task()>
task()
Out[34]: True
d['t'] = task
d['t']
Out[36]: True
EDITED : Modified the code a bit to show how you can even have argument values passed for your parameterized functions:
def func():
return True
def param_func(i):
return 2*i
def param_func2(i, j):
return i*j
class MyDict(dict):
def __getitem__(self, key):
if isinstance(key, tuple):
super_key = key[0]
else:
super_key = key
super_val = super().__getitem__(super_key)
if callable(super_val):
if isinstance(key, tuple):
args = key[1:]
return super_val.__call__(*args)
else:
return super_val.__call__()
return super_val
if __name__ == "__main__":
d = MyDict()
d['num'] = 1
print(d['num'])
d['func'] = func
print(d['func'])
d['param_func'] = param_func
print(d['param_func', 2])
d['param_func2'] = param_func2
print(d['param_func2', 2, 6])
Output :
1
True
4
12

TypeError: 'NoneType' object is not callable (Python)

I have a code error that I need to debug but I'm not sure where I went wrong. When I run my code I got:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
c3_plus_0i = create_complex(create_ordinary(3), create_ordinary(0))
File "<pyshell#30>", line 2, in create_complex
return get("make","complex")(x,y)
TypeError: 'NoneType' object is not callable
This is the code that I have:
from generic_arith_min import *
def install_complex_package():
def make_com(x,y):
return tag(repcom(x,y))
def repcom(x,y):
return (x,y)
def real(x):
return x[0]
def imag(x):
return x[1]
def tag(x):
return attach_tag("complex",x)
# add,sub,mul,div: (RepCom, RepCom) -> Generic-Com
def add_com(x,y):
return make_com( add(real(x), real(y)),
add(imag(x), imag(y)) )
def sub_com(x,y):
return make_com( sub(real(x), real(y)),
sub(imag(x), imag(y)) )
def mul_com(x,y):
return make_com(sub(mul(real(x), real(y)),
mul(imag(x), imag(y))),
add(mul(real(x), imag(y)),
mul(real(y), imag(x))))
def div_com(x,y):
com_conj = complex_conjugate(y)
x_times_com_conj = content(mul_com(x, com_conj))
y_times_com_conj = content(mul_com(y, com_conj))
return make_com(div(real(x_times_com_conj), real(y_times_com_conj)),
div(imag(x_times_com_conj), real(y_times_com_conj)));
def complex_conjugate(x):
return (real(x),negate(imag(x)))
def negate_com(x): # (RepCom) -> Generic-Com
return make_com(negate(real(x)), negate(imag(x)))
def is_zero_com(x): # (RepCom) -> Py-Bool
if is_zero(real(x)) and is_zero(imag(x)):
return True
else:
return False
def is_eq_com(x,y): # (RepCom, RepCom) -> Py-Bool
if is_equal(real(x),real(y)) and is_equal(imag(x),imag(y)):
return True
else:
return False
put("make","complex", make_com)
put("add",("complex","complex"), add_com)
put("sub",("complex","complex"), sub_com)
put("mul",("complex","complex"), mul_com)
put("div",("complex","complex"), div_com)
put("negate",("complex",), negate_com)
put("is_zero",("complex",), is_zero_com)
put("is_equal",("complex","complex"), is_eq_com)
def repord_to_repcom(x):
return repcom(create_ordinary(x),create_ordinary(0))
def CCmethod_to_OCmethod(method):
return lambda ord, com: method(repord_to_repcom(ord), com)
def CCmethod_to_COmethod(method):
return lambda com, ord: method(com, repord_to_repcom(ord))
put("add",("ordinary","complex"), CCmethod_to_OCmethod(add_com))
put("add",("complex","ordinary"), CCmethod_to_COmethod(add_com))
put("sub",("ordinary","complex"), CCmethod_to_OCmethod(sub_com))
put("sub",("complex","ordinary"), CCmethod_to_COmethod(sub_com))
put("mul",("ordinary","complex"), CCmethod_to_OCmethod(mul_com))
put("mul",("complex","ordinary"), CCmethod_to_COmethod(mul_com))
put("div",("ordinary","complex"), CCmethod_to_OCmethod(div_com))
put("div",("complex","ordinary"), CCmethod_to_COmethod(div_com))
put("is_equal",("ordinary","complex"), CCmethod_to_OCmethod(is_eq_com))
put("is_equal",("complex","ordinary"), CCmethod_to_COmethod(is_eq_com))
def create_complex(x,y):
return get("make","complex")(x,y)
#################
# Do not change #
#################
n3 = create_ordinary(3)
c3_plus_0i = create_complex(create_ordinary(3), create_ordinary(0))
c2_plus_7i = create_complex(create_ordinary(2), create_ordinary(7))
def gradeThis_complex_package():
complexA = is_equal(n3, c3_plus_0i)
complexB = is_equal(sub(add(n3, c2_plus_7i), c2_plus_7i), n3)
if complexA and complexB:
print("Well done! Your install_complex_package is complete!")
else:
print("Please check your solution for install_complex_package.")
gradeThis_complex_package()
Below is the supported file that it is imported from:
_operation_table = {} #variables with prefixed with an _ are by convention, for internal use and should not be touched.
def attach_tag(tag, content):
return (tag, content)
def type_tag(datum):
if type(datum) == tuple and len(datum) == 2:
return datum[0]
raise Exception('Bad tagged datum -- type_tag ', datum)
def content(datum):
if type(datum) == tuple and len(datum) == 2:
return datum[1]
raise Exception('Bad tagged datum -- content ', datum)
def put(op, types, value):
if op not in _operation_table:
_operation_table[op] = {}
_operation_table[op][types] = value
def get(op, types):
if op in _operation_table and types in _operation_table[op]:
return _operation_table[op][types]
else:
return None
def apply_generic(op, *args):
type_tags = tuple(map(type_tag, args))
proc = get(op, type_tags)
if proc:
return proc(*map(content, args))
raise Exception('No method for these types -- apply_generic', (op, type_tags))
##########################
# Generic Number Package #
##########################
#generic operators we want to support
def add(x,y):
return apply_generic("add", x, y)
def sub(x,y):
return apply_generic("sub", x, y)
def mul(x,y):
return apply_generic("mul", x, y)
def div(x,y):
return apply_generic("div", x, y)
def negate(x):
return apply_generic("negate", x)
def is_zero(x):
return apply_generic("is_zero", x)
def is_equal(x, y):
return apply_generic("is_equal", x, y)
#composite generic operators
def square(x):
return mul(x,x)
#Generic ordinary number package
def install_ordinary_package():
def make_ord(x):
return tag(x)
def tag(x):
return attach_tag("ordinary", x)
# add,sub,mul,div: (RepOrd, RepOrd) -> Generic-OrdNum
def add_ord(x,y):
return make_ord(x+y)
def sub_ord(x,y):
return make_ord(x-y)
def mul_ord(x,y):
return make_ord(x*y)
def div_ord(x,y):
return make_ord(x/y)
def negate_ord(x): # (RepOrd) -> Generic-Ord
return make_ord(-x)
def is_zero_ord(x): # (RepOrd) -> Py-Bool
return x == 0
def is_equal_ord(x,y): # (RepOrd, RepOrd) -> Py-Bool
return x == y
put("make","ordinary", make_ord)
put("negate",("ordinary",), negate_ord)
put("is_zero",("ordinary",), is_zero_ord)
put("add",("ordinary","ordinary"), add_ord)
put("sub",("ordinary","ordinary"), sub_ord)
put("mul",("ordinary","ordinary"), mul_ord)
put("div",("ordinary","ordinary"), div_ord)
put("is_equal",("ordinary","ordinary"), is_equal_ord)
install_ordinary_package()
def create_ordinary(x):
return get("make", "ordinary")(x)
Where exactly did the above code cause the rise to this error? If anyone could help I would really appreciate it. Thank you!
Your _operation_table dictionary does not contain an entry with make and complex therefore your get() function returns None which in fact is not callable.
print("complex" in _operation_table["make"])
False
Perhaps you've forgotten to call install_complex_package (in the same way you called install_ordinary_package) which adds the required function to _operation_table. Once called, your code works fine.

Can I create a master function in Python to take a single line of other functions?

I have two functions that contain mostly the same code. One returns "True" if the array passed in contains all positive numbers while the other returns "True" if the array contains all numbers that are divisible by 10.
I want to combine these two functions into a function like this:
def master_function(array, function):
for i in array:
if function:
result = True
else:
result = False
break
print(result)
return result
The only part that would vary is the "function" in the If statement. When I write functions with the missing line they don't get called as the program executes.
def positive_integers(array):
i >= 0
def divisible_by_10(array):
i%10 == 0
The test code isn't executed either.
master_function([10,20,30,35],divisible_by_10)
Your functions aren't returning anything, and you need to give them access to i:
def positive_integers(i):
return i >= 0
def divisible_by_10(i):
return not i%10
def master_function(array, function):
for i in array:
if function(i):
result = True
else:
result = False
break
print(result)
return result
Your function don't return anything. Also, you need read about all and any:
def positive_integers(array):
return all(i >= 0 for i in array)
def divisible_by_10(array):
return all(i % 10 == 0 for i in array)
def master_function(array, function):
return function(array)
def master_function(array, function):
for i in array:
print str(i)
if function(i):
result = True
else:
result = False
print(result)
return result
def positive_integers(i):
if i >= 0:
return True
def divisible_by_10(i):
if i%10 == 0:
return True
master_function([10,20,30,35],divisible_by_10)

(Beginner)Python functions Codeacademy

I'm just learning to program on Codeacademy. I have an assignment, but cant figure out what I'm doing wrong.
First I need to define a function that returns the cube of a value. Then I should define a second function that checks if a number is divisible by 3. If it is I need to return it, otherwise I need to return False.
heres the code:
def cube(c):
return c**3
def by_three(b):
if b % 3 == 0:
cube(b)
return b
else:
return False
You are not catching the return value of the function cube. Do b = cube(b). Or better yet, do return cube(b).
def cube(c):
return c**3
def by_three(b):
if b % 3 == 0:
b = cube(b)
return b # Or simply return cube(b) and remove `b = cube(b)`
else:
return False
When you call the cube function with the argument b, it returns the cube of the passed argument, you need to store it in a variable and return that to the user, in your current code, you are neglecting the returned value.
I think this answer might also work:
def cube(b,c):
b = c ** 3
if b % 3 == 0:
return b
else:
return False
return b
I know that might be a little redundant but I think that might be another way of doing what you're trying to do. What Sukrit did I think is simpler.
I have finished Codecdemy and this is my code.
def cube(n):
return n ** 3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
Here's a lightweight solution I just developed, should work :)
def cube(number):
return number**3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
def cube(num):
return n ** 3
def by_three(value):
if value % 3 == 0:
return cube(value)
else:
return False
try calling the same letter for each. Instead of using 'c' and 'b', just use 'c'
def cube(c):
return c**3
def by_three(c):
if c % 3 ==0:
return cube(c)
else:
return False

AttributeError: 'bool' object has no attribute 'keys'

i am a newbie on this site and am also a newbie to programming, i'm trying to learn python using a book for beginners on python 3.1. I have come across an example that just won't work whatever I try, I have searched for faults in writing about 10 times still it seems exactly what I see in the book. This is the example:
the fridge class
#!/usr/bin/env
class Fridge:
"""methods:
has(food_name [, quantity])-chk if string is in the fridge
has_various(foods)-chk if enough food is in the fridge
add_one(food_name) -adds 1 food
add_many(food_dict)- adds dict to fridge
get_one(food_name)- take out 1 food
get_many(food_dict) - a dict out of fridge
get_ingred(food)- if passed an obj get the list of __ingredients__
"""
def __init__(self, items={}) :
if type(items) != type({}):
raise typeError("Fridge req a dict but was given %s" % type(items))
self.items=items
return
def __add_multi(self, food_name, quantity):
if (not food_name in self.items):
self.items[food_name]=0
self.items[food_name]=self.items[food_name]+quantity
def add_one(self, food_name):
if type(food_name) != type(""):
raise TypeError ("add_one requires a string givem a %s " % type(food_name))
else:
self.__add_multi(food_name, 1)
return True
def add_many(self, food_dict):
if type(food_dict) != type({}):
raise TypeError ("add_many requires a dict, got a %s" % type(food_dict))
for item in food_dict.keys() :
self.__add_multi(item, food_dict[item])
return
def has(self, food_name, quantity=1):
return self.has_varoius({food_name:quantity})
def has_various(self, foods):
try:
for food in foods.keys():
if self.items[food] < foods[food]:
return False
return True
except KeyError:
return Fasle
def __get_multi(self, food_name, quantity):
try:
if (self.items[food_name] is None) :
return False
if (quantity > self.items[food_name]):
return False
self.items[food_name] = self.items[food_name] - quantity
except KeyError:
return False
return quantity
def get_one(self, food_name):
if type(food_name) !=type(""):
raise TypeError("get_one requires a string and was given a %s" % type(food_name))
else:
result=self.__get_multi(food_name, 1)
return result
def get_many(self, food_dict):
if self.has_various(food_dict):
foods_removed={}
for item in food_dict.keys():
foods_removed[item]=self.__get_multi(item, food_dict[item])
return foods_removed
def get_ingredients(self, food):
try:
ingredients=self.get_many(food.__ingredients())
except AttributeError:
return False
if ingredients!=False:
return ingredients
the omelet class
#!/usr/bin/env python3.3
class Omelet:
def __init__(self, kind="cheese"):
self.set_kind(kind)
return
def __ingredients__(self):
return self.needed_ingredients
def get_kind(self):
return self.kind
def set_kind(self, kind):
possible_ingredients=self.__known_kinds(kind)
if possible_ingredients == False :
return False
else:
self.kind=kind
self.needed_ingredients= possible_ingredients
def set_new_kind(self, name, ingredients):
self.kind=name
self.needed_ingredients= ingredients
return
def __known_kinds(self, kind):
if kind == "cheese":
return {"eggs":2, "milk":1, "cheese":1}
elif kind == "mushroom":
return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
elif kind == "onion":
return {"eggs":2, "milk":1, "cheese":1, "onion":1}
else:
return False
def get_ingredients(self, fridge):
self.from_fridge= fridge.get_ingredients(self)
def mix(self):
for ingredient in self.from_fridge.keys():
print("mixing %d %s for the %s omelet" % (self.from_fridge["ingredient"], ingredient, self.kind))
self.mixed=True
def make(self):
if self.mixed == True:
print("Cooking the %s omelet!" % self.kind)
self.cooked = True
this is how i invoke the classes and what i do to use the classes and the error i get
>>> exec(open("/home/knoppix/test/fridge.py").read())
>>> exec(open("/home/knoppix/test/omelet.py").read())
>>> o=Omelet("cheese")
>>> f=Fridge({"cheese":5, "milk":4, "eggs":12})
>>> o.get_ingredients(f)
>>> o.mix()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 41, in mix
AttributeError: 'bool' object has no attribute 'keys'
Please excuse me if there is a typing fault in the code , it`s exactly what I found in the book!
def get_ingredients(self, fridge):
self.from_fridge= fridge.get_ingredients(self)
In this function, your fridge.get_ingredients() might be returning False.
So self.from_fridge has Boolean value which does not have keys() method.
You may want to add appropriate check in mix() method.
The function "__known_kinds(kind)" should preferably return {} to be consistent, instead of different object types although "None" is better than "False".
if kind == "cheese":
return {"eggs":2, "milk":1, "cheese":1}
elif kind == "mushroom":
return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
elif kind == "onion":
return {"eggs":2, "milk":1, "cheese":1, "onion":1}
else:
return {}
Then you only have to deal with dictionary type in mix() method. The else can also be dropped from mix() as exception will be raised if dict == {}.
def mix(self):
if self.from_fridge == {}:
raise IndexError("self.from_fridge returns Nothing")
for ingredient in self.from_fridge.keys():
....

Categories

Resources