Search code examples
pythonpython-3.xglobal-variablesglobal

why this code run correctly? (python global keyword)


I'm a newbie... and studying about global keyword. This code creates a random string.

I think line 8, string.append(word[x]) make error on this code because string is a global variable, so must be required global keyword. (global string)

But this code runs correctly... Why can run correctly...?

import random
word = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(" ")
string = []
n = int(input())

def get(leng) :
    for i in range (0, leng) :
        x = random.randint(0, len(word)-1)
        string.append(word[x])
    sen = ''.join(string)
    return sen

print(get(n))

Solution

  • Your code doesn't seem to have any problems at first look, although not very clear on what you want to be happening or the error, but in get(), your list string doesn't need to be assigned as a global variable unless you want to re-define the variable. If for whatever reason, you decide to declare string or any variable in that matter inside a funcion, you would need to change its scope.