Kyo Kyo - 4 months ago 7
Python Question

Python_assigning variable using Random function

I am new to python with no prior coding experience. I am using "Python Programming for the absolute beginner" by Mike Dawson to learn this language. One of the assignment is - to simulate a fortune cookie and the program should display one of the five unique fortune at random, each time it's run.

I have written the below code, but unable to successfully run the program -

# Fortune Cookie
# Demonstrates random message generation

import random


print("\t\tFortune Cookie")
print("\t\tWelcome user!")

# fortune messages
m1 = "The earth is a school learn in it."

m2 = "Be calm when confronting an emergency crisis."

m3 = "You never hesitate to tackle the most difficult problems."

m4 = "Hard words break no bones, fine words butter no parsnips."

m5 = "Make all you can, save all you can, give all you can."

message = random.randrange(m1, m5)

print("Your today's fortune " , message )

input("\n\nPress the enter key to exit")

Answer

Your error is in message = random.randrange(m1, m5). The method only takes integers as parameters. You should try putting your sentences in a list instead and test the following:

import random

print("\t\tFortune Cookie")
print("\t\tWelcome user!")

messages = [
    "The earth is a school learn in it.",
    "Be calm when confronting an emergency crisis.",
    "You never hesitate to tackle the most difficult problems.",
    "Hard words break no bones, fine words butter no parsnips.",
    "Make all you can, save all you can, give all you can."
    ]

print("Your today's fortune ", random.choice(messages))

input("\n\nPress the enter key to exit")

random.choice will take a random element from the list. You could also generate a random number and call by index, but that's not as clear:

index = random.randint(0, len(messages) - 1)
print("Your today's fortune ", messages[index])