【问题标题】:Python 3 - How to randomize what text displaysPython 3 - 如何随机化显示的文本
【发布时间】:2016-09-26 22:15:23
【问题描述】:

我是 python 的初学者,我正在尝试弄清楚如何随机显示文本。例如,60% 的机会说“你好”,40% 的机会说“再见”等等。现在,为了好玩,我正在尝试创建一种翻转瓶子的游戏。如果您不知道它是什么,那基本上是您将一个半空的水瓶翻转并尝试将其降落时。这就是我所拥有的:(这很可能是完全错误的。)

import random

number = random.randrange(10)

if number == "1":
    print ("You have landed the bottle!")
elif number == "2":
    print ("You have landed the bottle!")
elif number == "3":
    print ("You have landed the bottle!")
elif number == "4":
    print ("You have landed the bottle!")
elif number == "5":
    print ("The bottle did not land, better luck next time.")
elif number == "6":
    print ("The bottle did not land, better luck next time.")
elif number == "7":
    print ("The bottle did not land, better luck next time.")
elif number == "8":
    print ("The bottle did not land, better luck next time.")
elif number == "9":
    print ("The bottle did not land, better luck next time.")
elif number == "10":
    print ("The bottle landed on the cap!")

【问题讨论】:

  • 有什么问题?
  • 提示1:使用代码格式而不是引号,请edit您的问题。提示2:问题是什么?
  • random模块
  • 您可能想知道random.randrange(10) 返回一个数字,但您正在与字符串进行比较
  • numpy.random.choice 接受带有p kwarg 的选项的权重。

标签: python python-3.x random


【解决方案1】:

基本上你的想法是对的,但是你可以大大简化你的代码。

if number < 5:
    print ("You have landed the bottle!")
elif number < 10:
    print ("The bottle did not land, better luck next time.")
else:
    print ("The bottle landed on the cap!")

您可以将调用中的值更改为randrange 和上面的 if 语句,以获得您想要的任何权重。

请注意,在您的原始问题中,您将数字与字符串进行比较。我在这里改变了它。将数字与字符串(即3 == "3")进行比较将始终为False

【讨论】:

  • 您可能应该注意到比较字符串和整数是错误的,这是一个问题:)
【解决方案2】:

您还可以使用可能的解决方案列表。

import random
possibilities=['landed'] * 3 + ['missed'] * 6 + ['landed on cap'] 
print(random.choice(possibilities))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多