I have a function (calculate) that references a variable outside of it (fill and empty) and it just won't detect that the variable already exists and tries to create one but I need that result for another function (render). Here is my code:
render = 0
isRunning = True
fill = ""
empty = ""
os.system('clear')
def calculate():
for x in position:
render = x
if render == 0:
empty = "-"
if render == 1:
fill = "⬛"
def render():
if position[0] == 1:
print(fill, empty)
if position[0] == 0:
print(empty, fill)
os.system('clear')
while isRunning:
calculate()
render()
time.sleep(3)
os.system('clear')
This is my new code after Pranav Hosangadi. I was confused on how to pass arguments into a function because I'm new to Python. This still doesn't work:
import time
import os
ant = "#"
position = [0, 1, 0]
render = 0
isRunning = True
fill = ""
empty = ""
def calculate(empty = empty, fill = fill):
for x in position:
render = x
if render == 0:
empty = "-"
if render == 1:
fill = "⬛"
return fill, empty
def render_function():
if position[0] == 1:
print(fill, empty)
if position[0] == 0:
print(empty, fill)
os.system('clear')
while isRunning:
calculate()
render_function()
time.sleep(3)
os.system('clear')
Any help would be great.
render()overwrites the integerrender = 0? Even if you fix the problem of referencing the global variable, nothing will happen when you docalculate()becauserenderis a function, not an integer, and is never equal to0or1. Everybody is telling you to use global variables, but that isn't always the best practice. You should just pass the value of your integer to the function as an argument instead, and usereturnto return a value back.globalkeyword. This is done for good reason as modifying global state within a function makes your code much more difficult to reason about.rendervariable seems to serve no purpose other than to copy the loop variable in that loop.