无法弄清楚如何制作代码并重新启动'

时间:2016-02-02 17:13:32

标签: python-3.x

我知道该行"转到开始"只是把它放在那里是错误的,我希望代码循环回到代码的开头但却无法弄清楚如何去做。请帮帮....

BEGIN

1 个答案:

答案 0 :(得分:1)

将代码包装在函数中并调用函数:

def my_function(output=''):  # <-- change 1

    dsides = int(input("how many sides do your dice have?"))
    print("Your dice has " + str(dsides) +" sides")
    dint = int(input("How many dice do you want to roll?"))
    import random
    y = 0
    while y < dint:
        out = random.randint(1, int(dsides))
        output += "{} ".format(out)   # <-- change 2
        # print(str(output))   # <-- change 3
        y=y+1

    while True:
        answer = raw_input('Run again? (y/n): ')
        if answer in ("y", "n"):
            if answer == "y":
                my_function(output)  # <-- recursive call
            else:
                print(output)   # <-- change 4
                print("GoodBye")
                return
        else:
            print ("Invalid input.")
            break

示例输出:

how many sides do your dice have?6
Your dice has 6 sides
How many dice do you want to roll?6
Run again? (y/n): n
2 1 3 4 6 5 
GoodBye