Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of declaring/using/calling functions, and passing data to and from them. Written as a reference for students in one of my classes.
#!/usr/bin/python3.1
#
import random
# single_roll: A function which rolls a single 6 sided die, and returns
# the result back to the calling function
def single_roll():
# returns a random value between 1 and 6
return random.randint(1,6)
# roll_dice: A function which rolls a given number of 6 sided die,
# and returns the result back to the calling
# function (main in this case).
def roll_dice(number_of_dice):
# Loop for a given number of dice.
#
# First initialize some of the variables we will need.
i = 0
roll_sum = 0
while i < number_of_dice:
# increment i
i += 1
# Call our helper function `single_roll()` that rolls a single
# dice for us. It takes no input arguments (since we defined it
# as having none.
new_roll = single_roll()
# Print out the result of the single roll.
print("Die roll number %d: %d" % (i, new_roll))
# Update the running total of the sum of all the rolls
# so far.
roll_sum += new_roll
# return the sum of all the rolls back to main
return roll_sum
def main():
# randomize the seed
random.seed()
# Get user input: How many dice do you want to roll?
number = input("How many dice do you want to roll? ").strip()
print() # an empty print for formatting purposes
# input() returns a string, so we need to convert to an integer
try:
number = int(number)
except:
# couldn't convert number to an integer
print("Couldn't convert `%s` to an integer. Exiting..." % number)
return
# Call the function, and receive back the return value
# into a variable called `my_sum`
my_sum = roll_dice(number)
# Print the result
print() # an empty line
print("The sum of all the dice rolls is: %d" % my_sum)
# End of function
# We've defined our functions above (including main() ), but
# we have to call them to use them. So call main() here.
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment