i am trying to get into more global and local scopes in python. My code is below, it recursively invokes itself. I tried to put there limitation while var i less 6. What I got is strange, that i varibale cannot be seen in while i <6
from random import choice
global i
i=0
def random_color_code():
hex_chars=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
hex_code='#'
while i < 6:
for i in range(0,6):
hex_code=hex_code+choice(hex_chars)
print(hex_code)
return random_color_code()
print(random_color_code())
Giving an error while i < 6: UnboundLocalError: local variable 'i' referenced before assignment, but if i change variable to other name such as a it works
from random import choice
global a
a=0
def random_color_code():
hex_chars=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
hex_code='#'
while a < 6:
for i in range(0,6):
hex_code=hex_code+choice(hex_chars)
print(hex_code)
return random_color_code()
print(random_color_code())
i wonder if it is seeing locally for i in range(0,6) on next line and thinks variable will be compiled next line, then why does not accept i as global variable ?
global iin the function definition -- but then will discover that you have an infinite recursion. Why are you using recursion and global variables at all? A simple 1-liner:'#' + ''.join(random.choices(hex_chars, k = 6))should suffice.kis an argument for choices function? I wanted to get more depth about scopes in pythonkis an argument forchoices.