如何多次运行程序的目的?

2024-04-19 18:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

Tags: tosample代码import程序youinputif
2条回答

像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

如果要保持程序运行,请向程序添加一个循环,该循环仅在用户输入“n”时终止

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')

相关问题 更多 >