Search code examples
pythonpython-3.xwhile-loop

My while True: loop is not continuing to loop like the first set of code


Hey guys python beginner here, I'm working on a little adventure game and I can't figure out how to work my loops. My first one is in a while True: loop and continues to loop the code when the user input is anything else. But when same loop repeated on lines 20-34 the loop doesn't seem to work anymore, the script just ends.

``

Adventure project

import time

while True:
    print('A man approachs you with his sword drawn and an angry look spread across his face, what do     you do?')
    print('1. Run away')
    print('2. Punch the man')
    fightOrRun = input()

    if fightOrRun in {'2','2.'}:
        print('Man: "Your going to get it!"')
        break
     elif fightOrRun in {'1','1.'}:
         print('Man: "Where do you think your going!"')
         break
     else:
         print('Not a valid input!') 
         continue

 while True:   
     if fightOrRun in {'2','2.'}:
         print('1. Adios loser!')
        fightOrRun = input()
        break

    elif fightOrRun in {'1','1.'}:
        print('1. I dont know')
        print('2. Im sorry')
        fightOrRun = input()
        break

    else:
        print('Please enter a valid input!')
        continue
``

I've tried adding the second half to the first while True: loop but it just results in the error on the second half being "Code is unreachable pylance"


Solution

  • The reason the second half of your code is unreachable is because in your first conditional, all of the options result in either a break or continue. This will mean that all the code after it is inaccessible.

    I suspect that removing the break statements would get you your desired outcome.

    You can read more about it in the python docs on Control Flow