0

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 ?

8
  • 2
    You could put global i in 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. Commented Nov 11, 2022 at 10:58
  • i am not familiar with it. k is an argument for choices function? I wanted to get more depth about scopes in python Commented Nov 11, 2022 at 11:01
  • the answer here was what i needed about for loop variable declaration. Why deleted? Commented Nov 11, 2022 at 11:01
  • 1
    There is nothing wrong with doing an experiment, but yes k is an argument for choices. Commented Nov 11, 2022 at 11:02
  • 1
    You probably want a generator function that produces an infinite stream of random colors, but only produces each color on demand as you iterate over that stream. Commented Nov 11, 2022 at 13:04

2 Answers 2

1

If you are determined to implement this using a global variable and recursion, as an experiment, this is how you might do it:

def random_color_code(length=6):
    hex_chars = ['0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    global i  # global statement needs to be inside the function
    i += 1    # we don't need to loop inside the function - recursion replaces the loop
    c = choice(hex_chars)
    if i < length:
        return c + random_color_code()
    elif i == length:
        return c  # This condition allows us to escape infinite recursion

i = 0
print(random_color_code())
print(random_color_code()) # None - counter has not been reset
i = 3 
print(random_color_code()) # only prints half the code

As you can see, this makes the function reliant on an external variable, and also allows the function to change that external variable, making the program's behavior hard to predict and reason about. This is how the recursive function could be written with a default parameter instead of globals:

def random_color_code(i=0, length=6):
    hex_chars = ['0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    c = choice(hex_chars)
    if i < length - 1:
        return c + random_color_code(i + 1)
    elif i == length - 1:
        return c

But there is no particular need for recursion here anyway - a loop or choices would be better.

Sign up to request clarification or add additional context in comments.

Comments

1
from random import choice
global i
i=0
def random_color_code(i):
hex_chars = ['0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b',   'c', 'd', 'e', 'f']
hex_code = '#'
if i >= 6:
    return ""
else:
    for i in range(0, 6):
        hex_code = hex_code+choice(hex_chars)
        print(hex_code)
return random_color_code(i+1)


print(random_color_code(i))

1 Comment

This should works now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.