当用户输入正确时,我如何跳过if语句?

时间:2014-05-27 12:16:29

标签: python if-statement input skip

我正在做一个会问你排名的代码。你有多个答案。 我想要做的是当用户输入答案并且答案正确时代码将继续,当答案错误时,代码将返回到if语句的开头。

我的代码目前所做的是,无论如何,它都将在声明的顶部。 我想要它,以便在答案正确时代码将跳过。

这是我的代码!

print ('what rank do you want')
print ('light')
print ('heavy')
print ('soldier')
print ('ninja')
print('if you want to pick a rank again than type "retake"')#ignore this line#


print ('light')
print ('heavy')
print ('soldier')
print ('ninja')

invalid_input = True
def start() :
    invalid_input = True
    rank = input('pleese pick a rank!\n')

    if rank == ('light'):               
        print ("you have chosen light")
        invalid_input = False           


    elif rank == 'heavy':
        print ('you have chosen heavy')
        invalid_input = False


    elif rank == ('soldier'):
        print ('you have chosen soldier')
        invalid_input = False


    elif rank == ('ninja'):
        print ('you have chosen ninja')
        invalid_input = False


    else:
        print ('Sorry, that was an invalid command!')


while invalid_input :
    start()

print ('well done you have picked your rank') #the bit where the code will carry on#

2 个答案:

答案 0 :(得分:0)

start()函数内部,invalid_input本地变量,与您定义的全局invalid_input分开。

如果您希望将invalid_input视为start()的全局内容,则需要告诉解释器:

def start():
    global invalid_input
    invalid_input = True

但是,您最好完全避免全局变量,并让您的函数返回TrueFalse

def start() :
    rank = input('please pick a rank!\n')

    if rank in ('light', 'heavy', 'soldier', 'ninja'):
        print('You have chosen {}'.format(rank))
        return False

    else:
        print('Sorry, that was an invalid command!')
        return True

invalid_input = True
while invalid_input:
    invalid_input = start()
如果有有效的输入,只需使用无限循环和break

while True:
    if not start():
        break

我会亲自返回True来获取有效的输入。

答案 1 :(得分:0)

您可以删除大量代码重复:

ranks = ['light', 'heavy', 'soldier', 'ninja']

print('what rank do you want')
for rank in ranks:
    print(rank)

def getRank():
    rank = input('please pick a rank!\n')
    if rank in ranks:           
        print("you have chosen", rank)
        return rank

rank = getRank()
while rank is None:
    print('Sorry, that was an invalid command!')
    rank = getRank()

print('well done you have picked your rank')

这里的想法是创建一个函数,如果输入不好,则返回特殊值None。它通过“脱离结束”而不需要明确的返回语句来实现。