I'm doing a code that will ask you a rank. you have multiple answers. what i'm trying to do is when the user puts in an answer and the answer was correct then the code will carry on, and when the answer is wrong then the code will go back to the start of the if statement.
what my code does at the moment is that it will go to the top of the statement no matter what. I want it so that the code will skip when the answer is right.
here is my code!
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#
You can remove a lot of code duplication:
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')
The idea here is to make a function which returns the special value None if the input is no good. It does this by "falling off the end" with no explicit return statement needed.