functions running in loops and try/except does not work

I am a beginner in Python3 and was learning the basics during the last few weeks. I decided to use my knowledge and was trying to build a text-based game based on this example.

The first 3 scenes are similar to the ones from the example but I changed the story (can be ignored) and some other small things and also added two more scenes.

Description of game: In scene 1 the character wakes up in his room and needs to decide to leave or to stay in the room. Staying in the room will end the game. Leaving the room will initiate scene 2. In scene, 2 the character needs to make the choice to talk to a rabbit or ignore it. If he picks up the rabbit and talks to it the character will get a letter with a spell + a number (2). When he ignores the rabbit he won't have that information.

In scene 3 he will be attacked by a monster. he will die when he ignored the rabbit at the prior stage. He will win and proceed based on the other decision and will get the second number (3)

In scene 4 he needs to win a dance battle. If he leaves without trying the game is over. if he wins he gets the last number (1)

In scene 5 he can type in the three numbers in the order he was collecting them. if he is successful he wins.

Description of code: I started with a class (not finished that part) that should entail all necessary variables and functions. There is also an empty list that will be filled with the numbers during the course of the story.

At the end I want to use the try and except methods to catch errors in case the input is not an integer.

Issues: Scene 1 and 4 are working. Scene 2 and 3 are running in loops. not sure why since I copied those parts from the lin above. I only applied small changes to the code. Scene 5 works fine till "Enter the second Number". It stops after submitting the input. I was changing already a few things but can't resolve my issues.

Here is the code:

class Adventure_Text_Game (): 
    
    def __init__(self): # check first part
        asdads # not ready
    
    import time

    numbers = [] # empty list that needs to be filled with numbers. those numbers will need to be entered to open the lock to rescue the parents

    # numbers that can be collected  in story
    num1 = 2
    num2 = 3
    num3 = 1

#works fine
    def scene1(self):
        print("""\nWELCOME TO THE ADVENTURE GAME!

                        Michael had a bad night and woke up in the middle of the night in his 
                        bedroom disturbed by an odd noise outside of the house.
                        Should he stay stay in his room or take a look? 

                        Type your choice: Stay or Take a look?""")
        sc1 = input()
        time.sleep(2)
        while sc1 != "STAY" and sc1 != "TAKE A LOOK": #the conditon that keeps the loop running ans=='incorrect'
            if sc1.upper()=="STAY":
                print("\nMichael is a coward and is not leaving his room...Game Over")
                break
            elif sc1.upper()=="TAKE A LOOK":
                print("\nMichael takes all his courage and exits the room silently directly going to the garden where the noise came from.")
                scene2()
            else:
                print("ENTER THE CORRECT CHOICE! Stay or Take a Look?")
                sc1 = input()

#caught in loop...why?
    def scene2():
        print("""
                Outside he finds a cute white little rabbit that has never been there before and also seems to be a little nervous. The neighbors also don't posess a rabit 
                Should Michael pick up the rabbit or ignore him? 

                Type your choice: Pick or Ignore?

                """)
        time.sleep(2)
        sc1 = input()
        while sc1 != "PICK" and sc1 != "IGNORE":
            if sc1.upper()=="PICK":
                print("""\nMichael but Michael sees a little tag that says "My name is Roger". Michael starts talking to the rabit and pets him to calm him down. Suddenly the rabbit starts talking and is telling Michael his parents are in danger captured by a monster only he knows how to defeat.""")
                time.sleep(2)
                print("The rabbit gave Michael a letter with a magical spell and a wooden wand which will help him to defeat the monster. Michael also sees the number", str(num1),  "at the bottom of the page! The rabbit then hops away and disappeaed in the darkness. There was nothing else in the garden so he decided to walk towards the street.")
                pick="True"
                numbers.append(num1)
                print (numbers)
            elif sc1.upper()=='IGNORE':
                print("""\nMichael decided not to pick up the rabbit. There was nothing else in the garden so he decided to walk towards the street.""")
                pick="False"
            else:
                print("ENTER THE CORRECT CHOICE! Stay or Evaluate?")
                sc1 = input()
        scene3(pick)


                
#caught in loop....why? 
    def scene3(pick):
        print("""\n\nWhen arriving at the pedestrian way of his street, Michael saw the MONSTER in front of him!
        It had red eyes and evil looks. He got very scared! """)
        time.sleep(2)
        if(pick=="True"):
            time.sleep(2)
            print("""But then he remembered! He had that letter and that wand from the rabbit. 

                  Well she had nothing to lose!""")
            time.sleep(2)
            print("\nHe starts reading the spell while holding the wand. The wand created a bright light followed by an explosion which vaporized the monster. On the ground Michael saw only a heap of ashes in the form of another number - the number", str(num2))
            numbers.append(num2)
            print (numbers)
        elif(pick=="False"):
            print("The monster attacked Michael and hurt him badly....Game over!")
            time.sleep(2)
        scene4()


