Previous Next

Python Variables

Variables are employed to keep data values. Python is a dynamically typed language, so you don't need to declare a variable type explicitly.

Example:

name = "john"  #type str
age = 22       #type int

Variable Names

Example:

Fruit = "banana"    #valid variable name
FrUit = "apple"     #valid variable name
_fruit = "mango"    #valid variable name

5fruit = "lemon"    #invalid variable name
$fruit = "grape"    #invalid variable name

A multi-word variable name can be cumbersome to the reader. To enhance readability, the programmer can follow these:

Example:

NameOfCountry = "India"      #Pascal case
nameOfCountry = "Japan"      #Camel case
name_of_country = "Russia"   #snake case

Global and Local Variables

Variables are classified into two categories: global variables and local variables.

Local Variable

A local variable is declared within a function and can only be accessed from within that function.

Example:

def my_func():
    fruit = "Orange"
    print(fruit + " is a local variable.")

my_func()

Output

Orange is a local variable.

Global Variable

Global variables are defined outside of a function and may be used anywhere within the program.

Example:

fruit = "Orange"

def my_func():
    print(fruit + " is a global variable.")

my_func()

Output

Orange is a global variable.
Previous Next