繁体   English   中英

使用Random函数的Python_assigning变量

[英]Python_assigning variable using Random function

我是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")

您的错误在于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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM