随机/循环挑战



提前感谢您的回答。所以,我刚开始学习Python,现在面临着一个令人头疼的挑战。这是一个挑战:

目标是编写一个模拟幸运饼干的程序。该程序每次运行时都应随机显示五种独特财富中的一种。

我的解决方案:

# Program simulates fortune cookie.
# Displays one of five unique fortunes at random
"""
Fortunes:
* You will meet someone that will change your life today.
* Invest in lottery this week because you will win big.
* You will get a call from someone with great influence this week.
* Purchase chinese food as you will read a fortune that will come to pass.
* Good news about an inheritance will come shortly.
"""
# Steps:
# Display a Welcome message explaining what the Fortune cookie program is  about, and how users can use it.
# Import random module to randomize the messages.
# Employ loop to repeat.
#Welcome
print("ttn<<<Welcome to Your Fortune Cookie.>>>")
print("t*To see what the Fortune Cookie Ginie has in store for you.")
print("t*Ok, here we go...n")

print(input("Press Enter to Reveal your Fortune: "))
#random module
import random
fortune1 = random.randint(1, 6)
#loop body
fortune1 < 1
while True:
print("You will meet someone that will change your life today.")
print(input(">>Press Enter again to Reveal another Fortune: "))
if fortune1 == 2:
    print("Fortune: Invest in lottery this week because you will win big.")
    print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 3:
    print("Fortune: You will get a call from someone of great influence    this week.")
    print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
    print("Fortune: Purchase chinese food as you will read a fortune that will come to pass.")
    print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
    print("Fortune: Good news! An inheritance will come shortly.")
    print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 5:
    print("Fortune: Aha! You will win something this weekend")
    print(input(">>Press Enter again to Reveal another Fortune: "))
else:
    print("Let's check again...")
fortune1 += 1
print("That's all your fortune")

虽然我想以不同的方式运行它,但程序运行了一些。我想我的问题是:有没有其他方法可以让我做到这一点?再次感谢您的回复。

另一种方法是有一个输出列表,然后用random.choice(list)从列表中随机选择一个输出。示例:

import random
fortunes = ['fortune1', 'fortune2', 'fortune3']
while True:
    input("Press enter to receive a fortune. ")
    print(random.choice(fortunes))

最新更新