【问题标题】:using random module to randomly pick from a list and execute something使用随机模块从列表中随机选择并执行某事
【发布时间】:2014-11-17 19:43:58
【问题描述】:

我试图让程序从列表中随机打印一个项目,然后程序要求用户在存在真/假条件的地方输入一些信息,然后将用户返回到他们可以开始的地方选择一个新的“轨道”

我遇到的问题是,由于所有帮助,只选择了“listone”,而不是随机列表选择。

import random
questlist = ['questone', 'questtwo', 'questthree']
random.choice(questlist)


def start():
    print('Hi, welcome to the race track')
    pick = input('pick a track')
    displaytrack()


def displaytrack():
    tracks = ('track 1', 'track 2', 'track 3')
    print(tracks)



if 'questone':
    ans = input('how old are u')
    if ans == 3:
        print('Correct')
        print('Thanks for using')
        start()
    else:
            print('Incorrect')
            start()


if 'questtwo':
    ans = input('How nice are u')
    if ans == 'very':
        print('Correcterino')
        print('Thanks for using')
        start()
    else:
            print('Wrongerino')
            start()

if 'questthree':
    ans = input('How tall are u')
    if ans == 'pretty':
        print('sixfoot')
        print('Thanks for using')
        start()
    else:
            print('no feet')
            start()

【问题讨论】:

    标签: python random


    【解决方案1】:

    您需要存储选择的输出并在条件表达式中使用它:

    choice = random.choice(questlist)
    

    替换

    if 'questone':
    

    if choice == 'questone':
    

    以此类推,否则if 表达式只是检查字符串'questone' 是否为None,它的计算结果总是True

    【讨论】:

      【解决方案2】:

      用这个代替你当前的第三行

      PC_Choice = random.choice(questlist)
      

      然后使用:如果 PC_Choice == questone

      像这样:

      if PC_Choice == 'questone':
          ans = input('how old are u')
          if ans == 3:
          print('Correct')
          print('Thanks for using')
          start()
      else:
              print('Incorrect')
              start()
      

      然后改变另外两个,这将使它给出一个随机选择

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多