Python Forum

Full Version: Why is this code not working?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been sitting in front of my PC for 5 hours straight now trying to solve this, but it just comes to the question and if i answer yes it breaks the loop as wanted, but if I type in no it crashes. Any help is appreciated, thank you, -Ivan
def clss():
    import os
    os.system('cls' if os.name == 'nt' else 'clear')
def pause():
    raw_input("Press Enter to continue")
print ("No Life Ent.")
pause()
clss()
print ("The No Life inc. Quiz")
pause()
clss()
print ("Begin game?")
a1 = raw_input("Type in yes or no: ")
while a1 !="yes":
    if a1 == yes:
        print ("Ok, let us begin then")
        break
    else:
        print("Type in yes.")
        continue
pause()
print("THANK THE LORD THIS WORKS!")
pause()
I've got Python 2.7.13 if that is of any help.
Hello!
Perhaps there are cases when importing a module inside a function is reasonable but I think this in not one.

Well, if you answer 'no', the loop will never stop. You don't change the value of a1 anywhere inside the loop so its condition will return True every time.
In the future, please elaborate on your promlem.
If I tell you my car is not working, can you fix it?
You can set while True and a1 == 'yes'(string) else will be 'no',and break out on both.
But you soon get into trouble with this design.
Keeping all in functions make it easier to to jump around like playing a game and back to menu.
Eg:
from six.moves import input
import time

def my_game():
   print('Game running')
   for i in reversed(range(5)):
       time.sleep(1)
       print('Playing {}'.format(i))
   input('Push enter to retun to menu')

def menu():
   while True:
       print('(1) Play game')
       print('(Q) Quit')
       choice = input('Enter your choice: ').lower()
       if choice == '1':
           my_game()
       elif choice == 'q':
           return False
       else:
           print('Not a correct choice: {}'.format(choice))

if __name__ == '__main__':
   menu()
So here always fall back into menu,from here can Quit game or play new game.
You can build on game/menu function over jump over to other function,
can always fall back to menu where there is a way out(Quit).

With function you can build quite complex structure and your code don't get messy.
Using class is and other way to structure code,not needed for small games for larger games it can be useful Undecided