首页 > 解决方案 > Python掷骰子游戏卡在代码上,如果满足某些用户输入,想要循环重新启动

问题描述

所以我对整个编码场景还很陌生,我正在做一些初学者项目来建立我所学到的东西。

找不到任何直接帮助我的信息,所以我想我会问,任何信息都会有帮助,谢谢!

import random

useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
    lets_play = input('Do you wish to roll? Yes or no: ')
    if lets_play.lower() == 'yes':
        d1 = random.randint(1, 6)
        d2 = random.randint(1, 6)
        ask = input('Do you wish to roll again? ')
        if ask.lower() == 'yes':
            # How do I return to give the user another chance?
        elif ask.lower() == 'no':
            print('Alright, later!')
            break

    elif lets_play.lower() == 'no':
        print('Alright, later!')
        break
    else:
        print('Not any of the options, try again...')
        # how do I return to the top to give the user another chance?

原代码为图片

标签: python

解决方案


你已经提出了几个问题,但我会尝试用一个例子来回答它们。首先,要无限运行 while 循环,您可以将其设置为(与您的语句True基本相同,只是更简单)。1=1

您关于函数的第二个问题通常是肯定的 - 如果某些代码需要重复多次,通常最好将其提取到函数中。

关于跳过一行代码的第三个问题 - 最简单的方法是 if/else 语句,就像你已经做过的那样。可以改进的一件事是使用continue; 它从头开始重新启动循环,而break跳出循环。

这是您的场景的简单代码示例:

import random

def roll():
    print('First roll:', random.randint(1, 6))
    print('Second roll:', random.randint(1, 6))

play = input('Do you wish to roll? Yes or no: \n')

while True:
    if play.lower() == 'yes':
        roll()
        play = input('Do you wish to roll again? \n')
    elif play.lower() == 'no':
        print('Alright, later!')
        break
    else:
        play = input('Not any of the options, try again... Yes or no: \n')

推荐阅读