#!/usr/bin/env python # coding: utf-8 # In[8]: # Section 5.7 -- value-returning functions # idea: A value-returning function...."returns" a value when called # # Importing modules (or "packages") # we've done this before: we've written # import turtle # import time # # We're gonna look at the random module now # # import it: import random # Think about modules in this way: # a module gives you a "black box" of functions # meaning that you don't know "how" they work, but you # can have some confidence that they "do" work # # You usually never know 100% how a function in a module works # but if it functions fine, then don't worry about it! # # # Examples of functions in the random module # # display random number between 1 and 10 (inclusive) def main(): number=random.randint(1,10) print("The random number is",number) main() main() main() main() main() main() main() main() main() main() main() main() # In[10]: # Die rolling program # Randomly generate two numbers between 1 and 6 and display them # Ask user if they want to roll again. # # magic numbers MIN=1 MAX=6 def main(): # loop control variables go_again='y' while go_again=='y': print("Rolling the dice...") print("First die roll is",random.randint(MIN,MAX)) print("Second die roll is",random.randint(MIN,MAX)) go_again=input("Input y to roll again") main() # In[364]: # Other functions in the random module # randrange -- behaves similar to range in that the upper value # is never attained # # easiest example import random print(random.randrange(7)) # <-- random int in {0,1,2,3,4,5,6} print(random.randrange(1,5)) # <-- random int in {1,2,3,4} print(random.randrange(15,30)) #<-- random int in {15,16,...,29} print(random.randrange(0,10,2)) # <-- random int in {0,2,4,6,...,8} print(random.randrange(3,15,4)) # <-- random int in {3,7,11} # # Above functions always give integer outputs # What about floats? # # Random number in the interval [0,1) -- 0 <= x < 1 # I would use print(random.random()) # If instead, I want a random number in [A,B) -- A<=x