variable referenced before assignment error in python : <p>In my code I am testing if a user has AWS access keys:</p>

<pre><code>for response in paginator.paginate(UserName=user_name):
    if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys():
        key1 = response['AccessKeyMetadata'][0]['AccessKeyId']
</code></pre>

<p>Later in my code I test if key1 exists:</p>

<pre><code>if key1:
    print("\nAccess Key 1: ", key1)
else:
    print("The user does not have any keys.")
</code></pre>

<p>If the user has NO keys at all, the function fails with this error:</p>

<pre><code>  File ".\aws_iam_utils.py", line 1430, in rotate_access_keys
    if key1:
UnboundLocalError: local variable 'key1' referenced before assignment
</code></pre>

<p>Am I testing if key1 exists correctly? Why am I getting an unbound local error, when it should just print out the statement in the else clause?</p>
