Hi, I am a beginner for Python. There is one problem I encounter with a coin flip program which there are "None" involved with the print out. Any help will be appreciated.

import random

def flip():
    cflip = random.randrange(2)
    if cflip == 0:
        print("Heads")
    else:
        print("Tails")
     
def main ():
    for x in range (10):
        print (flip())
main ()

Here is the answer:

>>> 
Heads
None
Tails
None
Tails
None
Tails
None
Heads
None
Heads
None
Heads
None
Tails
None
Heads
None
Tails
None
>>>

Like I mentioned, there are strange "None" appear for each time the function is called. Please help. Thanks for your time.

Dani AI

Generated

Short answer: the function flip() prints a result but does not return one, so print(flip()) prints the string from inside flip() and then prints the function's implicit return value, None. pointed this out — returning the value (or not printing it twice) fixes the problem.

A couple of clear fixes:

  • Make flip() return the outcome and let the caller print it:
import random

def flip():
    return "Heads" if random.randrange(2) == 0 else "Tails"

for _ in range(10):
    print(flip())
  • Or keep flip() as a printing function and call it directly from the loop (do not wrap it in print()):
import random

def flip():
    if random.randrange(2) == 0:
        print("Heads")
    else:
        print("Tails")

for _ in range(10):
    flip()

Troubleshooting tips:

  • In the REPL, call flip() and observe whether it prints or returns a value. If you see the text then >>> flip() shows it but >>> x = flip() results in x being None, the function printed but did not return.
  • Prefer returning values from functions when the logic should be testable or reused; keep printing (side effects) in the caller. This makes unit testing and reuse easier.
  • Add the usual entry guard for scripts you run as programs: if __name__ == "__main__": and put the loop there.

This explains why each call produced an extra None and gives two simple, immediate fixes for to try.

Recommended Answers

All 2 Replies

You should return value from function, not print.

@pyTony Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.