Hi all,
This is a problem that has been holding me up for a while in Python. I frequently get issues relating to "global ___ is not defined" and cannot figure out what I'm doing wrong. Here is a coin-flip function I wrote:
def coinflip():
import random
import time
heads = 0
tails = 0
flips = 0
rec = open('coin toss.txt','w')
rec.write('Coin Toss Record')
rec.write('\n')
N = int(raw_input('Welcome to the Coin Toss! How many times do you want to flip the coin?: '))
while (flips < N):
flip = random.randint(1,2)
if flip == 1:
heads += 1
if heads > 0:
rec.write('H ')
time.sleep(.1)
flips += 1
else:
tails += 1
if tails > 0:
rec.write('T ')
time.sleep(.1)
flips += 1
print "There were ", tails ," and ", heads ," heads."
and the script I run the function in is:
import coinflip
import random
coinflip.coinflip()
When I run the script, it will ask for the number of flips, and then I get the error "global name 'random' is not defined." There is nothing else named random in the folder for the file to get confused about, and random works in other settings, just not when I try to use it when using a function in a script. I'm sure this is an obvious fix to those with more experience, but any help would be deeply, deeply appreciated.