Signup/Sign In

Scope of the variable initialised in the if statement

In this article, we will learn about what happens to the variable that is initialized inside an if statement in Python. We will use some custom codes to better understand the topic. Let's first have a quick look over what is an if statement in Python.

Python If Statement

Python has statements known as Conditional Statements to check for logical conditions. If statement is one of the conditional statements in Python. It checks for a condition using if keyword and if the condition given turns out to be True upon evaluation, it comes inside the scope of that if statement, otherwise it continues with the program code. It is also known as the decision making process. For example,

   does something..

Scope of a Variable in If Statement

Control blocks like If statements in Python do not count and the variables used or initialized inside the block of an If statement can also be used and accessed outside its scope. This is a normal functionality of if statements that programmers use in their everyday codes. Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". So, anything declared in an if block has the same scope as anything declared outside the block. Variables are not checked at compile-time, which is why other languages throw an exception. In Python, so long as the variable exists at the time you require it, no exception is thrown.

Example: Variable has Local Scope

Here, b is not initialized or declared before the if condition. b is initialized inside if block and it can be used outside the if block locally throughout the program.

#local varaible outside if
a = 2

#check for an expression
   #local variable inside if
   b = a+2



Example: When an If Statement returns an error

In this case, the expression (a==3) is False, so the statement inside if does not executes. When we try to print the value of x outside the if block , it returns NameError because x doesn't exist or it is not defined.

#local variable outside the if statement
a = 2

#checks for an expression
    #local variable declared inside if block
    x = 3

#returns error

NameError: name 'x' is not defined


In this article, we learned about the scope of a variable that is defined inside the if block. We learned that control blocks allow all the variables to be used locally even if they are initialized inside the if block. Variables have a local scope that are defined inside the if statements.

About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.