Brandon Lee
Brandon Lee

Reputation: 765

Python3 string format assignment lead to referenced before assignment

I understand that there exist numbers of posts about referenced before assignment with increments.

However, I see a similar issue with format string.

greeting = "hello, {}"

def printHello(name):
   greet = greeting.format(name)
   print(greet)

printHello("Erica")

I have local variable 'greet' referenced before assignment.

Can anyone explain why this is the case?

Also, this error occurs once in a while so it's not deterministic...

I assume global greeting will fix the issue?

== edited ==

I have found that the error was coming from one of the library not my code sorry for confusion

Upvotes: 3

Views: 166

Answers (1)

votelessbubble
votelessbubble

Reputation: 805

The problem here is that you have re-defined print and hence it is going in a recursion. Changing the function name to something else, should solve the problem

greeting = "hello, {}"

def printHello(name):
    greet = greeting.format(name)
    print(greet)

Upvotes: 5

Related Questions