修改while循环骰子滚动程序,使其同时滚动两个骰子,并打印两个骰子值

qpgpyjmq  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(293)

在此处输入图像描述

"""strong text
Generate random numbers for the user

模拟掷骰子,直到用户想要退出为止。使用f字符串也称为格式字符串“”
导入强文本

want_to_quit = ''

while not want_to_quit:
dice_value = random.randint(1, 6)
print(f'You rolled a {dice_value}')
want_to_quit = input('Press enter to roll again, any other key to quit ')
gcuhipw9

gcuhipw91#

在你的问题中有很多东西需要考虑:
1-如果只想运行两次,为什么需要循环?您可以在不预先循环的情况下直接生成两个滚动结果,然后可以选择显示或不显示。

import random

dice_value_0 = random.randint(1,6)
dice_value_1 = random.randint(1,6)

# Here you can choose how many to show out of them:

print(f'You rolled a {dice_value_0}')

# You can untag the next line if you need a second value:

# print(f'You rolled a {dice_value_1}')

2-尽管如此,我怀疑您需要根据需要创建两个以上的价值观。为此,最好创建一个可以掷骰子一次的函数,并且可以在每次需要时调用它。请注意,行开头的缩进(制表符)很重要。

import random

def roll_dice():
    return random.randint(1,6)

# Now you can roll dices all you want:

x=roll_dice()
print(f'You rolled a {roll_dice()}') # Roll #1
print(f'You rolled a {roll_dice()}') # Roll #2

3-你也可以一次滚动所有骰子,将它们存储在数组中并作为函数返回,然后使用它们的索引选择要显示的内容。

import random

def roll_dices(count=1):
    dices = [] # empty array, no dices were roll yet.
    for dice_number in range(1,count):
        dices.append(random.randint(1,6))
    print(f'The dices that you have rolled are {dices}')
    return dices

# Now you show all dices by index (dice_number)

dices = roll_dices(4) # Say we want 4 rolls
for dice in dices:
    print(f'You rolled a {dice}')
print(f'So the dice at index #{1} was {dices[1]}. That was #{2} in order.')

相关问题