python编写骰子和的程序,Python骰子模拟

I'm a bit stuck on a homework question that simulates rolling dice. The question asks to create a function that returns a random integer value from 1 to 6, and to create a main program that asks the user how many dice to roll(must be limited to 5 dice), and calls the function to print the generated values. So far I have this:

import random

def dice(number_of_dice):

for i in range(0,number_of_dice):

return random.randint(1,6)

number_of_dice = input("How many dice would you like to roll? ")

while number_of_dice >5:

number_of_dice = input("You may only have a limit of 5 dice, enter a number under 5. " )

print dice(number_of_dice)

When running the program, it only returns one random integer value no matter what the "number_of_dice" input is. What exactly is wrong here?

Any help is appreciated, thanks.

解决方案

As soon as your dice function executes and encounters the return statement for the first time, it returns without continuing the rest of the for loop.

To fix this, you can declare a local variable inside dice that holds the multiple results you want to return. Use statements like

retval = []

retval.append(...)

return retval

(I'll leave it to you to fill in the blanks.)

A more advanced use of Python involves using the yield statement to return a single value from a special kind of function called a generator, which remembers where it was and can be restarted later. However, it's worthwhile to get a firm grasp on the basics before using features like yield.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值