Why do I keep getting a UnboundLocalError with my function? - python

so I've been struggling with the first part of an assignment. For some reason the while loop in the entrance() function has been causing problems. As far as I know, this is the only statement that has been throwing me off. Can help me fix this?
#Satinderpal Saroa A3 30027872
#Entrance Function
def entrance():
lockedDoor = True
print("""
ROOM: ENTRANCE
_____________________________________________________________
You are at the entrance. The door you entered through is gone
and the door to what might be the exit is in front of you.
There are two entryways to the left and the right, what will
you choose to do?
_____________________________________________________________
Your choices are:
1. Try to open the door
2. Go through the left entryway
3. Go through the right entryway
""")
enterChoice = int(input("Your choice: "))
while lockedDoor == True:
if (lever == "backwards" and dial == "red"):
lockedDoor == False
print("You go through the door and enter... another part of the house?!")
if(enterChoice not in [1,2,3]):
print("INVALID INPUT: Please enter 1,2, or 3.")
enterChoice = int(input("Your choice: "))
if (enterChoice == 1):
print("You try to open the door, it doesn't move an inch!")
enterChoice = int(input("Your choice: "))
elif(enterChoice == 2):
print("You make your way down to the kitchen.")
lever = kitchen()
elif(enterChoice == 3):
print("You make your way down to the pantry")
dial = pantry()
return()
#Kitchen Function
def kitchen():
lever = "nothing"
print("""
ROOM: KITCHEN
_____________________________________________________________
You reach the kitchen. Everything is spotless, a disturbing
revelation as you know that the house hasn't been touched
in decades. Near the sink, there is a lever that can be pulled
backwards or forwards. What will you do?
_____________________________________________________________
Your choices are:
1. Pull the lever backwards
2. Push the lever forwards
3. Do nothing and go back to the entrance
""")
kitchenChoice = int(input("Your choice: "))
if (kitchenChoice not in [1,2,3]):
print("INVALID INPUT: Please choose between 1,2, and 3")
kitchenChoice = int(input("Your choice: "))
elif (kitchenChoice == 1):
lever == "backwards"
print("The lever is pulled backwards")
lever = entrance()
elif (kitchenChoice == 2):
lever == "forwards"
print("The lever is pushed forwards")
lever = entrance()
elif (kitchenChoice == 3):
print("You don't do anything and return to the entrance")
lever = entrance()
return (lever)
#Pantry Function
def pantry():
dial = "nothing"
print("""
ROOM: PANTRY
_______________________________________________________________
You reach the pantry. All of the foodstocks and goods have been
expired for ages. You notice a dial that can be turned to one of
three colors; red, blue, and green. What will you do?
_______________________________________________________________
Your choices are:
1. Turn the dial to red
2. Turn the dial to blue
3. Turn the dial to green
4. Don't do anything and return to the entrance
""")
pantryChoice = int(input("Your choice: "))
if (pantryChoice not in [1,2,3,4]):
print("ERROR: Please enter 1,2,3 or 4.")
pantryChoice = int(input("Your choice: "))
elif (pantryChoice == 1):
dial == "red"
print("The dial is set to red")
dial = entrance(dial)
elif (pantryChoice == 2):
dial == "blue"
print("The dial is set to blue")
dial = entrance()
elif (pantryChoice == 3):
dial = "green"
print("The dial is set to blue")
dial = entrance()
elif (pantryChoice == 4):
print("You don't do anything and you return to the entrance")
dial = entrance()
return(dial)
#Start function
def start():
entrance()
start()

please initialize 'lever' variabel in entrace as it is used in it else use a global variable 'lever' in the program

Related

How to break multiple loops in an if-statement within an if-statement in Python 3

How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:
while True:
print("choose 1st branch")
choice = input()
if choice == '1':
print('1, now choose second branch')
while True:
choice = input("")
if choice == "2":
print("2")
while True:
choice = input("")
if choice == "3":
print('3')#
else: #needs to ask for input for choice 3 again
print("try again")
else:print("try again")#needs to ask for input for choice 2 again
ive edited a simpler code example of what im trying to accomplish
Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.
occu = "ranger"
prompt = "-->"
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
def room1():
print("you walk into an bare room")
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = "ranger"
while True:
print("you see a door infront of you")
print("do you go left, right or forward?")
choice = get_user_choice(prompt, ("left", "right", "forward"))
if choice == "left" and hole == False:
print("\nDo you \ndodge \nor \nattack?")
choice = get_user_choice(prompt, ("dodge", "attack"))
if choice == "dodge" and occu == "ranger":
trap = True
rat = True
print("\nhole \nroom")
choice = get_user_choice(prompt, ("hole", "room"))
if choice == "hole" and rat == True:
print("you walk up to the hole, you see a faint glitter")
print("do you reach your hand in?")
print("\nyes \nno")
choice = get_user_choice(prompt, ("yes", "no"))
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
choice = True
elif choice == "no":
print(" you go back to the centre of the room")
Notice that other input also get modified to use this function to check if the choice user selected is valid or not.
The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.
proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
proceed = True # CHANGE PROCEED, NOT CHOICE
elif choice == "no":
print("You go back to the center of the room")
# Perhaps assign proceed to be True here as well?
else:
print("unknown choice, try again")
occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
print("you see a door infront of you")
print("do you go left, right or foward?")
if input(prompt) == 'left' and hole == False:
print('\nDo you \ndodge \nor \nattack?')
if input(prompt) == 'dodge' and occu == 'ranger':
trap = True
rat = True
print("\nhole \nroom")
if input(prompt) == 'hole' and rat == True:
print("you walk up to the hole, you see a faint glitter")
while True:
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice not in ['yes', 'no']:
print("unknown choice, try again")
continue # <-- Starts loop over.
elif choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
else:
print(" you go back to the centre of the room")
break # <-- Breaks out of loop.

