When there is a print statement inside a function, it is not printing.
I dont understand what is going wrong.
def test():
print("please print this")
return "return this"
And, my main function is like this:
if __name__ == "__main__":
classwhereiwrotefunction.test()
When I use a debugger, and try to store the return value in a variable, it does show the value. But, does not print it.
the problem is with indentation I guess. Try the below code it will work.
class Class_name:
def test(self):
print("please print this")
return "return this"
if __name__ == "__main__":
class_name = Class_name()
print(class_name.test())
>> please print this
>> return this
Related
def user(choose):
if (choose == "1"):
play = game()
elif (choose == "2"):
return stats(play)
else:
return quit()
I want to take the value from function game() and use it in stats(), but I get an error saying that play is not defined. How do I declare game() and use it in another function?
You could "postpone" execution of func1:
def func1():
return 'abc'
def something_else(callable):
callable()
def main():
hello = None
def f():
"""set result of func1 to variable hello"""
nonlocal hello
hello = func1()
# over here func1 is not executed yet, hello have not got its value
# you could pass function f to some other code and when it is executed,
# it would set result for hello
print(str(hello)) # would print "None"
call_something_else(f)
print(str(hello)) # would print "abc"
main()
After question has changed...
Right now, your local variable play is out of scope for stats.
Also, looks like you expect that function would be called twice.
You need to save play in global content
play = None # let's set it to some default value
def user(choose):
global play # let python know, that it is not local variable
if choose == "1": # no need for extra brackets
play = game()
if choose == "2" and play: # double check that play is set
return stats(play)
return quit()
Why is it that when this code is executed, I would get 'hi'?
Thanks!
def b():
print("hi")
def c():
return True
if b() == 'hi':
print("Done")
You are confusing printing to the console with returning a value. Your function implicitly returns None if you do not return anything from it so it is never equal to 'hi'. Your b() does print - and not return its 'hi'
def b():
print("hi") # maybe uncomment it if you do not want to print it here
return "hi" # fix like this (which makes not much sense but well :o)
def c():
return True
if b() == 'hi':
print("Done")
You can test it like this:
def test():
pass
print(test())
Outputs:
None
Further readings:
about the return statement
about defining functions (read the paragraph below the second fib-CodeBlock example - it tells you about None)
One even more important thing to read: How to debug small programs (#1) - it gives you tips on how to fix code yourself and find errors by debugging.
Essentially what you're doing is saying if b(), which runs the b() function and prints "hi" is equal to "hi", print "done", but since your function prints "hi", rather than returning "hi", it will never equal true.
Try this:
def b():
return "hi"
def c():
return True
if b() == 'hi':
print("Done")
Instructions:
First, def a function called distance_from_zero, with one argument (choose any >argument name you like).
If the type of the argument is either int or float, the function should return >the absolute value of the function input.
Otherwise, the function should return "Nope"
I've done the first task and I thought that i completed the task, however
"Your function seems to fail on input True when it returned 'None' instead of 'Nope'"
Here is my code:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
print(argument)
else:
print("Nope")
From what ive seen in other modules codecademy tests this with my arguement being "1", such that the if statement goes through, will return the absolute value of (argument) and then i would pass the module. (i added print(argument) for testing purposes, the console outputs nothing.)
Am i mis understanding how returning works? Why is this not working?
I appreciate all responses! :)
EDIT: It prints "None", not "Nope" in the console. Forgot to mention this.
In Python, if return isn't explicit, it becomes None. Try this:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
print(abs(argument))
else:
print("Nope")
> f = distance_from_zero(-4234)
4234
> f
None
As you can see the value of f is None, this is because print is outputting to the console and not actively returning content. Instead, try using the return statement:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
else:
return "Nope"
> distance_from_zero(123)
123
# here, because you're not assigning the value returned to a variable, it's just output.
> f = distance_from_zero(-4234)
> f
4234
> f = distance_from_zero('cat')
> f
'Nope'
It's also important to know that the reason this:
return abs(argument)
print(argument)
printed to the console is not because of the print call. Anything after return in a block is not executed. The reason you see the output printed to the screen is because in the interpreter Python outputs all function return values not collected into variables.
def distance_from_zero(num):
if type(num) == int or type(num) == float:
return abs(num)
else:
return "Nope"
I have a class file. Let's call it "C1.py". The sample code looks like below.
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
def M1(ans):
if ans == 1 or ans == 2:
return True
else:
return False
Now, I have another python file in the same folder, which will access the class file shown above.
from trial import C1
def getAns(class1):
while True:
ans = input("Answer: ")
if class1.M1(ans):
return ans
break
sample = C1()
print sample.greeting
ans = getAns(sample)
print ans
When I run those files, sample.greeting prints fine. Everything is fine until when the execution reaches the line "ans = getAns(C1)", which gives the error "M1() takes exactly 1 argument (2 given)".
So, where in the code should I change so that I can call that method successfully?
Note here that the above code is only the abstraction of my whole program to highlight my problem. It sounds stupid with just the code above alone. So, please, please bear with that for me.
M1 is currently defined as a method of C1, as such it needs to have an additional self argument which would be the instance of the class. I.e
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
def M1(self, ans):
if ans == 1 or ans == 2:
return True
else:
return False
In other languages such as C++ or Java the presence of self (or this) is implicit, but in python it's explicit.
alternatively if you don't want or need M1 to access C1's state you could make M1 static via #staticmethod i.e.
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
#staticmethod
def M1(ans):
if ans == 1 or ans == 2:
return True
else:
return False
So I'm having a problem with a larger piece of code where I'm getting an error message when I'm calling a function inside of another function that is inside of a class. In the code:
#Test program to solve problems.
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self):
return self.number**2
if __name__ == "__main__":
test = Foo(input("Choose a number: "))
print test.run()
I raise an "AttributeError: Foohas no attribute calculate", but I don't understand why? Am I calling calculate wrong to throw this error?
EDIT
So I know that if I change the indentation or calculate it works, but I wanna know is there anyway to get it working as it currently is with calculate indented in run or do python classes not work that way.
Updated after question edit:
Check out this link that shows how to make a "closure" https://stackoverflow.com/a/4831750/2459730
It's what you described as a function inside of a function.
def run(self):
def calculate(self): # <------ Need to declare the function before calling
return self.number**2
print "I will now square your number"
print "Your number squared is: "
print self.calculate() # <---- Call after the function is declared
Before question edit:
Your calculate function isn't indented properly.
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): # <----- Proper indentation
return self.number**2 # <------ Proper indentation
The calculate function should have the same indentation level as the run function.
Indentation level is off. You are defining calculate INSIDE of the run function instead of in the class.
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): #NOTE THE INDENTATION DIFFERENCE
return self.number**2
if __name__ == "__main__":
test = Foo(input("Choose a number: "))
print test.run()
Seems you call function before it is defined. I think closure should help you:
def run(self):
print "I will now square your number"
print "Your number squared is: "
def calculate():
return self.number**2
print calculate()
When you define a function inside a function then there is not need to use 'self'
in inner function and call function after defining it.
so you can write the code as,
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
#This squares the number
def calculate():
return self.number**2
print "I will now square your number"
print "Your number squared is: "
print calculate()
if __name__ == "__main__":
test = Foo(int(input("Choose a number: ")))
print test.run()
The problem is just that you can't do that. It may seem tempting because you can outside of a class and it makes your code a littler cleaner, but within a class, you can't do it.