This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I have this code:
def the_flying_circus():
if True and True and True and not False:
print "Kevin stinkt"
elif 10 < 4:
print "Justin stinkt"
else:
print "herb-wuerzig"
When I print the_flying_circus I get Kevin stinkt printed, None as a return. I would need False as return for an online tutorial. Why do I get None, and how can I achieve an True?
None is the return value of the function. A function that finishes without an explicit return statement will return None.
In response to your additional question:
If you want the function to return true, put
return True
at the end. If you want it to return false, put
return False
at the end.
The function returns None if it does not return anything else, hence you first print inside the function and then you print the None that was returned.
If you either exchange your print statements with return or just call the_flying_circus() instead of print the_flying_circus() you will get the expected result.
def the_flying_circus():
if True and True and True and not False:
return "Kevin stinkt"
elif 10 < 4:
return "Justin stinkt"
else:
return "herb-wuerzig"
Then you can run the function and print the returned value:
print the_flying_circus()
Or you can do:
def the_flying_circus():
if True and True and True and not False:
print "Kevin stinkt"
elif 10 < 4:
print "Justin stinkt"
else:
print "herb-wuerzig"
And just call the function without printing the returned value:
the_flying_circus()
The code needed is the following:
# Make sure that the_flying_circus() returns True
def the_flying_circus(antwort):
if antwort > 5:
print "H"
elif antwort < 5:
print "A"
else:
print "I"
return True
what ever input I give, the_flying_circus always returns True
Related
Python: Why don't I get a result in the terminal
def is_even(number):
if number % 2 == 0:
return True
return False
is_even(10)
You need to print the output of the function. You also need to create the function.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(10)) #True
print(is_even(7)) #False
I am trying to get a print statement on the same line as the return statement, how do I go about doing this?
I have tried to put the print statement just under the if statement, but above return statements and it prints the result above the return statement.
def isleap(y):
if y % 400 == 0:
print("Year %d is divisible by 400, therefore it is a leap year" %y)
return True
elif y % 100 ==0:
return False
elif y % 4 == 0:
return True
else:
return False
I am importing the above code to run from another file, which is this:
import leapyear
print (leapyear.isleap(1800))
print (leapyear.isleap(2019))
print (leapyear.isleap(2000))
print (leapyear.isleap(2012))
This is the result:
False
False
Year 2000 is divisible by 400, therefore it is a leap year
True
True
I want the result to have something like
True: Year 2000 is divisible by 400, therefore it is a leap year
all in the same line, with the colon involved.
You can return True and the print statement together. With the help of the star * operator you can pass elements from the tuple to the print() function as separate parameters:
def func():
return True, 'It works.'
print(*func())
# True It works.
If the order of print statements is not important you can add the parameter end='' to the first print() function:
def func():
print('It works.', end='')
return True
print(func())
# It works.True
You can do something like this:
def isleap(y):
if y % 400 == 0:
return True, ': Year %d is divisible by 400, therefore it is a leap year' %y
elif y % 100 ==0:
return False, ''
elif y % 4 == 0:
return True, ''
else:
return False, ''
print(*isleap(1800), sep='')
print(*isleap(2019), sep='')
print(*isleap(2000), sep='')
print(*isleap(2012), sep='')
print()
# If you want to use it later.
ret = isleap(2000)
if ret[0]:
print('Length of the message is:', len(ret[1]))
Output:
False
False
True: Year 2000 is divisible by 400, therefore it is a leap year
True
Length of the message is: 60
After I answered this question, the person who asked this question asked what to do if he/she wants to reuse the results. Hence, I have updated my answer which is similar to this answer.
This function is supposed to return True if a number is prime and False if it's not. The problem is that is_prime(9) returns True.
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3:
return True
else:
for i in range(2,x):
if x%i==0:
return False
break
else:
return True
Because if you write
for i in range(2,x):
if x%i==0:
return False
break
else:
return True
if x is 9 then 9%2 != 0, so it takes else path and returns True
odd_number % 2 is always = 1
You have to remove the last line and replace it with return True after the for has finished:
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3: #<-- This one is useless, it will be already checked within the for
return True
else:
for i in range(2,x):
if x%i==0:
return False
break
return True
print is_prime(9)
print is_prime(11)
Your code is improperly indented. The else:return True line should be indented one level less, so that it runs after the for loop terminates. The current code returns True whenver any divisibilty test fails, not when all of the divisibility tests fail.
The function is buggy. The else: inside the loop is returning True the first time it encounters a number that isn't a divisor. That needs to be deleted, and the return True needs to be placed after the loop (outside of it).
Check indentation. The if and else in the for loop.
Understand the meaning of return, the function literally exits when you return.
Corrected code:
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3:
return True
else:
for i in range(2,x):
if x%i==0:
print "Hello"
return False
break
else:
return True
print is_prime(9)
I have two functions cube which returns a number cubed and by_three which, if cube is divisible by 3, I need to return cube, else return false. here is what I have so far(below). I keep getting the "Oops, try again. by_three(3) returned True instead of 27 " error, some please help if you know what im doing wrong, or perhaps idiotic!.
def cube(number):
return number**3
def by_three(number):
return number%3==0
if bythree(number):
return cube(number)
else:
return false
Your indentation is all over the place but this will do what you want:
def cube(number):
return number**3
def by_three(number):
return number%3==0
def main(number):
return cube(number) if by_three(number) else False
if by_three(number) is True cube(number) will be called and returned else just False will be returned.
Your code is either unreachable after the return or you have it outside the function where a return will not work. There is also no false in python it is upper case F `
You need a third method.
def cube(number):
return number**3
def by_three(number):
return number%3==0
def whattodo(number):
if by_three(number):
return str(cube(number)) #We must return one type, so we return string for both false and number
else:
return "false"
try:
print int(whattodo(input("Enter a number")) #We are trying to convert the string into an integer
except ValueError: #What if it is not a number? (In this case, it will be a string whose value is "false"
print "Your number is not divisible by three. Screw you"
Try this:
def cube(number):
return number**3
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
I have a program that does a simple palindrome check, by comparing each ends of the string and then doing a substring of the original string recursively. That is, I compare str[0] to str[-1], do a str[1,-1] and repeat the comparisons. What I did find while stepping through the code is, that when I ask the function check_palin() to return 1, it returns None. I can clearly see it 'execute' the return statement, but it always returns None when I ask it to return 1. However, it returns 0 correctly. The same behavior is observed with returning True/False. Here is my code. What am I doing wrong??
def check_palin(s):
global init
print("Init is %d" %(init))
if len(s) <= 1 :
if not init :
print("returning 1")
return True
else :
print("Please supply a string of atleast 2 characters! Exiting...\n")
print("returning 0")
return False
else :
init = 0
if first_word(s) == last_word(s) :
check_palin(middle(s))
else :
print("returning 0")
return False
def first_word(s) :
return s[0]
def last_word(s):
return s[-1]
def middle(s):
return s[1:-1]
init = 1
s = raw_input("Please enter a string")
print(check_palin(s))
if not check_palin(s) :
print ("String %s IS NOT a palindrome!" %(s))
else :
print ("String %s IS a palindrome!" %(s))
Output:
Please enter a stringababa
Init is 1
Init is 0
Init is 0
returning 1
None
Init is 0
Init is 0
Init is 0
returning 1
String ababa IS NOT a palindrome!
Process finished with exit code 0
You forgot to return the result of your recursion.
if first_word(s) == last_word(s) :
return check_palin(middle(s))