Variables in python with examples

Python variables

Variables are a essential part of programming languages, and Python is no different.

One important thing to note about in Python is that every variable is considered as an object, this is because Python is completely Object Oriented.

Variable names:

One of the first thing you should learn is how you should be naming your variable in Python. There are few rules you must follow while naming your variables in Python. The rules are quite simple and easy to understand.

  • You cannot declare a variable starting with a digit, it should be either a letter or an underscore(_). For example, _avg, sum, num1 and so on are valid variable names but 1num is invalid.
  • Your variable name must contain only uppercase(A-Z), lowercase(a-z) or underscore(_). For example, mean, new_sum, Square and so on.
  • Variable names in Python are case sensitive. So, Square and square are two different variables though they have the same name but they differ because they have two different casing.

Hence, a variable is a named area used to store information in the memory. It is useful to consider variables a compartment that holds information which can be changed later in the program. For instance,

a = 10

In the above example, we have created a variable and we have assigned the value 10 to it.

Assigning values to a variable

As you can see from the above model, you can utilize the assignment operator = to assign a value to a variable.

Example 1: Declaring and assigning a value

fruit = "apple"
print(fruit)

In the above program, we allotted a value apple to the variable fruit. At that point, we printed out the value appointed to fruit. The datatype of the variable will be dynamically interpreted by the Python interpreter.

Example 2: Changing the value of the variable

fruit = "apple"
print(fruit)

fruit = "orange"
print(fruit)

Output

apple
orange

The value of the variable can be changed even after declaration.

Example 3: Assigning multiple values to multiple variables.

a, b, c = 5, 10, "Welcome"
print(a)
print(b)
print(c)

Output

5
10
Welcome

The way to do this is to list your variables separated by commas(,). The order of your variables will be in same order as the values will be assigned.

Example 4: Assigning same values to multiple variables

a = b = c = 10
print(a)
print(b)
print(c)

Output

10
10
10

To assigned same values to all the variables we need to separate each of the variables by using the equals sign(=). The final equal sign(=) should be the value which you want to assign to all the variables. Hence, after printing a,b and c, it gives us the value 10.