Variables in Python

One of the most powerful features of a programming language is the ability to manipulate variables.
When we create a program, we often like to store values so that it can be used later.
A variable is a name which refers to a value. OR Variables are containers for storing data values. A variable is created the moment you first assign a value to it.

x = 100 ## x is a variable that stores 100

Rules for Creating a Variable

Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
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)

xyz = "hello"
Xyz = "world"
xYz = 100
x_yz = 10.09
_xyz = [1,2,3]
xyz_2 = ("hi","buddies")
xyz2 = {1,2,5}
Invalid Variables
1xyz = "hello world"
1-xyz = 100.32
x-yz = ("a","A")
@xyz = [23,43]
xy z = 100

Multi Words Variable Names

Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:

thisIsAVariable = "string text"
Pascal Case
Each word starts with a capital letter:
ThisIsAVarianle = "string text"
Snake Case
Each word is separated by an underscore character:
this_is_a_variable = "string text"

Python Variables - Assign Multiple Values

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

x , y , z = 100 , "abcd" , [123,"hello"]
print(x) ## 100
print(y) ## 'abcd'
print(z) ## [123,'hello']

One Value to Multiple Variables

You can assign the same value to multiple variables in one line:

x = y = z = 100
print(x) ## 100
print(y) ## 100
print(z) ## 100

Unpack a Collection

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

x , y , z = [12,"hello",12.43]
print(x) ## 12
print(y) ## 'hello'
print(z) ## 12.43