0

I have this code which has some semantic errors which I can't find. The first line fails to tell us what the coin flip was. The 1000 flips are a mathematically improbable 1000 tails. The die rolls a 0 when the values should be between 1 and 6. The two dice result just tells us about the function and the 10 dice result also has zeros in it.

import random
import numpy as np

def flipacoin():
    #This function flips a virtual coin and returns "Heads" or "Tails"
    coin = random.randint(1, 2) #returns a 1 or a 2
    if coin == 1:
        coin = "Heads"
    elif coin == 2:
        coin = "Tails"

def flipNcoins(n):
    #This function flips a coin a number of times (n flips total) and returns a string stating results.
    total_heads = 0
    total_tails = 0
    for i in range(n):
        if flipacoin() == "Heads":
            total_heads += 1
        else:
            total_tails += 1
    return "Heads " + str(total_heads) + ", Tails " + str(total_tails)


def rolladie():
    #This function rolls a virtual die and returns a number between 1 and 6.
    die = random.randint(0,6)
    return die

def rolltwodice():
    #This function rollstwo virtual dice and returns a tuple of the two values.
    die1 = rolladie()
    die2 = rolladie()
    return die1, die2

def rollNdice(n):
    #This function rolls n virtual dice and returns an array of roll values between 1 and 6.
    rolls = np.zeros((n,))
    for i in range(n):
        die = rolladie()
        rolls[i] = die
    return rolls

1 Answers1

1

coin = "Heads" sets a local variable coin to "Heads". It does not return it. return "Heads" would (or, equivalently, return coin at the end of the function). Any function that does not execute a return before its end is assumed to return None. None is obviously not "Heads", so you accumulate 1000 total_tails.

It should not come as a large surprise that random.randint(0,6) rolls numbers from 0 to 6, not 1 to 6. To do the latter, use random.randint(1,6) instead.

I don't understand what you mean by "The two dice result just tells us about the function".

Amadan
  • 191,408
  • 23
  • 240
  • 301