Python function question about if-elif function
Question:
Below is my answer for a question on Hackerrank.
However, when I run the code, 2 values appeared in the terminal. One of which is a None value. I’m not sure which line of code created this None value. Please advice. Thank you
Code:
def is_weird(num):
if num % 2 == 1:
print("Weird")
elif num % 2 == 0 and 2 <= num <= 5:
print("Not Weird")
elif num % 2 == 0 and 6 <= num <= 20:
print("Weird")
elif num % 2 == 0 and num > 20:
print("Not Weird")
N = int(input("Enter number: "))
print(is_weird(N))
Terminal output:
Enter number: 8
Weird
None
Answers:
Python function returns None
by default. In your case, the is_weird()
function is returning None
.
So, when you enter 8 as input, your function prints "Weird"
because of the print statement inside the function and then it returns None
. This value gets printed because of the line print(is_weird(N))
Your isweird() function is equivalent to:
def is_weird(num):
if num % 2 == 1:
print("Weird")
elif num % 2 == 0 and 2 <= num <= 5:
print("Not Weird")
elif num % 2 == 0 and 6 <= num <= 20:
print("Weird")
elif num % 2 == 0 and num > 20:
print("Not Weird")
return None
Below is my answer for a question on Hackerrank.
However, when I run the code, 2 values appeared in the terminal. One of which is a None value. I’m not sure which line of code created this None value. Please advice. Thank you
Code:
def is_weird(num):
if num % 2 == 1:
print("Weird")
elif num % 2 == 0 and 2 <= num <= 5:
print("Not Weird")
elif num % 2 == 0 and 6 <= num <= 20:
print("Weird")
elif num % 2 == 0 and num > 20:
print("Not Weird")
N = int(input("Enter number: "))
print(is_weird(N))
Terminal output:
Enter number: 8
Weird
None
Python function returns None
by default. In your case, the is_weird()
function is returning None
.
So, when you enter 8 as input, your function prints "Weird"
because of the print statement inside the function and then it returns None
. This value gets printed because of the line print(is_weird(N))
Your isweird() function is equivalent to:
def is_weird(num):
if num % 2 == 1:
print("Weird")
elif num % 2 == 0 and 2 <= num <= 5:
print("Not Weird")
elif num % 2 == 0 and 6 <= num <= 20:
print("Weird")
elif num % 2 == 0 and num > 20:
print("Not Weird")
return None