1

I just started my first programming class a few weeks ago and I'm embarrassed to say I'm very stuck. We had to create a program that (in my Professor's words):

Simulate the roll of two dice. Use a randomly generated integer to represent the roll of each die in a function named point. Return the combined value of a roll. Use a loop in main to roll the dice five times and report each result.

So, I did my best and keep getting the same issue where it is telling me my variable total is not defined, even though I'm calling the function which contains the variable.

I submitted the below code to my professor, who in turn responded:

The dice program is close. Return the total of a roll. Call point in main and capture the returned value for printing.

So he is saying to call the function point in my main function (which, at least I think, I am) but it still won't read my vital variable to finishing this.

import random

min=1
max=6



def main():
  for roll in range(5):
    point()
    print(total)


def point():

  roll=random.randint(min, max)
  roll2=random.randint(min, max)
  total=roll+roll2
  return total

main()

2 Answers 2

1

Inside the main function, this line:

point()

does not make total available in the current scope. Instead, it simply calls the function point and then discards its return value.

You need to capture this return value by assigning it to a variable named total:

def main():
  for roll in range(5):
    ################
    total = point()
    ################
    print(total)

Now, when you do print(total), total will be defined and equal to the value of point().

Sign up to request clarification or add additional context in comments.

1 Comment

Grrr I knew it'd be something simple! Thank you so much!! The explanation was perfect as well =D
1

You're trying to reference a variable that only exists within the scope of the point() function. But you don't need to since you return the value anyway.

Try this.

from random import randint
def rollD6():
    return randint(1,6)

def point():
    return rollD6()+rollD6()

def main():
    for roll in range(5):
        print point()

main()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.