无法弄清楚如何使代码“重新启动”



我知道"goto Start"这一行是错误的,只是把它放在那里,这就是我希望代码循环回代码开头但根本无法弄清楚如何做的地方。请帮忙....

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?"))
print("You are rolling " + str(dint) + " dice")
import os
answer=0
import random
y=0
while( y < dint ):
    out = random.randint(1, int(dsides))
    print(str(out))
    y=y+1

while (True):
    answer = raw_input('Run again? (y/n): ')
    if(answer in ("y", "n")):
        if(answer == "y" ):
            goto start
        else:
            print("GoodBye")
            break
    else:
        print ("Invalid input.")
        break

代码包装在一个函数中并调用该函数:

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

最新更新