随机/循环挑战

时间:2016-05-03 01:16:37

标签: python-3.x

提前感谢您的回答。所以,我刚刚开始学习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("\t\t\n<<<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")
  
    
      

虽然我想以不同的方式运行它,但程序却跑了。我想我的问题是:还有另外一种方法可以做到这一点吗?再次感谢您的回复。

    
  

1 个答案:

答案 0 :(得分:2)

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

import random

fortunes = ['fortune1', 'fortune2', 'fortune3']

while True:
    input("Press enter to receive a fortune. ")
    print(random.choice(fortunes))