PYTHON
Dr.B.Srinivasa Rao
Assistant Professor
Department of CSE
GITAM Institute of Technology (GIT)
Visakhapatnam – 530045
25 September 2020,2:00-4:00P.M Department of CSE, GIT Course Code Computational Statistics Lab 1
FUNCTIONS
Functions are reusable pieces of programs.
They allow you to give a name to a block of
statements, allowing you to run that block
using the specified name.
We have already used built-in functions such
as len and range
Functions are defined using the def keyword
FUNCTIONS…
def sayHello():
print(‘Hello World’)
# End of function #
sayHello() # call the function
sayHello() # call the function again
Output:
Hello World!
Hello World!
FUNCTIONS…
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a)
a, b = b, a+b
fib(5)
Output:
0
1
1
2
3
PARAMETERS AND ARGUMENTS
A function can take parameters, which are
values you supply to the function so that the
function can do something utilizing those
values.
These parameters are just like variables
except that the values of these variables are
defined when we call the function
Parameters are specified within the pair of
parentheses in the function definition,
separated by commas
PARAMETERS AND ARGUMENTS…
def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
x=5
y=7
printMax(x, y)
DEFAULT ARGUMENT VALUES
For some Functions, you may want to make
some parameters optional and use default
values in case the user does not want to
provide values for them.
This is done with the help of default
argument values
You can specify default argument
values for parameters by appending to the
parameter name in the function definition
the assignment operator (=) followed by the
default value.
DEFAULT ARGUMENT VALUES…
def say(message, times = 1):
print(message * times)
say('Hello')
say('World', 5)
say(5,5)
Output:
?
KEYWORD ARGUMENTS
If you have some functions with many
parameters and you want to specify only
some of them
You can give values for such parameters by
naming them- this is called keyword
arguments
Using this function is easier since we do not
need to worry about the order of the
arguments
we can give values to only those parameters
to which we want to, provided that the other
parameters have default argument values
KEYWORD ARGUMENTS…
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
('a is', 3, 'and b is', 7, 'and c is', 10)
('a is', 25, 'and b is', 5, 'and c is', 24)
('a is', 100, 'and b is', 5, 'and c is', 50)
VARARGS PARAMETERS
Sometimes you might want to define a
function that can take any number of
parameters.
Arbitrary Argument Lists can be achieved
by using the stars.
VARARGS PARAMETERS…
def total(initial=5, *numbers,
**keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50,
fruits=100))
Output:
166
PYTHON DATA STRUCTURES
Data structures are basically just that - they
are structures which can hold some data
together. In other words, they are used to
store a collection of related data
There are popular built-in data structures in
Python
List
Tuple,
Dictionary
Set
LISTS
A list is a data structure that holds an
ordered collection of items i.e. you can store
a sequence of items in a list.
List is a sequence of values. In a string, the
values are characters; in a list, they can be
any type.
The values in a list are called elements or
sometimes items enclosed in square brackets
Once you have created a list, you can add,
remove or search for items in the list
LISTS…
A list of four integers
[10, 20, 30, 40]
A list of three strings
['crunchy frog', 'ram bladder', 'lark vomit']
A list contains a string, a float, an integer,
and (lo!) another list called nested list.
['spam', 2.0, 5, [10, 20]]
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
LISTS…
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
LISTS…
The most common way to traverse the
elements of a list is with a for loop.
>>>for cheese in cheeses:
>>>print (cheese)
Cheddar
Edam
Gouda
>>>numbers = [1, 2, 3,4,5,6]
>>>for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
>>>print (numbers)
[2, 4, 6, 8, 10, 12]
LISTS OPERATIONS…
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given
number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST METHODS…
append(x)
Add an item to the end of the list; equivalent to
a[len(a):] = [x].
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print (t)
['a', 'b', 'c', 'd']
extend(L)
Extend the list by appending all the items in the given
list; equivalent to a[len(a):] = L.
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
LIST METHODS…
sort()
Sort the items of the list, in place
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
USING LISTS AS STACKS…
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
USING LISTS AS QUEUES…
To implement a queue, use collections.deque
which was designed to have fast appends and
pops from both ends
>>> from collections import deque
>> >queue = deque(["Eric", "John", “Michael"])
>>> queue
deque(['Eric', 'John', 'Michael'])
>>> queue.append("Terry“)
>>>queue
deque(['Eric', 'John', 'Michael', 'Terry‘])
>>> queue.popleft()
’Eric’
FUNCTIONAL PROGRAMMING
TOOLS
There are three built-in functions with lists:
filter(), map(), and reduce().
filter()
filter(function, sequence) returns a sequence
consisting of those items for which
function(item) is true
>>> def f(x): return x % 2 != 0 and x %
3 != 0
filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
FUNCTIONAL PROGRAMMING
TOOLS…
map()
map(function, sequence) calls function(item)
for each of the sequence’s items and returns
a list of the return values.
For example, to compute some cubes
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729,
1000]
FUNCTIONAL PROGRAMMING
TOOLS
reduce()
reduce(function, sequence) returns a single
value constructed by calling the binary
function on the first two items of the
sequence, then on the result and the next
item, and so on
>>>def add(x,y): return x+y
>>>reduce(add, range(1, 11))
55
TUPLES
Lists are what they seem - a list of values.
Each one of them is numbered, starting from
zero - the first one is numbered zero, the
second 1, the third 2, etc. You can remove
values from the list, and add new values to
the end.
A tuple is a sequence of values. The values
can be any type, and they are indexed by
integers, so in that respect tuples are a lot
like lists. The important difference is that
tuples are immutable. Example: the names of
the months of the year
TUPLES
A tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e‘
It is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you
have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
<type 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
TUPLES
Another way to create a tuple is the built-in
function tuple. With no argument, it creates
an empty tuple
>>> t = tuple()
>>> print(t)
()
If the argument is a sequence (string, list or
tuple), the result is a tuple with the elements
of the sequence:
>>> t = tuple('lupins')
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
TUPLES
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'
And the slice operator selects a range of elements.
>>> print(t[1:3])
('b', 'c')
But if you try to modify one of the elements of the
tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
You can’t modify the elements of a tuple, but you can
replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e')
SETS
Python also includes a data type for sets.
A set is an unordered collection with no
duplicate elements.
Basic uses include membership testing and
eliminating duplicate entries.
Set objects also support mathematical
operations like union, intersection,
difference, and symmetric difference.
SETS
>>> basket = [’apple’, ’orange’, ’apple’, ’pear’,
’orange’, ’banana’]
>>> fruit = set(basket)
>>> fruit
set([’orange’, ’pear’, ’apple’, ’banana’])
>>> ’orange’ in fruit
True
>>> ’crabgrass’ in fruit
False
SETS
>>> a = set(’abracadabra’)
>>> b = set(’alacazam’)
>>> a
set([’a’, ’r’, ’b’, ’c’, ’d’])
>>> a - b
set([’r’, ’d’, ’b’])
>>> a | b
set([’a’, ’c’, ’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
>>> a & b
set([’a’, ’c’])
>>> a ^ b # letters in a or b but not both
set([’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
DICTIONARIES
A dictionary is like a list, but more general. In
a list, the indices have to be integers; in a
dictionary they can be (almost) any type.
You can think of a dictionary as a mapping
between a set keys and a set of values.
Each key maps to a value called a key-value
pair or sometimes an item.
A pair of braces creates an empty dictionary:
{}
>>> k={}
>>> type(k)
<type 'dict'>
DICTIONARIES
The function dict creates a new dictionary
with no items.
Because dict is the name of a built-in
function you should avoid using it as a
variable name
>>> eng2sp = dict()
>>> print(eng2sp)
{}
This squiggly-brackets, {}, represent an
empty dictionary
DICTIONARIES
To add items to the dictionary, you can use
square brackets
>>> eng2sp['one'] = 'uno‘
This line creates an item that maps from the
key 'one' to the value 'uno'.
If we print the dictionary we see a key-value
pair with a colon between the key and value
>>> print (eng2sp)
{'one': 'uno'}
DICTIONARIES
>>> eng2sp = {'one': 'uno', 'two': 'dos',
'three': 'tres'}
But if you print eng2sp, you might be
surprised:
>>> print(eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
In general, the order of items in a dictionary is
unpredictable
But that’s not a problem because the elements
of a dictionary are never indexed with integer
indices
DICTIONARIES
>>> print(eng2sp['two'])
'dos'
The key 'two' always maps to the value 'dos'
so the order of the items doesn’t matter.
If the key isn’t in the dictionary, you get an
exception:
>>> print(eng2sp['four'])
KeyError: 'four'
The len function works on dictionaries; it
returns the number of key-value pairs:
>>> len(eng2sp)
3
DICTIONARIES
The in operator works on dictionaries
>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
LOOPING OVER DICTIONARIES
>>> h = histogram('brontosaurus')
>>> print h
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2,
't': 1}
The histogram indicates that the letters 'a'
and 'b' appear once; 'o' appears twice, and
so on.
def print_hist(h):
for c in h:
print(c, h[c])
DICTIONARIES
>>> h = histogram('parrot')
>>> print(hist(h))
a1
p1
r2
t1
o1
Again, the keys are in no particular order.
Dictionaries have a method called keys that
returns the keys of the dictionary