Why does my code return 'None' along with the correct output?

Question:

I have a program that takes 4 number inputs and passes them to a user defined function. the first value becomes the second in the list, and the 4th value becomes the third in the list. The program is supposed to output the inputs as numbers with spaces in between them.

def swap_values(user_val1, user_val2, user_val3, user_val4):
    newList = [user_val2, user_val1, user_val4, user_val3]
    return print(f'{newList[0]} {newList[1]} {newList[2]} {newList[3]}')

if __name__ == '__main__': 
    val1 = int(input())
    val2 = int(input())
    val3 = int(input())
    val4 = int(input())
    print(swap_values(val1, val2, val3, val4))

While I do get the correct answer outputted for the input "8, 3, 4, 2", I also get ‘None’ right bellow it like so

3 8 2 4
None

What should I do to fix this?

Asked By: Alelx

||

Answers:

This is because the function swap_values is first printing the value and returning the print function which is None
This can be fixed by using this code:

def swap_values(user_val1, user_val2, user_val3, user_val4):
newList = [user_val2, user_val1, user_val4, user_val3]
return f'{newList[0]} {newList[1]} {newList[2]} {newList[3]}'
if __name__ == '__main__': 
    val1 = int(input("val1"))
    val2 = int(input("val2"))
    val3 = int(input("val3"))
    val4 = int(input("val4"))
    print(swap_values(val1, val2, val3, val4))
Answered By: Anay_28

You have two print statements.

This line

    return print(f'{newList[0]} {newList[1]} {newList[2]} {newList[3]}')

prints the four numbers, and then returns the return value of the print operation. But print doesn’t have a return value in Python, so it’s "None". Then this line

    print(swap_values(val1, val2, val3, val4))

prints that return value.

You could change swap_values() to simply return a string, and then have the caller print it out. Or you could print the values inside swap_values(), and just call that function without another print statement around the call. Just don’t do both.

Answered By: Ben23

You print the return value from print() which is None.

Rather than print within the swap_values function, return the swapped values then print. For example:

def swap_values(user_val1, user_val2, user_val3, user_val4):
    return user_val2, user_val1, user_val4, user_val3

print(*swap_values(1,2,3,4))

Output:

2 1 4 3
Answered By: Pingu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.