如何不止一次地运行程序的目的?

时间:2017-07-29 22:45:06

标签: python python-3.x loops

下面是我的简单骰子滚动程序的代码,程序本身很好,但我的问题是,一旦我滚动(或不要)我不能再做任何行动除了杀死程序,任何非常感谢所有的帮助。

import random

inp = input("Do you want to roll? Y/N - ").lower()

if inp=="Y".lower():

    print(random.sample(range(1,6),2))

if inp=="N".lower():

    print("Standing by")

input('Press ENTER to exit')

2 个答案:

答案 0 :(得分:3)

如果您想让程序保持运行,请在程序中添加一个循环,该循环仅在用户输入'

后终止。
import random

while True:
    inp = input("Do you want to roll? Y/N - ").lower()

    if inp == "y":
        print(random.sample(range(1,6),2))
        continue # ask again

    if inp == "n":
        print("Standing by")
        break # jump to the last line

input('Press ENTER to exit')

答案 1 :(得分:1)

与AK47一样,这也可以通过功能完成。功能的重点是重用代码

import random


def roll():
    print(random.sample(range(1, 6), 2))


while True:
    inp = input("Do you want to roll? Y/N - ").lower()
    if inp == "Y".lower():
        roll()
    elif inp == "N".lower():
        print("Standing by")
    else:
        break