簡體   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