【问题标题】:Print dice rolls on a single line在一行上打印骰子
【发布时间】:2022-01-17 20:05:38
【问题描述】:
import random

while True:   
    num_side = int(input("Which type of dice do You wish to roll? Select from: [4, 6, 8, 10, 12, 20, 100]: "))
    num_dice = int(input("How many dice do You wish to roll?: "))
    rolls = []
    for die in range(num_dice):
        dice_roll = random.randint(1, num_side)
        rolls.append(dice_roll)
        print ("You rolled: {}".format(rolls))

当 num_dice 输入 == 大于 1 时,输出将打印在多行上,例如,如果 num_dice == 4,输出将如下所示

You rolled: [x]

You rolled: [x,x]

You rolled: [x,x,x]

You rolled: [x,x,x,x]

我该如何解决这个问题以在一行上打印卷?

【问题讨论】:

  • 如果您不希望 print 语句在循环中,那么不要将其缩进以将其放入循环中。这是唯一的问题——缩进在 Python 中是绝对关键的。

标签: python for-loop while-loop


【解决方案1】:

print() 语句移到一个缩进上,只有在掷完所有骰子后才会显示结果。

import random    
while True:   
    num_side = int(input("Which type of dice do You wish to roll? Select from: [4, 6, 8, 10, 12, 20, 100]: "))
    num_dice = int(input("How many dice do You wish to roll?: "))
    rolls = []
    for die in range(num_dice):
        dice_roll = random.randint(1, num_side)
        rolls.append(dice_roll)
    print("You rolled: {}".format(rolls))

【讨论】:

    【解决方案2】:

    替换打印语句如下

            print ("You rolled: {}".format(rolls),end=" ")
    

    【讨论】:

      【解决方案3】:

      只是 step your print() function out of your for loop 喜欢下一个

      
      import random
      
      while True:   
          num_side = int(input("Which type of dice do You wish to roll? Select from: [4, 6, 8, 10, 12, 20, 100]: "))
          num_dice = int(input("How many dice do You wish to roll?: "))
          rolls = []
          for die in range(num_dice):
              dice_roll = random.randint(1, num_side)
              rolls.append(dice_roll)
              
          print ("You rolled: {}".format(rolls))
      
      

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 2021-02-18
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多