#works fine
    def scene4():
        print ("""\nMichael now sees a little light coming from a house across the street. So many strange things already happened which is why he approcahed the house carefully.
                He arrived at the window and saw a dancing Leprachaun.""")
        time.sleep(2)
        print ("""\nThe Leprachaun was expecting Michael already and insisted to have a step dance battle in order to get passed him.""")
        time.sleep(2)

        print ("""Type your choice: Dance or Leave?""")

        sc1 = input()
        time.sleep(2)
        while sc1 != "DANCE" and sc1 != "LEAVE":
            if sc1.upper()=="LEAVE":
                print("\nYou didn't rescue your parents...Game Over")
                break
            elif sc1.upper()=="DANCE":
                print ("""\nAfter all what happended that night he didn't really question it and started moving his feet although had no clue how to dance at all
                            But to his and the Leprachaun's surprise he danced like he was born stepdancer. His legs were basically flying. 
                            The Leprachaun couldn't believe what he saw and could only forfeit.""")
                time.sleep(2)
                print ("Before the Leprachaun disappeared he gave Michael another number - number", str(num3))
                numbers.append(num3)
                scene5()
            else:
                print("ENTER THE CORRECT CHOICE! Dance or Leave?")
                sc1 = input()


#need to check exception
    def scene5():
        print ("""\nMichael is now able to get passed the Leprachaun and is now standing in front of a door that is locked.
                    Next to the door he finds a keypad. He figures that he needs to type in the three digits he was collecting earlier.""")
        sc1 = input("Enter the first number")
        sc1 = int(sc1)
        try: 
            if sc1 == numbers [0]:
                print ("This number is correct!")
                sc1 = input("Enter the second number")
                if sc1 == numbers [1]:
                    print ("This number is correct!")
                    sc1 = input("Enter the third number")
                    if sc1 == numbers [2]:
                        print ("Congratulations! You can open the door and rescue your parents! ")
        except (ValueError, TypeError): #type error in case number is not an integer
            print("Please enter a proper number")
        
                

Also a visualization of the flow

1 answer

  • answered 2022-05-07 02:54 Ethan _kom

    For scene two you should have:

    while sc1 != "PICK" and sc1 != "IGNORE":
          print("ENTER THE CORRECT CHOICE! Pick or Ignore?")
          sc1 = input()
    

    If it breaks out of the loop then we know that the user entered a valid input and the program can proceed to the if and elif block. The way you have it if the correct input is inserted while in the while loop then the if and elif statements will never execute. I'm also seeing that you reference the number list in the methods and append to it. You should have this variable initialized to 'self.numbers'. The methods can't distinguish one number array from another and it's better to have a global list object for your class. This may be what's causing some problems. It might be a better idea to initialize a string with digits in the init method. self.numbers = '231'. Then you can index a number out if you either want to print it or compare it to inputs.

    I don't know why your scene 3 is looping but I noticed that after the elif statment executes it still moves on to the next scene. According to your flow chart the game should end here. I recommend checking the if and elif blocks of your scenes. Whenever the game should end use return.

    EDIT: I'll show some example code for clarification:

        def __init__(self): # check first part
    
             self.nums = '231' 
             self.numbers = []
    
        def scene2(self):
        print("""
                Outside he finds a cute white little rabbit that has never been there before and also seems to be a little nervous. The neighbors also don't posess a rabit 
                Should Michael pick up the rabbit or ignore him? 
    
                Type your choice: Pick or Ignore?
    
                """)
        time.sleep(2)
        sc1 = input().upper()
        while sc1 != "PICK" and sc1 != "IGNORE":
            print("ENTER THE CORRECT CHOICE! Pick or Ignore?")
            sc1 = input().upper()
    
         if sc1.upper()=="PICK":
                print("Michael but Michael sees a little tag that says \"My name is Roger\". Michael starts talking to the rabit and pets him to calm him down. Suddenly the rabbit starts talking and is telling Michael his parents are in danger captured by a monster only he knows how to defeat.\n")
                time.sleep(2)
                print("The rabbit gave Michael a letter with a magical spell and a wooden wand which will help him to defeat the monster. Michael also sees the number", str(self.nums[0]),  "at the bottom of the page!The rabbit then hops away and disappeaed in the darkness. There was nothing else in the garden so he decided to walk towards the street.\n")
                pick= True
                self.numbers.append(self.nums[0])
                print(self.numbers)
        
        else:
            print("""\nMichael decided not to pick up the rabbit. There was nothing else in the garden so he decided to walk towards the street.""")
            pick= False
            
        #self.scene3(pick)
    

    Added the upper method to circumvent the input problem you have. You should also add new lines at the end of your print statements. I noticed that there were a few syntax errors as well, I recommend that you use a code editor so that it'll catch those for you.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum