Function breaks all code that come after it - python

I've started working on a small game. I've created a function that breaks all the code that follows it. Here's the full function:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
although it still works with just this:
def printBoard(currentBoard):
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
even things like:
print("Hello")
won't work after it. I've tried switching around variable names and such but the error the error still remains.

Looks like you are missing a closing ")"

Your indentation is wrong, change the function to this:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))

Related

Trying to get my python program to run but I keep getting a variable assignment error. Any ideas as to what I am doing wrong?

def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.

Initializing and displaying grid - python

I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())
You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.

sys.stdout.write not working as expected in Python

I have two functions prints() and clear(). The function prints() print lines of text and the function clear() delete the printed lines with this method:
def clear():
i = 0
while True:
if(i > globals['l']):
break
else:
sys.stdout.write("\033[F \033[K")
i += 1
where globals['l'] is the number of lines to clear.
Then after the function clear() runs and the lines are cleared, the function prints() run again etc...
I don't understand why the function clear() is clearing only 22 lines of 32 lines. But if I have, for example, 19 lines it is working perfectly. Where is the problem? How can I fix this?
Try this:
def clear(line_count):
sys.stdout.write("\033[F \033[K" * line_count)
sys.stdout.flush()
EDIT:
Works only on Unix systems
You can use:
print("\033c")
Or:
import subprocess
subprocess.call(["printf", "\033c"])

Functions: printing blank lines (Python)

Page 27 of "How to think like a computer scientist: Learning with Python" reads:
"As an exercise, write a function called nineLines that uses threeLines to print nine blank lines. How would you print twenty seven lines?"
I wrote:
def newLine():
print
def threeLines():
newLine()
newLine()
newLine()
def nineLines():
threeLines()
threeLines()
threeLines()
print 1
print nineLines()
print nineLines()
print nineLines()
print 2
The result was:
1
None
None
None
2
Why those "none" there? I suppose I don't want them there. Was my reasoning correct? Thanks.
Your reasoning is correct, except that the print is redundant. nineLines is going to print the lines anyway. What your print statement is printing is the return value of the function, which since it isn't explicitly returning anything is None.
def threeLines():
for i in range(3):
print '\n'
def nineLines():
for i in range(3):
threeLines()
for i in range(3):
nineLines()

Tk python code is ignored?

I'm making a GUI based game but for some reason a couple of lines in my code are not doing anything at all, when i know they should be.
def inspect():
if 'camera' in inv:
out1.config(text="there's nothing unusual here")
darts()
For some reason, darts() and out1.config() are completely ignored in this specific part of the code.
I know the if statement runs as it should, I have used some print statements to make sure. the function is called at the right time, and inv does contain 'camera'.
I have used different text in out1.config(),but no matter what this line wont do anything.
the code simply continues on after as normal, as if the if statement never ran, and just does what would happen if the statement returned false. everything past then runs fine, everything before runs fine.
This bit of code worked perfect before, but just when i came back to do some more work on it it suddenly dosnt work.
Here is the GUI part:
global a , b , c , d ,out1 , main_menu,out2
main_menu.destroy()
window=gui.Tk()
global window
actions1 = gui.Frame(window)
out2 = gui.Label(window,text='Brefing room ; Cmdr Forge')
out1 = gui.Message(window,text='ok')
line = gui.Label(text='-------------------------------------------------------------')
a = gui.Button(window,text = 'a')
b = gui.Button(window,text = 'b')
c = gui.Button(window, text = 'c')
d = gui.Button(window, text = 'd')
out2.pack()
line.pack()
out1.pack(side='right')
actions1.pack()
a.pack()
b.pack()
c.pack()
d.pack()
start()
window.mainloop()
EVERYTHING else that uses this works as it should.
This is the part of code that inspect() is in:
def darts():
def inspect():
if 'camera' in inv:
out1.config(text="there's nothing unusual here")
darts()
def inspect_glass():
def remove():
out1.config(text = 'you now have a minature video camera. If only you knew where to plug it in so you could see the footage.')
inv.append('camera')
darts()
out1.config (text="on closer inspection it appears to be a lens of a minature video camrea. it is not one of the agency's, it looks different from the ones they use.")
a.config (text='remove camrea',command = remove)
out1.config(text='above the dartboord apears to be a small glass ball, pressed firmly into the wall')
a.config(text='look closer',command = inspect_glass)
a.config(text='look at dartboard', command = inspect)
b.config(text='play darts', command = play_darts)
c.config(text='do something elce', command = commons)
out2.config(text='Common room ; darts')
The code basicly does this:
if you look at the deartboard you see a glass ball. if you look closer you see its a camrea. you have the option to take it. ten if you were to look at the dartboard again, it should say nothing usual here, if you had already taken the camera.
def inspect():
print '-*- HERE -*-'
print inv
print 'camera' in inv
if 'camera' in inv:
print '--> yes'
out1.config(text="there's nothing unusual here")
darts()
else:
print '--> no'
In case of doubts, try putting enough prints that you can track what exactly occurs. I bet that, unlike what you deduced, they will not output an inv with 'camera' in it but at the same print --> no.
A better idea is to replace all these prints with import pdb; pdb.set_trace() and then use the debugger.

Categories