1

Beginner programmer here working with Python and am currently experiencing a bug.

I am trying to write a function where, when a user inputs a number the machine will return True if the number input is 5. If the number input is any other number it will return as None.

Currently, when I enter 5 I will get True followed by None. If I enter any other number I will get None followed by None again. Anyone have any ideas?

Here is the code:

x = int(input('Enter a number: '))

def is_it_five (x):
    if x == 5:
        print(True)
    else:
        print(None)

print(is_it_five (x))
AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    Having your parameter also named `x` isn’t a great idea. – AMC Nov 17 '19 at 07:12
  • When you have a boolean test *just return the result of the boolean test*. Using `if : return True`, `else: return False` is entirely redundant over `return `. – Martijn Pieters Jan 19 '20 at 21:24

4 Answers4

1

Your first value is coming from the loop, and the second value 'None' is coming from Print function, since you are not returning anything.

Either you can call the function without print statement:

is_it_five (x)

Or you can return it from the function and print.

x = int(input('Enter a number: '))

def is_it_five (x):
    if x == 5:
        return True
    else:
        return None

print(is_it_five (x))
NiKS
  • 377
  • 3
  • 15
1
x = int(input('Enter a number: '))

def is_it_five (x):
    if x == 5:
        return(True)

    else:
        return(False)

print(is_it_five (x))
Jainil Patel
  • 1,284
  • 7
  • 16
1

Functions in Python always return some value. By default, that value is None. So if I create any random function e.g

def get_string(some_string):
    print(some_string)

and then execute it; get_string("Example")

The output will be

Example

But, if you do print(get_string("Example")) The output will change to

Example
None

This is because the

get_string("Example")

is treated as an object in this case when you pass it inside the print statement.

However, when you are calling the function without printing it, you are not printing the value which the function returns.

In the same context if you do something like

value = get_string(some_string)

Your string will get printed as usual, but now the value variable will contain None.

0

Your problem is that you are printing a function that already prints something when called. Replace

print(is_it_five(x))

with just

is_it_five(x)

Emerson SD
  • 23
  • 3