Python Game Terminates during IF statement

Hi FCC! I am a VERY new Python programmer. The code below quits after I imput 1 or 2 during the prompt under the “first_shot” function. For some reason, the code after first_shot, including second_shot and the “Game Over” text.

The error in my IDE says NameError: shot1 not defined

import random

import time

score = 0

def print_pause(message):

    print(message)

    time.sleep(2)

def intro():

    print_pause("Welcome to Brittany's Putt-Putt world!")

    print_pause("The Putt-Putt adventure of a lifetime awaits you.")

    print_pause("You are on Hole #1, a Par 3.")

    print_pause("""You see a narrow bridge that goes over the river, or a wide fairway that goes around.""")

def first_shot():

    print_pause(""""Would you like to try to go over the bridge, or take the wide fairway?""")

    shot1 = input("Press 1 for the Bridge Press 2 for the Fairway  ")

#can't figure out why this will not print.  After 1 or 2 is input, the program closes. 

def second_shot():

    if shot1 == "1":

        print_pause("You got over the bridge!")

    print_pause("You made it into the fairway!")

def play_game():

    intro()

    first_shot()

    second_shot()

    print_pause("Game Over! See you next time.")

play_game()

shot1 is defined in the scope of first_shot function. It cannot be accessed like that from the outside of this function. This could work if second_shot function would be defined within first_shot function or if shot1 variable would be made a global variable.

Generally usually it’s better to explicitly return values needed by other functions and then pass them into those functions also explicitly. What this means - return shot1 from the first_shot function and then pass it into the second_shot function. This would require small changes to functions involved and in the play_game function.

Thank you! That worked. I ended up moving the code from second_shot into the first_shot function and jettisoning the second shot function for now.

shot1 is a local variable that’s why the program stops

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.