Python Basics #04 – Variables

In this part of the tutorial, we will learn about declaring and using variables in python.

You can think of variables as containers which store data. The data can be an integer, string, or even collections like lists for example.

In python, we don’t need to specify the data type while declaring the variable. Python automatically decides the data type when the variable is declared.

x = 5
y = 5.0
z = "string"
declaring variables in python
Declaring variables in python

We can print the data type of the variable using the type() method. As you can see above x has the type int, y has the type float and z has the type str.

We can change the data type of variable even after it is assigned. All we need to do is just reassign its value. Consider the example below.

x = 5     # x is an int here
x = 'a'   # x becomes str here

Strings can either be declared using single quotes OR double-quotes. Otherwise, we will get a “syntax error”.
For instance, have a look at the code below.

a = 'this is a string'
b = "this is also a string"
c = 'this will give a syntax error"
d = "this will also give an error'

Now we know how to declare a variable. There are some rules of using variable names which we need to follow too.

  • Variable names 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)

In the next part of the tutorial, we will learn about the different operators used in python.


Back : Python Basics #3 – Python Syntax

Next : Python Basics #5 – Operators

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: