Data Types
Every value in Python has a data type. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of
these classes. There are various data types in Python. Some of the important types are
listed below.
1. Numbers 2.Strings 3.List 4.Tuple 5.Dictionary
Python Numbers
Integers, floating point numbers and complex numbers belong to Number category.
They are defined as int, float and complex class in Python. We can use
the type() function to know which class a variable or a value belongs to and
the isinstance() function to check if an object belongs to a particular class.
>>> a = 10
>>> type(a)
<class 'int'>
>>> type(2.563214)
<class 'float'>
>>> isinstance(1+2j,complex)
True
Int: Integers can be of any length, it is only limited by the memory available.
Integers are numbers without decimal values
>>> n = int(input("enter a number "))
enter a number 1234
>>> print(n)
1234
Float: A floating point number is accurate up to 15 decimal places. Integer and
floating points are separated by decimal points. 1 is integer,1.0 is floating point
number.
>>> k = float(input("enter a number"))
enter a number12
>>> print(k)
12.0
Complex: Complex numbers are written in the form, a + bj, where a is the real part
and b is the imaginary part. Here are some examples.
>>> m = complex(input("enter a number"))
enter a number3
>>> print(m)
(3+0j)
https://gvsnarasimha.blogspot.com/ 1
Python Strings
String is sequence of characters. strings, which can be expressed in several ways. They can
be enclosed in single quotes ('...') or double quotes ("...") with the same result. Strings are
immutable, so we cannot modify string values. Characters are stored into a string by
using Indexing. Like list and tuple, slicing operator [ ] can be used with string.
>>> s = 'Hello world!'
>>> s[4]
'o'
>>> s[6:11]
'world'
>>> s.upper()
'HELLO WORLD!'
>>> s.lower()
'hello world!'
The string data type has methods, some of the methods of its objects:
string.find(str):Return the lowest index of string character
string.index(Str): returns the index of string character
string.count(str):Return the number of occurrences of substring
string.upper(s):Return a copy of s, but with lower case letters converted to upper case.
string.lower(s):Return a copy of s, but with upper case letters converted to lower case.
Ex:
>>> str1 = "Python is object oriented programming language "
>>> str1.find("t")
2
>>> str1.index("y")
1
>>> str1.count('o')
4
>>> str1.lower()
'python is object oriented programming language '
>>> str1.upper()
'PYTHON IS OBJECT ORIENTED PROGRAMMING LANGUAGE '
https://gvsnarasimha.blogspot.com/ 2
Python List
List is an ordered sequence of items, which can be written as comma-separated values
(items) between square brackets. Lists might contain items of different types, but usually the
items all have the same type
Like strings (and all other built-in sequence type), lists can be indexed and sliced:
>>> a=[1,2.2,'python']
>>> print(a[0])
1
>>> print(a[0:2])
[1, 2.2]
>>> print(a)
[1, 2.2, 'python']
The list data type has methods, some of the methods of list objects:
list.append(x) Adds an item to the end of the list. .
list.insert(i, x)Inserts an item at a given position.
list.remove(x) Removes the first item from the list whose value is x. It is an error if there is no
such item.
list.clear() Remove all items from the list.
list.count(x) Return the number of times x appears in the list.
list.sort() Sort the items of the list in place.
list.reverse() Reverse the elements of the list in place.
>>> a=[1,2.2,'python']
>>> a.append(10)
>>> print(a)
[1, 2.2, 'python', 10]
>>> a.remove(2.2)
>>> print(a)
[1, 'python', 10]
>>> a.reverse()
>>> print(a)
[10, 'python', 1]
https://gvsnarasimha.blogspot.com/ 3
Python Tuple: Tuples are immutable sequences, Tuple is made up of data items with comma
separated values enclosed within parentheses. Tuple is typically used to store collections of
heterogeneous data or homogeneous data items. Like strings (and all other built-
in sequence type), tuple can be indexed and sliced
>>> t = (10,20,30,40)
>>> print(t[0:7])#slicing
(10, 20, 30, 40)
Various methods in tuple are
len(tuple):Gives the total length of the tuple.
max(tuple)Returns item from the tuple with max value.
min(tuple):Returns item from the tuple with min value.
tuple(seq):Converts a list into tuple.
Ex:
>>>t = (10,20,30,40)
>>>l = [1,2,3,4]
>>>print(len(t))
4
>>>print("Maximum Value", max(t))
Maximum Value 40
>>>print("Minimum Value", min(t))
Minimum Value 10
>>>print("Elements of list are:", tuple(l),"\n")
Elements of list are: (1, 2, 3, 4)
Dictionaries: an unordered set of key: value pairs, with the requirement that the keys are unique
(within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-
separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary;
this is also the way dictionaries are written on output.
Example:
>>> dic = {1:'ravi',2:'rani',3:'gopi',4:'gita'}
>>> print(dic)
{1: 'ravi', 2: 'rani', 3: 'gopi', 4: 'gita'}
>>> print(dic.keys())
dict_keys([1, 2, 3, 4])
>>> print(dic.values())
dict_values(['ravi', 'rani', 'gopi', 'gita'])
>>> for x in range(1,5):
print(dic[x])
ravi
rani
gopi
gita
https://gvsnarasimha.blogspot.com/ 4
Functions
We are familiar with functions like print, input, int which are built-in functions
Basically, we can divide functions into the following two types:
1. Built-in functions : Built-in functions are Functions that are part of Python which are
intended to perform specific task. Some of the Built-in functions are input, print, int,
float,…
2. User-defined functions: User-defined functions are the Functions defined by the users to
perform specific task:
When we need to perform very complex and large calculations it becomes difficult to debug,
test and maintain the code. To solve this difficulty we subdivide the program into small
individual chunks, later they combined into a single unit. These individually coded programs
are called subprograms which are referred as “Functions”
When we want to perform some task we write functions on our own which are termed as
user defined functions.
Function: function is a group of related statements that perform a specific task. A function
helps us to break the program into small and modular chunks. A function can be called as
subprogram
When we need same code at multiple locations we write a function and call the function
at that particular position instead of repeatedly writing it. So we can call function as reusable
component
in the above syntax keyword def and function -name are mandatory whereas
parameters,” ” ”docstring” ” ” and return statement are optional
The keyword def introduces a function definition. It must be followed by the function
name and the parenthesized list of formal parameters. The statements that form the body of the
function start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal
is the function’s documentation string, or docstring. (More about docstrings can be found in the
section Documentation Strings.) There are tools which use docstrings to automatically produce
online or printed documentation, or to let the user interactively browse through code; it’s good
practice to include docstrings in code
https://gvsnarasimha.blogspot.com/ 5
Function Call
Once we have defined a function, we can call it from another function, program or even
the Python prompt. To call a function we simply type the function name with appropriate
parameters.
def rect():
l = int(input(“enter length of rectangle:”))
b = int(input(“enter breadth of rectangle:”))
print(“Area of rectangle”, l*b)
rect()
output:
enter length of rectangle 10
enter breadth of rectangle 10
Area of rectangle 100
Writing user defined functions:
Functions without arguments and return type:
Functions without arguments and with return type:
Functions with arguments and without return type:
Functions with arguments and with return type:
Functions without arguments and return type: We can write functions without arguments
and return type. Let us write a simple function to find area of rectangle
Ex: def rect():
l = int(input(“enter length of rectangle:”))
b = int(input(“enter breadth of rectangle:”))
print(“Area of rectangle”, l*b)
rect()
output:
enter length of rectangle 10
enter breadth of rectangle 10
Area of rectangle 100
Functions without arguments and with return type: We can write functions without
arguments and with return type. Let us write a simple function to find area of rectangle
which return area of rectangle
def rect():
l = int(input(“enter length of rectangle:”))
b = int(input(“enter breadth of rectangle:”))
return l*b
ar = rect()
print(“Area of rectangle”,ar)
output:
enter length of rectangle 20
enter breadth of rectangle 10
Area of rectangle 200
https://gvsnarasimha.blogspot.com/ 6
Functions with arguments and without return type:
We can write functions with arguments and without return type. Let us write a simple
function to find area of rectangle
def rect(l , b ):
print(“Area of rectangle”,l*b)
rect(10,10)
output:
Area of rectangle 100
Functions with arguments and return type:
We can write functions with arguments and without return type. Let us write a simple
function to find area of rectangle
def rect(l , b ):
return l*b
c = rect(10,10)
print(c)
output:
Area of rectangle 100
Call by value: The call by value is passing arguments to a function, where the actual value of
an argument is passed into the formal parameter of the function
Ex:
def rect(l , b ):#formal arguments
return l*b
c = rect(10,10)#actual arguments
print(c)
Call by reference: The call by reference is passing reference into the formal parameter of the
function
def rect(l):
return l
k = [1,2,3]
c = rect(k)
print(c)
Output:[1,2,3]
https://gvsnarasimha.blogspot.com/ 7
Recursion: A function calling itself repeatedly till some condition is met is called a s recursion.
Ex: Factorial by using recursion
def fact(k):
if k==1:
return 1
else:
return(k*fact(k-1))
n = int(input("Enter Number"))
if n>1:
f = fact(n)
print("The factorial of given number is", f)
output: Enter number 5
The factorial of given number is 120
Default Arguments
Function arguments can have default values in Python. We can provide a default value to an
argument by using the assignment operator (=).when we don’t supply actual arguments the
default arguments will be supplied as input. if we supply actual arguments we get the result
based on it. Here is an example.
Example:
def rect(l=10,b=20):
print(l*b)
rect( )
output:
200
The above program takes default arguments l=10,b=20 and calculates area of rectangle as 200
Ex:2
def rect(l=10,b=20):
print(l*b)
rect(50,60 )
output:
3000
exit() function:
It is a predefined function, and it is used for terminate from the python program. It is coming
from sys module.
Syntax: exit()
Example: while 1:
print(“ exit loop ”)
exit()
Output: exit
And a dialogue box will be displayed prompting to kill the program
https://gvsnarasimha.blogspot.com/ 8
Modules:
Modules: Modules refer to a file containing Python statements & definitions. A file containing
Python code, for e.g.: example.py, is called a module.
We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code. We can define our most used
functions in a module and import it, instead of copying their definitions into different programs.
# Python Module example
def add(a, b):
"""This program adds two numbers and return the result"""
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
Importing modules :
We can import the definitions inside a module to another module or the interactive
interpreter in Python. We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.
>>> import example
This does not enter the names of the functions defined in example directly in the current
symbol table. It only enters the module name example there. Using the module name we can
access the function using dot (.) operation.
For example:
>>> example.add(4,5.5)b
9.5
There are various ways to import modules. They are listed as follows.
The import statement
We can import a module using import statement and access the definitions inside it using the dot
operator as described above. Here is an
example.
# to import standard module math
import math
print("The value of pi is", math.pi)
Output
The value of pi is 3.141592653589793
https://gvsnarasimha.blogspot.com/ 9
Import with renaming
We can import a module by renaming it as follows.
>>> import math as m
>>> print(m.pi)
3.141592653589793
Here we renamed the math module as m.
Hence, math.pi is invalid, m.pi is the correct implementation.
The from...import statement
We can import specific names form a module without importing the module as a whole. Here is
an example
.
# import only pi from math module
>>>from math import pi
>>>print("The value of pi is", pi)
The output of this is same as above. We imported only the attribute pi form the module. In
such case we don't use the dot operator. We could have imported multiple attributes as follows.
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
https://gvsnarasimha.blogspot.com/ 10
Date and Time
The datetime module supplies classes for manipulating dates and times in both simple and
complex ways. While date and time arithmetic is supported, the focus of the implementation is
on efficient member extraction for output formatting and manipulation. The module also
supports objects that are timezone aware.
Few methods and datamembers of datetime module are
classmethod date.today()
Return the current local date.
timedelta.min
The most negative timedelta object, timedelta(-999999999).
timedelta.max:The most positive timedelta object,
date.year
Between MINYEAR and MAXYEAR inclusive.
date.month
Between 1 and 12 inclusive.
date.day
Between 1 and the number of days in the given month of the given year.
Ex:
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2016, 9, 27)
>>> today.datetime()
>>>today.day
27
>>> today.month
9
>>> today.year
2016
>>> today.max
datetime.date(9999, 12, 31)
>>> today.min
datetime.date(1, 1, 1)4
https://gvsnarasimha.blogspot.com/ 11