Tutorial on Variables in Python

What is a variable?

A variable can be thought of as a container to store values. Variables will be the names to hold values during the lifetime of a program. A variable has its own memory allocated during the program. You can think of a variable as a value that changes based on various conditions or transformations the data goes through during the running of a program. A program consists of instructions on what is being done with the data and what happens to the data.

How are data types evaluated for variables in Python?

We do not mention data types explicitly in a Python program.

1. Simple example

I would like to show an example.

a = 100
b = "variables tutorial" 
c = 156.89 
print(a)
print(b)
print(c)

The output will be:

100
variables tutorial
156.89

We know that the variable a is an integer, b is a string and c is a float data type. We do not use them explicitly like C, C++ etc.

2. Multiple Assignment of variables

We can assign multiple variables in a single line. I have an example for you.

output, profit,dollar = "hello!!!", 300.22,'$'
print(output)
print("The profit is ", profit)
print(dollar)

#output
hello!!!
The profit is  300.22
$

I was able to make multiple assignments for output as a string, profit as a decimal, the dollar as a single character. I used them to print it out later.

3. Combining similar data types and using them together with ‘+’

I have 2 variables of the same type and I used a ‘+’ operator on it. It applies the addition of the variables and prints them out.

a,b = 200, 34 
print(a+b)

#output 
234 

Another example with strings below

str1 = "Playing with Variables "
str2 ="in Python "
str3= "is amazing"
print(str1+str2+str3)

#output
Playing with Variables in Python is amazing

I apply ‘+’ on strings, it appends them together and the out will be a single line of appended strings.

I try to combine different data types together python throws an error.

python error when using ‘+’ on different data types

We can fix this by doing the below.

sayHello = "hello!!!"
profit = 300.22
dollar = '$'
print(sayHello+str(profit)+dollar)
#output 
hello!!!300.22$

All I did was added a type conversion of str(). I am indicating that no matter what its data type is, I would like it to be converted into a string.

I would like to give more details on the standard data types available in Python. It will be in ‘Primitive data structures in the Python’ section. Click here.

Please feel free to check out the documentation in Python.org

Please view the next tutorial for built-in types here.

Go back to the lesson Overview.