Python - Variables

Python

Share
python logo

In this tutorial we will learn to work with variables in Python.

Variables are named memory locations which holds some value. And these values can be changed later.

We don't have to explicitly declare variables in Python to reserve memory space. They are automatically declared and memory is allocated when a variable is assigned a value.

Creating Variables

Following are the rules that we must remember while naming a variable in Python.

  • We can only use letters (uppercase A-Z and lowercase a-z), digits (0-9) and underscore (_) to name a variable.
  • Variable name must start with a letter or underscore.
  • We can't start a variable name with digit.
  • Variable name is case-sensitive.

Following are some of the valid variable names.

isGameOver
x
y
sum
_avg
score1
score2

Following are invalid variable names.

1account      # can't start with digit
user-name     # con't use -

Case sensitive

Variables are case-sensitive in Python which means lowercase variable name and uppercase variable name are treated differently.

Following variables are treated differently even though they are the same word.

score = 10
SCORE = 10

Assign value to a variable

We use the = sign to assign value to a variable.

In the following example we are assigning integer value to a variable x.

x = 10

Same value assignment

We can assign same value in one go to multiple variables in Python.

In the following example we are assigning value 10 to the three variables.

x = y = z = 10

Different value assignment

We can assign different values in one go to different variables in Python.

In the following example we are assigning 1 to a, 3.14 to b, 'Hello World' to msg and 1+2j to c.

a, b, msg, c = 1, 3.14, 'Hello World', 1 + 2j

Swap value of variables

If there are two variables and we want to swap their values without using any third variable then we can write the following code in Python.

var1, var2 = var2, var1

In the following example we have two variables a and b and they hold values 10 and "Happy" respectively and we are swapping their values.

# before
a = 10
b = "Happy"
print("before:", a, b)

# swap
a, b = b, a

# after
print("after:", a, b)

We will get the following output.

before: 10 Happy
after: Happy 10
Share