Creating Variable

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

x = 5
y = "John"
print(x)
print(y)
Dynamic Type

Variables do not need to be declared with any particular type, and can even change type after they have been set.

x = 4       # x is of type int
x = "Sally" # x is now of type str
Casting
x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0
Getting Type of a Variable

You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))
Single Quote vs Double Quote
x = "John"
# is the same as
x = 'John'
Case sensitivity

Variable names are case-sensitive. This will create two variables:

a = 4
A = "Sally"
#A will not overwrite a
Variable naming convention

Variable name must follow the criteria:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Batch Assignment: Different values at different variable

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

The number of variable in left side must be equal to the number of values in right side. Otherwise, it will give error.

Batch Assignment: One value into multiple variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpacking a Collection

If you have a collection of values in a list, tuple etc. Python allows you extract the values into variables. This is called unpacking.

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Global Variable

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example:

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

Output:

Python is fantastic
Python is awesome
Global Variable using `global` Keyword

We can also expose a local variable from inside a function to act as a global variable using global keyword.

Example 1:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Output:

Python is fantastic

Example 2:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Output:

Python is fantastic