How to Set Variable Scope in Python


Through this example, we can learn how to set the scope of variables in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

num = 2

def autofunc():
    num = 1
    print('internal block num = %d' % num)
    num += 1

for i in range(3):
    print('The num = %d' % num)
    num += 1
    autofunc()

Output:

The num = 2
Internal block num = 1
The num = 3
Internal block num = 1
The num = 4
Internal block num = 1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement