Datatype & Variables

Updated on Jan 07, 2020


Variables are named locations that are used to store references to the object stored in memory. The names we choose for variables and functions are commonly known as Identifiers. In Python, Identifiers must obey the following rules.

  1. All identifiers must start with a letter or underscore (_), you can't use digits. For e.g: my_var is a valid identifier but 1digit is not.
  2. Identifiers can contain letters, digits and underscores (_). For e.g: error_404, _save are valid identifiers but $name$ ($ is not allowed) and #age (# is not allowed) are not.
  3. They can be of any length.
  4. Identifiers can't be a keyword. Keywords are reserved words that Python uses for special purposes). The following are keywords in Python 3.
1
2
3
4
5
6
7
False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
pass       else       import     assert
break      except     in         raise

Assigning Values to Variables #


Values are basic things that programs work with. For e.g: 1, 11, 3.14, "hello" are all values. In programming terminology, they are also commonly known as literals. Literals can be of different types for e.g 1, 11  are of type int, 3.14 is a float and "hello" is a string. Remember that in Python everything is object even basic data types like int, float, string, we will elaborate more on this in later chapters.

In Python, you don't need to declare types of variables ahead of time. The interpreter automatically detects the type of the variable by the data it contains. To assign value to a variable equal sign (=) is used. The = sign is also known as the assignment operator.

The following are some examples of variable declaration:

1
2
3
4
5
x = 100                       # x is integer
pi = 3.14                     # pi is float
empname = "python is great"   # empname is string

a = b = c = 100 # this statement assign 100 to c, b and a.

Try it out:

x = 100                       # x is integer
pi = 3.14                     # pi is float
empname = "python is great"   # empname is string

a = b = c = 100 # this statement assign 100 to c, b and a.

print(x)  # print the value of variable x
print(pi)  # print the value of variable pi
print(empname)  # print the value of variable empname
print(a, b, c)  # print the value of variable a, b, and c, simultaneously


tip:

When a value is assigned to a variable, the variable doesn't store the value itself. Instead, the variable only stores a reference (address) of the object where it is stored in the memory. Therefore, in the above listing, the variable x stores a reference (or address) to the 100 ( an int object ). The variable x doesn't store the object 100 itself.

Comments #


Comments are notes which describe the purpose of the program or how the program works. Comments are not programming statements that Python interpreter executes while running the program. Comments are also used to write program documentation. In Python, any line that begins with a pound sign (#) is considered a comment. For e.g:

1
2
3
# This program prints "hello world"

print("hello world")

Try it out:

# This program prints "hello world"

print("hello world")


In this listing, line 1 is a comment. Thus, it will be ignored by the Python interpreter while running the program.

We can also write comments at the end of a statement. For e.g:

1
2
3
# This program prints "hello world"

print("hello world")  # display "hello world"

When comments appear in this form they are called end-line comments.

Try it out:

# This program prints "hello world"

print("hello world")  # display hello world


Simultaneous Assignment #


The simultaneous assignment or multiple assignment allows us to assign values to multiple variables at once. The syntax of simultaneous assignment is as follows:

var1, var2, ..., varn = exp1, exp2, ..., expn

This statement tells the Python to evaluate all the expression on the right and assign them to the corresponding variables on the left. For e.g:

1
2
3
4
a, b = 10, 20

print(a)
print(b)

Try it out:

a, b = 10, 20

print(a)
print(b)


Simultaneous assignments is quite helpful when you want to swap the values of two variables. For e.g:

1
2
3
4
>>> x = 1   # initial value of x is 1
>>> y = 2   # initial value of y is 2

>>> y, x = x, y # assign y value to x and x value to y

Expected Output:

1
2
3
4
>>> print(x)  # final value of x is 2
2
>>> print(y)  # final value of y is 1
1

Try it out:

x = 1   # initial value of x is 1
y = 2   # initial value of y is 2

y, x = x, y # assign y value to x and x value to y

print(x)  # final value of x is 2
print(y)  # final value of y is 1


Python Data Types #


Python has 5 standard data types namely.

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary
  6. Boolean - In Python, True and False are boolean literals. But the following values are also considered as false.
    • 0 - zero , 0.0
    • [] - empty list , () - empty tuple , {} - empty dictionary ,  ''
    • None

Receiving input from Console #


The input() function is used to receive input from the console.

Syntax: input([prompt]) -> string

The input() function accepts an optional string argument called prompt and returns a string.

1
2
3
4
>>> name = input("Enter your name: ")
>>> Enter your name: tim
>>> name
'tim'

Try it out:

name = input("Enter your name: ")
print(name)


Note that the input() function always returns a string even if you entered a number. To convert it to an integer you can use int() or eval() functions.

1
2
3
4
5
6
>>> age = int(input("Enter your age: "))
Enter your age: 22
>>> age
22
>>> type(age)
<class 'int'>

Try it out:

age = int(input("Enter your age: "))

print(age)
print(type(age))


Importing modules #


Python organizes codes using modules. Python comes with many built-in modules ready to use for e.g there is a math module for mathematical related functions, re module for regular expression, os module for operating system related functions and so on.

To use a module we first import it using the import statement. Its syntax is as follows:

import module_name

We can also import multiple modules using the following syntax:

import module_name_1, module_name_2

Here is an example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> import math, os
>>>
>>> math.pi
3.141592653589793
>>>
>>> math.e
2.718281828459045
>>> 
>>>
>>> os.getcwd()  # print current working directory
>>> '/home/user'
>>>

Try it out:

import math, os

print(math.pi)
print(math.e)

print(os.getcwd())


In this listing, the first line imports all functions, classes, variables and constants defined in the math and os module. To access objects defined in a module we first write the module name followed by a dot (.) and then the name of the object itself. (i.e class or function or constant or variable). In the above example, we are accessing two common mathematical constants pi and e from the math math. In the next line, we are calling the getcwd() function of the os module which prints the current working directory.

In the next chapter, we will cover numbers in Python.


Other Tutorials (Sponsors)