写一个简单的PYTHON程序,模拟摇一个色子

来源:百度知道 编辑:UC知道 时间:2024/06/21 23:54:43
Write a program that simulates rolling a die. Your program
should contain at least two functions.
– You should first ask the user how many times he would like to
roll the die. Make sure that the user enters a number. ( You will need to modify this function so that it returns an int instead of a float.)
– Your program should next print out the value of each roll of the die.
– Sample output of the program:

How many times would you like to roll the die? 4
3114
How many times would you like to roll the die? 4
3
1
1
4
该是这样显示的

import random

def roll_die_once(min = 1, max = 6):
    """Roll the die once, with min and max given."""
    return random.randrange(min, max+1)

def main():
    """Accept user input as times, then roll the die repeatedly for times given."""
    times = raw_input("How many times would you like to roll the die? ")
    try:
        times = int(times)
    except:
        raise ValueError, "Your times[%(times)s] cannot be an int" % locals()

    for i in range(times):
        print roll_die_once()

main()