0

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

atline
  • 28,355
  • 16
  • 77
  • 113
  • 1
    `print(is_weird(N))` -> `is_weird(N)`. Or don't print inside function, instead use `return`. – Austin Dec 24 '18 at 05:35
  • you are trying to print response from your function, currently you are returning nothing. So only need to call the function instead of print `is_weird(N)` – Vikas Periyadath Dec 24 '18 at 05:37

1 Answers1

0

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
Rish
  • 804
  • 8
  • 15