U3 S14-15
Reflection
When the process is too long to view, use the documentation to explain what the process does
Randomization is everywhere in our lives
RANDOM(a, b) generates and returns a random integer from a to b
The random library must be imported to use it's function
random.choice can pick a random element from a list
random.shuffle can rearrange the elements of a list at random
You can use the ladder function in randrange and not include the maximum value
randint(start,stop) claims a random number from a range, randrange(start,stop,step)
generates a random number in a range by setting increments
Multiple Choice
What does the random(a,b) function generate?
A. A random integer from a to be exclusive
==B. A random integer from a to b inclusive.==
C. A random word from variable a to variable b exclusive.
D. A random word from variable a to variable b inclusive.
What is x, y, and z in random.randrange(x, y, z)?
==A. x = start, y = stop, z = step==
B. x = start, y = step, z = stop
C. x = stop, y = start, z = step
D. x = step, y = start, z = stop
Which of the following is NOT part of the random library?
==A. random.item==
B. random.random
C. random.shuffle
D. random.randint
- Write a thorough documentation of the following code.
import random
names_string = input("Give me everybody's names, seperated by a comma.")
names = names_string.split(",")
num_items = len(names)
random_choice = random.randint(0, num_items - 1)
person_who_will_pay = names[random_choice]
print(f"{person_who_will_pay} is going to buy the meal today!")
Documentation: First import the random library to use the code inside the library, these codes allow us to eliminate the need to define complex code to use, and then import the user to use the names in the library, the names are separated by splits using commas, each name will be by the corresponding index, then use random.randint to randomly select an index and output the names.
import random # import random library
nameList = ["Eric","Lily","Jack","Kerry","RJ","John","Ashley","Tony","Scott","Tim","Petter","Amy","Potter","Alle","Golf"] # create a nameList to be used
# Print 5 random names from nameList
i = 1
while i <= 5:
randomNames = random.choice(nameList) # use random function from random library
print(randomNames)
i += 1
- Create a program to simulate a dice game where each player rolls two fair dice (6 sides); the player with the greater sum wins
import random
def rollDice(): # define how to roll dices
firstRoll = random.randint(1,6)
secondRoll = random.randint(1,6)
score = firstRoll + secondRoll
return score
# print their scores
playerAscore = rollDice()
print("PlayerA got",playerAscore)
playerBscore = rollDice()
print("PlayerB got",playerBscore)
# compare scoreA with scoreB
if playerAscore > playerBscore:
print("playerA wins")
if playerAscore < playerBscore:
print("playerB wins")
if playerAscore == playerBscore:
print("Both them tied with",playerAscore)