import random
# 6. Write a program that simulates a slot machine with three slots,
# each displaying a number between 1 and 6.
# Implement the machine in a function run_Slotmachine() that returns
# a list containing the three resulting numbers.
# Compare the numbers outside the function to determine whether
# the user has won or lost.
# a) Write the function so that each slot receives a random number.
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
result[i] = random.randint(1, 6)
return result
result = run_Slotmachine()
if result[0] == result[1] == result[2]:
print("You have won:", result)
else:
print("You have lost:", result)
# b) Extend the function so that each slot runs 100 times,
# simulated by generating a random number per iteration.
# Only the final number of each slot is retained.
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(100):
result[i] = random.randint(1, 6)
return result
result = run_Slotmachine()
if result[0] == result[1] == result[2]:
print("You have won:", result)
else:
print("You have lost:", result)
# c) Extend the function so that each slot runs a random number
# of times between 1 and 100.
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(random.randint(1, 100)):
result[i] = random.randint(1, 6)
return result
result = run_Slotmachine()
if result[0] == result[1] == result[2]:
print("You have won:", result)
else:
print("You have lost:", result)
# d) Modify the function to simulate the machine more realistically.
# Each slot contains a strip with the numbers 1 to 6.
# Move each slot forward a random number of steps between 1 and 100.
# After reaching 6, the next number is 1.
# Starting at 6, 10 steps result in 4 and 15 steps result in 3.
def run_Slotmachine():
result = [6, 6, 6]
for i in range(3):
for j in range(random.randint(1, 100)):
if result[i] == 6:
result[i] = 1
else:
result[i] = result[i] + 1
return result
result = run_Slotmachine()
if result[0] == result[1] == result[2]:
print("You have won:", result)
else:
print("You have lost:", result)
# e) Modify the program so that the user can decide at the end of each game
# whether to play again. Use the resulting numbers from the previous game as
# the initial values for the next game.
def run_Slotmachine(result):
for i in range(3):
for j in range(random.randint(1, 100)):
if result[i] == 6:
result[i] = 1
else:
result[i] = result[i] + 1
return result
result = [6, 6, 6]
play_again = True
while play_again:
result = run_Slotmachine(result)
if result[0] == result[1] == result[2]:
print("You have won:", result)
else:
print("You have lost:", result)
play_again = input("Play again? (y/n): ") == "y"