Python Variables

Python is a dynamically typed programming language which means there is no need to declare the data type of variable.

Table of Contents

Post Update Timeline

Updated on : 15-07-2020

Added new topics such as Constants, Variable assignment, and naming convention, global and local variables, deleting variables, etc.

Declaring Variables also with different DataTypes

To declare a variable in Python type variable followed by equal to operator or assignment operator and then the data to be stored inside the variable.

Syntax

variable_name = data

By using the above example I can declare variables with different data types such as string, integer, boolean, and float.

name = "Kunal"
age = 25
is_married = False
percentage_scored = 83.50

Note

It is mandatory to declare variables without assigning values to them else NameError the exception is thrown.

name 

print(name)

# PYTHON OUTPUT
Traceback (most recent call last):
    File "main.py", line 1, in 
    name 
NameError: name 'name' is not defined

Declare Variables as Constants

In definition and behavior constants are different from variables. As the value assigned to them remains the same throughout the program runtime.

Note

In Python, there is no such thing as constants. However, you can create a separate constants module file where you declare all the constants and import them to other python scripts as you need. A real-world example related to this is discussed below.

How to use constants in Python Programming Language

Create a my_constants.py:

PI = 3.14159265359
MAX_YEAR = 9999
MIN_YEAR = 1

Create a my_script.py:

import my_constants

print(my_constants.PI)
print(my_constants.MAX_YEAR)
print(my_constants.MIN_YEAR)

# PYTHON OUTPUT
3.14159265359
9999
1

You can also import a particular constant from my_constants.py. In my_script.py:

from my_constants import (PI, MAX_YEAR, MIN_YEAR, )

print(PI)
print(MAX_YEAR)
print(MIN_YEAR)

# PYTHON OUTPUT
3.14159265359
9999
1

Multiple Variable Assignment

You can also assign some data to multiple variables.

foo = bar = 25

print("foo", foo)
print("bar", bar)

# PYTHON VARIABLES
foo 25
bar 25

Also, you can assign different variables to multiple variables in a single line.

jack, john, jim = "Hi I'm Jack", "Hi I'm John", "Hi I'm Jim"
print(jack)
print(john)
print(jim)

# PYTHON OUTPUT
Hi I'm Jack
Hi I'm John
Hi I'm Jim

Variables Naming Convention

Variable naming convention in Python is as given below:

  • Variables must start with alphabet letters which may be the upper or lower case such as Interest, PrincipalAmount, marksScored, total_marks
  • Special characters are not allowed. However, you can use underscore to concatenate two words.
  • Using other special characters and numbers is prohibited.
  • The variable name must be readable and meaningful.

Use the function type() to display variable datatype

x = 15 #<class 'int'> interger
y = "Hello Python" #<class 'str'> string
z = 21.20 #<class 'float'> float
a = True #<class 'bool'> boolean

#print all Variables
print(x, y, z, a)

#print datatype of Variables
print(type(x), type(y), type(z), type(a))

#python output
<class 'int'> <class 'str'> <class 'float'> <class 'bool'>

Concatenate or Combine Variables together.

In Python, the variables of a different datatype can be concatenated together via symbols or operators.

Examples:

String concatenation examples.

name, age, salary = "Kapil", 25, 15000.50

print("%s whose age is %d years has take home salary %0.2f" % ( name, age, salary ) )
print("{} whose age is {} years has take home salary {}".format( name, age, salary ) )
print(f"{name} whose age is {age} years has take home salary {salary}" )
    
# PYTHON OUTPUT
Kapil whose age is 25 years has take home salary 15000.50
Kapil whose age is 25 years has take home salary 15000.5
Kapil whose age is 25 years has take home salary 15000.5

To learn more on string concatenation visit our post by clicking here

Operations on numbers:

a = 10+5
b = 10/2
c = 5*3
d = 10%6

print(a, b, c, d)

#python output
15 5.0 15 4

Global Variables

In simple definition, Global Variables are those whose value can be accessed by the other functions and classes. In most cases, variables which are global are used for the purpose of using their value throughout the program.

Declaring Global Variables in Python

name = "Jake"

def print_name():
    print(f"My Name is {name}")

print_name()

# PYTHON OUTPUT
My Name is Jake

Here the variable name is global and can be accessed inside the function print_name.

Local Variables

Local variables are available at the function or method level scope and like global variables, local variables cannot be accessed outside the function or method.

def print_name():
    name = "Jake" # This is local variable
    print(f"My Name is {name}")

print_name()

# PYTHON OUTPUT
My Name is Jake

Accessing local variables outside of its scope will throw NameError exception.

def set_name():
    name = "John"

set_name()

print(f"My Name is {name}")

# PYTHON ERROR
Traceback (most recent call last):
  File "main.py", line 6, in 
    print(f"My Name is {name}")
NameError: name 'name' is not defined

Accessing both Global and Local Variables inside a Function or Class Method

Consider a situation where you have given the same name to your global, local variable and you have to access those values based on their scopes.

Examples:

name = "kunal"

def print_name():
    global name # Here we are accessing global variable via keyword global
    print(f"My Name is {name}")

print_name()

# PYTHON OUTPUT
My Name is kunal

You can also update the local variable value inside function.

name = "kunal"

def print_name():
    global name
    name = "Jake" # This will update the global value of variable name
    print(f"My Name is {name}")

print(f"Value of variable name before calling function print_name() : {name}")
print_name()
print(f"Value of variable name after calling function print_name() : {name}")

# PYTHON OUTPUT
Value of variable name before calling function print_name() : kunal
My Name is Jake
Value of variable name after calling function print_name() : Jake

Note

Don’t try to directly assign value to a global variable like

 global name = "Jake"

this will throw an exception SyntaxError: invalid syntax.

Using global variables inside class methods.

name = "kunal"

class Person:

    def show_name(self):
    global name
    print(f"My name is {name}")

p = Person()
p.show_name()

# PYTHON OUTPUT
My name is kunal

Deleting or Dumping Variables

You can delete or dump unused variables using del keyword followed by a variable to dump.

Examples:

name = "kunal"
del name
print(name)

# PYTHON OUTPUT
Traceback (most recent call last):
  File "main.py", line 3, in 
    print(name)
NameError: name 'name' is not defined

The exception is thrown because the variable is no longer accessible after deletion. You can also add multiple variables followed by a comma to delete them.

name = "kunal"
age = 12
del name, age    

Note

To learn more on python variables go Visit Python.org

I have also found a great post on this topic in Programiz website.

Summary
Review Date
Reviewed Item
Python Variables
Author Rating
51star1star1star1star1star
Software Name
Python Programming Language
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Programming Language