0

I need a small tips to finished this exercise. The program should display head or tail after the for loop generate a sequence of 0 and 1. This module contains a number of random number generators:

import random

# function to determine head or tail of printed random number
def flip(coin):
    # if the coin is zero, then print head
    if coin == 0:
        print("heads!")
    # else print tail
    else:
        print("Tail!")
# simple repeat loop that calls flip() 10 times to generate a random
# sequence of 10 heads and tails
def main():
     for coin in range(10):
        print (random.randrange(2))

main()
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Joy
  • 33
  • 4

2 Answers2

3

You need to call the flip function, passing it the result of that random.randrange(2) call:

print (flip(random.randrange(2)))

As Padraic points out in comments, your code will also output None, because it's printing the returned value from the called function, and no return statement produces an implicit None. You can fix this in one of two ways: either have flip return the result instead of printing it, or call it without printing.

if coin == 0:
    return "heads!"
# else print tail
else:
    return "Tail!"

or:

flip(random.randrange(2))
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
3

you need to call the flip function. Also I would recommend using random.randint()

import random

#function to determine head or tail of printed random number
def flip(coin):
    #if the coin is zero, then print head
    if coin == 0:
        print("heads!")
    #else print tail
    else:
        print("Tail!")
#simple repeat loop that calls flip() 10 times to generate a random
#sequence of 10 heads and tails
def main():
     for coin in range(10):
        flip(random.randint(0, 1))

main()
Razor Robotics
  • 183
  • 1
  • 9