带有 2 个参数的 Python 掷骰子:骰子的边数和骰子的数量 [英] Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

查看:55
本文介绍了带有 2 个参数的 Python 掷骰子:骰子的边数和骰子的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 这就是我遇到的问题:编写一个函数 roll dice,它接受 2 个参数 - 骰子的边数和骰子的数量滚动 - 并为每个掷骰子生成随机滚动值.打印出每卷,然后返回字符串就这样!"示例输出

  1. This is the problem I have: Write a function roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice to roll - and generates random roll values for each die rolled. Print out each roll and then return the string "That’s all!" An example output

   >>>roll_dice(6,3)
   4
   1
   6 
   That's all!

  • 这是我目前使用普通掷骰子代码的代码:

  • This is the code I have so far using a normal roll dice code:

                      import random
    
                      min = 1
                      max = 6
    
                      roll_dice = "yes"
                      while roll_dice == "yes":
                          print random.randint(min,max)
                          print random.randint(min,max)
                          print "That's all"
    
                          import sys
                          sys.exit(0)
    

  • 推荐答案

    试试这个:

    def roll_dice(sides, rolls):
        for _ in range(rolls):
            print random.randint(1, sides)
        print 'That\s all'
    

    这使用 for 循环 来循环 rolls 数量的次并在每个循环的 1 和 sides 之间打印一个随机数.

    This uses a for loop to loop rolls amount of times and prints a random number between 1 and sides each loop.

    这篇关于带有 2 个参数的 Python 掷骰子:骰子的边数和骰子的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