Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading