繁体   English   中英

Python 掷骰子有 2 个参数:骰子的面数和骰子的数量

[英]Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

  1. 这是我遇到的问题:编写一个 function 掷骰子,它接受 2 个参数 - 骰子的面数和要掷的骰子数量 - 并为每个掷出的骰子生成随机掷骰值。 打印出每一卷,然后返回字符串“就是这样!” 一个例子 output

     >>>roll_dice(6,3) 4 1 6 That's all!
  2. 这是我到目前为止使用普通掷骰子代码的代码:

     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之间打印一个随机数。

import random
def roll_dice(attempts,number_of_sides):
  for i in range(attempts):
     print(random.randint(1, number_of_sides))
  print("thats all")

在更高级的情况下,您可以有两个参数,您可以在其中要求用户输入设置值,它将运行函数并给出滚动的数字、总和并询问用户是否想再试一次。

#导入“随机”模块导入随机

定义主():

#Get values from user to determine slides_per_dice and number_of_die.
sides_per_die = get_value(1,50, 'How many sides should the dice to have 
(1-50): ', 'That is not a correct response, enter a value between 1 and 
50')

number_of_dice = get_value(1,10, 'How many dice should be rolled (1-10): 
', 'That is not a correct response, enter a value between 1 and 10')

#Simulate rolling specified number of dice with specified sides on each 
dice.

outcome = rolling_dice (sides_per_die, number_of_dice)

#Asking user if they would like to roll again.
roll_again = input("Would you like to play again (y/n): ") .lower()
while roll_again != 'n':
    if roll_again =='y':
        main()
    else:
        print('Error: please enter "y" or "n".')
    roll_again = input("Would you like to play again (y/n): ")

#Final message if user ends the game.
print('Thanks for playing.')

#向用户询问 side_per_dice 和 number_of_nice 输入。

def get_value(lower_limit, upper_limit, prompt, error_message): number = int(input(prompt)) while number < lower_limit or number > upper_limit: print(error_message) number = int(input(prompt)) return number

#确定卷的结果并总结所有卷的总数。

def rolling_dice (sides_per_die, number_of_die): roll_sum = 0 print('Rolling dice.....') 用于掷骰范围 (number_of_die): result = random.randint(1, side_per_die) roll_sum += result print(result, end = " ") print(f'\n所有骰子的总和是{roll_sum}')

主要的()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM