我正在做一个会问你排名的代码。你有多个答案。 我想要做的是当用户输入答案并且答案正确时代码将继续,当答案错误时,代码将返回到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#
答案 0 :(得分:0)
在start()
函数内部,invalid_input
是本地变量,与您定义的全局invalid_input
分开。
如果您希望将invalid_input
视为start()
的全局内容,则需要告诉解释器:
def start():
global invalid_input
invalid_input = True
但是,您最好完全避免全局变量,并让您的函数返回True
或False
:
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。它通过“脱离结束”而不需要明确的返回语句来实现。