Vending Machine Program help(python)

I'm kinda stuck on something. Well, alot of things but one step at a time right. I'm not sure how to get the program to add the choices that the user input together. The assignment asks me to make a vending machine that gets a users input, return the total to them when they input 0 to quit, then it will ask them to enter the money to pay, if it is a valid amount, it will dispense change, if not, it will ask for more money. Right now though, I'm stuck on it returning the user choices and adding the total together. I will paste my code below. thanks
def main():
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = float(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices = []
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
I have discovered one problem which is that when you declare choices you declare it inside the loop, meaning it becomes [] each time the user picks something.
Try this:
def main():
choices = []
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = int(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
This means that the choices variable now has something useful in it.
Here is a more refined approach, it always helps to see different design concepts:
options = {
'1': {'title':'Dr.Pepper','price':1.50},
'2': {'title':'Mtn.Dew','price':1.50},
'3': {'title':'Water','price':1.00},
'4': {'title':'Doritos','price':1.75},
'5': {'title':'Snickers','price':1.50},
'6': {'title':'Gum','price':0.50}
}
def get_number(question):
value = input(question)
while 1:
try:
value = int(value)
break
except:
value = input(f'(must be a number) {question}')
return value
def main():
choices = []
amount = 0
while 1:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
for k, v in options.items():
print(f"\t{k}. {v['title']} - ${v['price']:.2f}")
# Now, the first input will ask the user to enter their choice
userchoice = get_number('Please enter the number corresponding to your preferred item or 0 to quit:')
if userchoice == 0:
break
# Now, the program will print the choice and re-run it until the user selects 0
choice = options.get(str(userchoice), None)
if choice:
choices.append(choice['title'])
amount += choice['price']
print(f"You selected one {choice['title']} for ${choice['price']:.2f}")
else:
print('Invalid Choice, Please Try Again')
print('Your Cart Contains:')
for each in sorted(choices):
print(each)
print(f'Total Amount: {amount}')
return choices, amount
choices, amount = main()

how do i use loop with double input. first asks for a letter then the output then asks if u wanna play again or quit(1, 2)

so basically I want to start with the door input then check if the door has money or not then ask the user again if he would like to play again using the play input. if user enters 2 then asks again which door and so on. if the user enters 2 or if the number of miss on the door(no money) is = 3 then the game stops. right now the problem is it will run the loop jackpot ==1 till the it hits jackpot == 0 and play ==1 is not working
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
print()
play = input("Do you wish to quit (1) or open another door (2)?")
if play == "2" and miss <= 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
play == "1"
print("Congratulations!! You have won $", total, ".")
else:
miss == "3"
print("Sorry the game is over. You win $", total, ". Try again.")
else:
print("try again")
Try this code see if this works, there were lots of mistakes I added break statements and refined the logic
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
else:
print("try again")
break

the input is not working in the second time

when an invalid answer (a number higher than 2) is given and is sent back to the intro(name) (see the else statement at the bottom) which is the introduction, the choise1 is auto completed and is redirected to crowbar()
def intro(name):#added the whole code
print( name + " you are in a back of a car hands tied, you can't remember anything apart the cheesy pizza you had for breakfast")
time.sleep(1)
print("you can see 2 men outside the car chilling out, they haven't seen that you have waken up")
time.sleep(1)
print("you figure out that your hands are not tied hard and manages to break free")
time.sleep(1)
print("and you see a piece of paper with your adress in it on the armrest in the middle of the front seats")
time.sleep(1)
print(" you see a crowbar under the back seat ")
time.sleep(1)
print("CHOOSE WISELY")
time.sleep(1)
print("""
1)grab the crowbar
2)check to see if the door was open""")
def car():
if choise1 == 1:
crowbar()
elif choise1 == 2:
door()
else:
print("that's not a valid answer")
intro(name)
choise1 = int(input("enter 1 or 2"))
car()
you can use function with parameter in this example (x )
def car(x):
if x == 1:
print("crowbar()")
elif x == 2:
print("door()")
else:
print("that's not a valid answer")
print("intro(name)")
choise1 = int(input("enter 1 or 2"))
car(choise1)

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

Categories