使用随机函数的Python_assigning变量

时间:2016-08-01 23:11:34

标签: python

我是python的新手,没有先前的编码经验。我正在使用Mike Dawson的“Python编程为绝对的初学者”来学习这门语言。其中一个任务是 - 模拟一个幸运饼干,程序应该随机显示五个独特的财富之一,每次运行。

我编写了以下代码,但无法成功运行程序 -

# 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")

1 个答案:

答案 0 :(得分:0)

您的错误在message = random.randrange(m1, m5)。该方法仅将整数作为参数。您应该尝试将句子放在列表中并测试以下内容:

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会从列表中获取一个随机元素。你也可以生成一个随机数并按索引调用,但这不是很清楚:

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