I'm very new to programming (so sorry if I don't present this problem right).
This is from LPTHW Exercise 36:
My Error:
Traceback (most recent call last):
File "ex36.py", line 329, in <module>
start()
File "ex36.py", line 149, in start
arena()
File "ex36.py", line 161, in arena
if stealth == True:
NameError: global name 'stealth' is not defined
My Assumption:
I thought 'stealth' was defined in the previous function, start(), but the definition didn't carry over to arena(). How do I fix it, and why doesn't 'stealth' from 1 function carry over to another function?
My Code (text-based game in progress):
from sys import argv
script, enemy = argv
...
def start():
print """ Choose a skill to train in
"""
stealth = False
gun = False
knife = False
heal = False
skill = raw_input("> ")
if 'gun' in skill:
print """
"""
gun = True
skill = gun
...
else:
dead()
arena()
def arena():
print """ You enter the arena. Will you:
hide, hunt for food, or search for water?
"""
path = raw_input("> ")
if "hide" in path:
print """ Hide
"""
if stealth == True:
print """ Witness
"""
witness()
else:
battle()
...
else:
print """ Dead
"""
dead()
start()
All advice is greatly appreciated. Thank you for your help.
Variables defined locally in one function have local scope and are not automatically accessible within another, disjunct function. You might want to consider passing stealth to arena when called from start, e.g. arena(stealth), and then stealth would be defined as a parameter of arena, i.e.
def arena(stealth):
Related
I am currently coding a text based game for a class I'm taking. I want to have a function with nested functions so I don't have to re-write player options in every single room. Here is what I currently have:
#The loop:
while p_choice != 'quit': #begins room loop
#The Forest Clearing
while room == 'Forest Clearing':
avail_choices = ['north'] + avail_all
room_inv = [] #items in this room
room_desc = ("\nYou are in The Forest Clearing. To the north you see a large cave\n"
"with stone stairs leading down. There doesn\'t seem to be anything\n"
"you can do here...\n")
if p_choice == 'north':
print("\nYou step through the cave entrance and walk cautiously down the
stairs.\n"
"You find yourself in some sort of cavern, filled with an inky darkness. It is
far too\n"
"dark to see much, but nearby, you see a pile of rubbish with a flashlight
sitting on top.")
room = rooms[room][p_choice]
elif p_choice not in avail_choices:
print('You can\'t do that here!')
room = [room]
else:
all_rooms()
#Function I'm trying to call
def all_rooms():
def look():
if p_choice == 'look':
print(room_desc)
room = [room]
I want it to return to the loop after printing the room description. It prints the room description like I want, but then it crashes and I get the following error:
Traceback (most recent call last):
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 136, in <module>
all_rooms()
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 95, in all_rooms
look()
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 72, in look
room = [room]
UnboundLocalError: local variable 'room' referenced before assignment
You are in The Forest Clearing. To the north you see a large cave
with stone stairs leading down. There doesn't seem to be anything
you can do here...
I've also tried:
def all_rooms():
def look():
if p_choice == 'look':
print(room_desc)
global room
and...
def all_rooms():
def look():
global room
if p_choice == 'look':
print(room_desc)
room = [room]
Not sure what to do here. Any help would be appreciated!
I am attempting to make a simple guessing game for my class with graphics and I'm trying to make an attempt counter. This is the area where my code is going wrong.
def value():
guess = int(input("Enter your guess: "))
if guess > num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooHigh()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess < num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooLow()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess == num:
attempts = attempts + 1
turtle.clearscreen()
interface()
yes()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("pink")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold", "underline"))
print ("Correct!")
else:
print ("ERROR")
def startScreen():
begin = input("Start the game?: ")
if begin == 'yes':
value()
elif begin == 'instructions':
instructions()
startScreen()
elif begin == 'no':
sys.exit()
else:
print ("Unrecognised answer.")
startScreen()
attempts = 0
num = random.randint(1,1000)
interface()
startScreen()
The error I receive is:
Traceback (most recent call last):
File "D:\Desktop\Python Programs\Game.py", line 154, in <module>
`startScreen()`
File "D:\Desktop\Python Programs\Game.py", line 141, in startScreen
`value()`
File "D:\Desktop\Python Programs\Game.py", line 110, in value
`attempts = attempts + 1`
UnboundLocalError: local variable 'attempts' referenced before assignment
It doesn't seem possible to move attempts into the function as it constantly calls itself, resetting attempts each time.
I am unsure why this is occurring so any help would be greatly appreciated. Thanks!
The reason you are getting this error is because of something called variable scope. You have defined the variable attempts outside of the function value, so the function will not recognize any local variable by the name attempts unless you explicitly put the statement global attempts at the beginning of your function. This will tell the function that you want to use the variable attempts that you defined in your main program. That should look like this:
def value():
global attempts
#function code
Alternatively, you can allow your function value to take an argument, and pass the variable attempts into that. That would look something like this:
def value(attempts):
#function code
#you can use the variable attempts as needed, since you're passing it directly into the function
#call the function however you want
attempts = 0
value(attempts)
In the function, when you access a variable for assignment, it by-default is treated as a local variable. So, to make Python know that the variable that you want to modify is a global variable, you do the following:
def value():
global attempts
# rest of your code
I am new to Python and am trying to make a simple game with several chapters. I want you to be able to do different things depending on the chapter, but always be able to e.g. check your inventory. This is why I have tried using nested functions.
Is it possible to create a global function which acts differently depending on what chapter I am in, while still having certain options available in all chapters or should I perhaps restructure my code significantly?
I get the following error code:
> Traceback (most recent call last): File "test.py", line 21, in
> <module>
> chapter1() File "test.py", line 19, in chapter1
> standstill() File "test.py", line 4, in standstill
> localoptions() NameError: name 'localoptions' is not defined
I understand that the global function doesn't identify a nested function. Is there any way to specify this nested function to the global function?
def standstill():
print("What now?")
print("Press A to check inventory")
localoptions()
choice = input()
if choice == "A":
print("You have some stuff.")
else:
localanswers()
def chapter1():
def localoptions():
print("Press B to pick a flower.")
def localanswers():
if choice == "B":
print("What a nice flower!")
standstill()
chapter1()
I used classes as Mateen Ulhaq suggested and solved it. Thank you! This is an example of a scalable system for the game.
(I am new to Python and this might not be the best way, but this is how I solved it now.)
class chapter1:
option_b = "Pick a flower."
def standstill():
print("What do you do now?")
print("A: Check inventory.")
if chapter1active == True:
print("B: " + chapter1.option_b)
#Chapter 1
chapter1active = True
standstill()
chapter1active = False
#Intro
import time
import random
def restart():
bowlSize = random.randint(1,100)
bowlStrawberries = 0
def lel():
while bowlSize > bowlStrawberries:
if (addCheck + bowlStrawberries) > bowlSize:
print('You´re filling the bowl..')
time.sleep(2)
print('...and...')
time.sleep(2)
print('Your mom slaps you!')
restart()
def addStrawberries():
print('The bowl has ' + str(bowlStrawberries) + ' strawberries in it')
print('How many strawberries do you want to add?')
addCheck = input()
lel()
print('STRAWBERRY (:')
time.sleep(2)
print('Okey so you have a bowl kinda')
time.sleep(2)
print('And you have a bag with 100 strawberries')
time.sleep(2)
print('So ur mom forces you to fill the bowl')
time.sleep(2)
print('But she will slap you if a strawberry drops on the floor')
time.sleep(2)
print('So you have to fill it up in as few tries as possible without overfilling it')
time.sleep(2)
restart()
addStrawberries()
I´m new to Programming, it´s my fifth day today and I can´t understand why I get errors. You propably had similar questions but I am new and I don´t know what to search. I basically want it to restart when I pick a higher value than the bowls space.
Exact errors:
Traceback (most recent call last):
File "C:/Users/***/Documents/strenter code herew.py", line 44, in <module>
addStrawberries()
File "C:/Users/***/Documents/strw.py", line 27, in addStrawberries
lel()
File "C:/Users/***/Documents/strw.py", line 14, in lel
if (addCheck + bowlStrawberries) > bowlSize:
NameError: name 'addCheck' is not defined
addCheck is a local variable in addStrawberries, meaning it can't be seen outside of the function. I recommend passing it as an argument to lel, i.e. call lel(addCheck) and define lel as def lel(addCheck). Alternatively you could make addCheck a global variable by inserting the statement global addCheck in addStrawberries before assigning it, but global variables tend to be icky.
I am creating a menu but i have come across an error an would like some help as i don't know what is wrong or how to fix it, the piece of code says i am putting an argument in but i have not entered an argument.
class menu(object):
def print_menu():
# menu options
print "Main Menu:"
print "Start"
print "Quit"
def user_menu():
# users input
menu_choice = raw_input('> ')
if menu_choice == 'start':
start()
#does nothing as of yet
elif menu_choice == 'quit':
raise SystemExit
def start():
pass
#initialising main menu
main = menu()
def start_up()
main.print_menu()
#first attempt
main.user_menu()
#second attempt
main.user_menu()
#third attempt
main.user_menu()
# start again to show the menu options
start_up()
start_up()
please help, this is the traceback error most recent call the occurs in the console when i run the script
Traceback (most recent call last):
File "Engine.py", line 38, in <module>
start_up()
File "Engine.py", line 27, in start_up
main.print_menu()
TypeError: print_menu() takes no arguments (1 given)
You forgot to add self as an argument.
So it has to look like this:
class menu(object):
def print_menu(self):
# menu options
print "Main Menu:"
print "Start"
print "Quit"
def user_menu(self):
# users input
menu_choice = raw_input('> ')
if menu_choice == 'start':
start()
#does nothing as of yet
elif menu_choice == 'quit':
raise SystemExit
Also, I am not sure if using class here is needed. If I were you, I would get rid of the menu class and use just leave those methods.