【问题标题】:How to determine "event" output to print on the outcome of a random dice roll?如何确定“事件”输出以打印在随机掷骰子的结果上?
【发布时间】:2019-06-14 07:32:50
【问题描述】:

我正在尝试根据掷出的骰子来打印某些字符串。

我已经尝试列出哪些滚动得到哪些事件,但即使那样,也没有任何事件仅打印出我滚动的内容。

    import random

    def dice_roll():


      d20_roll = random.randint(1,20)
      print("You rolled " +str(d20_roll))

      def dice_choice():
            event = str(d20_roll)

            bad_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 
            '11', '12']

            good_list = ['13', '14', '15', '16', '17', '18']

            gag_list = ['19', '20']

            if event == bad_list:
               print('bad_list stuff')

            elif event == good_list:
                 print('good_list stuff')

            else:
                 if event == print gag_list:
                    print("gag_list stuff")

        dice_choice()
    dice_roll()

我希望输出是随机滚动将产生的三个选项中的任何一个。 我收到的只是 dice_roll 本身的结果,没有选择。

【问题讨论】:

    标签: python-3.x if-statement


    【解决方案1】:

    首先,检查您的缩进,您对dice_choice() 的调用似乎在dice_choice() 本身内部,其次,您的测试if event == print gag_list: 存在语法错误,第三,您正在测试字符串是否等于列表,相反,您应该测试字符串是否在列表中,您的代码应该是这样的:

    import random
    
    def dice_roll():
        d20_roll = random.randint(1,20)
        print("You rolled " +str(d20_roll))
    
        def dice_choice():
            event = str(d20_roll)
    
            bad_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
            good_list = ['13', '14', '15', '16', '17', '18']
            gag_list = ['19', '20']
    
            if event in bad_list:  #  check using `in` not `===`
                print('bad_list stuff')
            elif event in good_list:
                print('good_list stuff')
            elif event == gag_list:
                print("gag_list stuff")
    
        dice_choice()
    
    dice_roll()
    

    示例输出:

    You rolled 11
    bad_list stuff
    

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2014-10-07
      • 1970-01-01
      • 2017-11-06
      • 2015-05-10
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多