Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

UNIT- 1 LECTURE-1

WHY PYTHON: Python is open source, interpreted, high level language and provides great
approach for object-oriented programming. It is one of the best language used by data
scientist for various data science projects/application. Python provide great functionality to
deal with mathematics, statistics and scientific function.

One of the main reasons why Python is widely used in the scientific and research
communities is because of its ease of use and simple syntax which makes it easy to adapt for
people who do not have an engineering background. It is also more suited for quick
prototyping.
According to engineers coming from academia and industry, deep learning frameworks
available with Python APIs, in addition to the scientific packages have made Python
incredibly productive and versatile. There has been a lot of evolution in deep learning Python
frameworks and it’s rapidly upgrading.

Reasons Why You Need to Learn Python as a Data Scientist

Simplicity: Python is one of the easiest languages to start your journey. Also, its simplicity
does not limit your functional possibilities.
What gives Python such flexibility? There are multiple factors:
Python is a free and open-source language
This is a high-level programming
Python is interpreted
It has an enormous community
In addition, Python is fast in writing. Just compare these 2 examples written in Java and
Python:
2. Scalability: Python is a programming language that scales very fast. Among all available

languages, Python is a leader in scaling. That means that Python has more and more

possibilities.

3. Libraries and Frameworks: Due to its popularity, Python has hundreds of different

libraries and frameworks which is a great addition to your development process. They save a
lot of manual time and can easily replace the whole solution.

As a Data Scientist, you will find that many of these libraries will be focused on Data
Analytics and Machine Learning. Also, there is a huge support for Big Data. I suppose there
should be a strong pro why you need to learn Python as your first language.

Some of these libraries are given below:

 Pandas

It is great for data analysis and data handling. Pandas provides data manipulation control.

 NumPy

NumPy is a free library for numerical computing. It provides high-level math functions along
with data manipulations.

 SciPy
This library is related to scientific and technical computing. SciPy can be used for data
optimization and modification, algebra, special functions, etc.

4. Web Development

To make your development process as easy as it is possible only, learn Python. There are a lot

of Django and Flask libraries and frameworks that make your coding productive and speed up
your work.

If you compare PHP and Python, you can find that the same task can be created within a few
hours of code via PHP. But with Python, it will take only a few minutes. Just take a look at

Reddit website — it was created with Python.

Here are Pythons Full Stack frameworks for web development:

 Django

 Pyramid

 Web2py

 TurboGears

And here are Pythons micro-frameworks for web development:

 Flask

 Bottle

 CherryPy

 Hug
Also, there is an alternative framework you might want to consider:

 Tornado

5. Huge Community

As I have mentioned before, Python has a powerful community. You might think that it

shouldn`t be one of the main reasons why you need to select Python. But the truth is vice

versa.

If you don`t get support from other specialists, your learning path can be difficult. That`s why

you should know that this won`t happen with your Python learning journey.
UNIT- 1 LECTURE-2

Essential Python libraries:

1. NumPy

Developed by Travis Oliphant in 2015, NumPy or Numerical Python is a fundamental library


for mathematical and scientific computations. The open-source software has functions of
linear algebra, Fourier transform, and matrix computations and is mainly used for
applications where speed and resources are important. NumPy aims to provide array objects
50x faster than traditional Python lists.

Data science libraries including SciPy, Matplotlib, Pandas, Scikit-Learn and Statsmodels are
built on top of NumPy.

2. Pandas

Developed by Wes McKinney, Pandas is used for data manipulation and analyses. It provides
fast, flexible and expressive data structures and provides features such as handling of missing
data, fancy indexing and data alignment.

Pandas provides fast, flexible and expressive data structures that helps developers work with
labelled and relational data. It is based on two main data structures– Series, and Frames.

3. Seaborn

Seaborn is Python’s most commonly used library for statistical data visualisation, used for
heatmaps and visualisations that summarise data and depict distributions. It is based on
Matplotlib and can be used on both data frames and arrays.

Seaborn is used for basic plottings– bar graph, line charts and pie charts.

4. Plotly

Plotly is a collaborative, web-based analytics and graphing platform. It is one of the most
powerful libraries for ML, data science and AI-related operations. Plotly is publication-ready
and immersive and is used for data visualisation.

Plotly can easily import data to chart, allowing developers to make slide decks and
dashboards with ease. It is used for the development of tools like Dash and Chart Studio.

5. Matplotlib

Developed by John Hunter, Matplotlib is one of the most common libraries in the Python
community. It is used for creating static, animated and interactive data visualisations.
Matplotlib provides endless customisation and charts. It enables developers to use histograms
to scatter, customise and configure plots. The open-source library offers an object-oriented
API for integrating plots into applications.
6. SciPy

SciPy or Scientific Python is used for complex mathematics, science and engineering
problems. It is built on the NumPy extension and allows developers to manipulate and
visualise data.

SciPy provides user-friendly and efficient numerical routines for linear algebra, statistics,
integration and optimisation. Its applications include multidimensional image processing,
solving Fourier transforms and differential equations.
UNIT- 1 LECTURE-3

Python Features:

1. Easy Language

Python is an easy language. It is easy to read, write, learn and understand.

 Python has a smooth learning curve. It is easy to learn.


 Python has a simple syntax and Python code is easy to understand.
 Since it’s easy to understand, you can easily read and understand someone else’s code.
 Python is also easy to write because of its simple syntax.
Because it is an easy language, it is used in schools and universities to introduce students to
programming. Python is for both startups and big companies.

2. Readable
The Python language is designed to make developers life easy. Reading a Python code is like
reading an English sentence. This is one of the key reason that makes Python best for
beginners.

Python uses indentation instead of curly braces, unlike other programming languages. This
makes the code look clean and easier to understand.

3. Interpreted Language
Python is an interpreted language. It comes with the IDLE (Interactive Development
Environment). This is an interpreter and follows the REPL structure (Read-Evaluate-Print-
Loop). It executes and displays the output of one line at a time.

So it displays errors while you’re running a line and displays the entire stack trace for the
error.

4. Dynamically-Typed Language

Python is not statically-typed like Java. You don’t need to declare data type while defining a
variable. The interpreter determines this at runtime based on the types of the parts of the
expression. This is easy for programmers but can create runtime errors.

Python follows duck-typing. It means, “If it looks like a duck, swims like a duck and quacks
like a duck, it must be a duck.”

5. Object-Oriented
Python is object-oriented but supports both functional and object-oriented programming.
Everything in Python is an object.

It has the OOP (Object-oriented programming) concepts like inheritance and polymorphism.
6. Popular and Large Community Support
Python has one of the largest communities on StackOverflow and Meetup. If you need help,
the community will answer your questions.
They also already have many answered questions about Python.

7. Open-Source
Python is open-source and the community is always contributing to it to improve it. It
is free and its source code is freely available to the public. You can download Python from
the official Python Website.

8. Large Standard Library

The standard library is large and has many packages and modules with common and
important functionality. If you need something that is available in this standard library, you
don’t need to write it from scratch. Because of this, you can focus on more important things.
You can also install packages from the PyPI (Python Package Index) if you want even more
functionality.

9. Platform-Independent
Python is platform-independent. If you write a program, it will run on different platforms
like Windows, Mac and Linux. You don’t need to write them separately for each platform.

10. Extensible and Embeddable

Python is extensible. You can use code from other languages like C++ in your Python code.
It is also embeddable. You can embed your Python code in other languages like C++.

11. GUI Support


You can use Python to create GUI (Graphical User Interfaces). You can
use tkinter, PyQt, wxPython or Pyside for this.
Python features a huge number of GUI frameworks available for it to variety of other cross-
platform solutions. It binds to platform-specific technologies.

12. High-level Language

Python is a high-level language and C++ is mid-level. It is easy to understand and closer to
the user. You don’t need to remember system architecture or manage the memory.
Python Identifier:

“An identifier is a name given to an entity”.

In very simple words, an identifier is a user-defined name to represent the basic building
blocks of Python. It can be a variable, a function, a class, a module, or any other object.
Naming Rules for Identifiers

Now you know what exactly identifiers are. So, how do we use them? We can’t use anything,
there are some certain rules to keep in mind that we must follow while naming identifiers.
The Python identifier is made with
combination of lowercase or uppercase letters, digits or an underscore.
These are the valid characters.

 Lowercase letters (a to z)
 Uppercase letters (A to Z)
 Digits (0 to 9)
 Underscore (_)
Examples of a valid identifier:
 num1
 FLAG
 get_user_name
 userDetails
 _1234
2. An identifier cannot start with a digit. If we create an identifier that starts with a digit then
we will get a syntax error.

We also cannot use special symbols in the identifiers name.

Symbols like ( !, @, #, $, %, . ) are invalid.


UNIT- 1 LECTURE-4

Reserved Keywords in Python


Reserved words (also called keywords) are defined with predefined meaning and syntax in
the language. These keywords have to be used to develop programming instructions.
Reserved words can’t be used as identifiers for other programming elements like name of
variable, function etc.
Following is the list of reserved keywords in Python 3
and except lambda with
as finally nonlocal while
assert false None yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try
Python 3 has 33 keywords while Python 2 has 30. The print has been removed from Python 2
as keyword and included as built-in function.
To check the keyword list, type following commands in interpreter −

>>> import keyword


>>> keyword.kwlist

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code.

Ex: if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Ex:

if 5 > 2:
print("Five is greater than two!")
Python Comments

Comments can be used to explain Python code. Comments can be used to make the code
more readable. Comments can be used to prevent execution when testing code. Comments
starts with a # and Python will ignore them:

#This is a comment

print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent
Python from executing code.

Built-in Data Types in Python


 Binary Types: memoryview, bytearray, bytes
 Boolean Type: bool
 Set Types: frozenset, set
 Mapping Type: dict
 Sequence Types: range, tuple, list
 Numeric Types: complex, float, int
 Text Type: str

1. Python Numbers

We can find complex numbers, floating point numbers and integers in the category of Python
Numbers. Complex numbers are defined as a complex class, floating point numbers are
defined as float and integers are defined as an int in Python. There is one more type of
datatype in this category, and that is long. It is used to hold longer integers. One will find this
datatype only in Python 2.x which was later removed in Python 3.x.
“Type()” function is used to know the class of a value or variable. To check the value for a
particular class, “isinstance()” function is used.

 Integers:
There is no maximum limit on the value of an integer. The integer can be of any length
without any limitation which can go up to the maximum available memory of the system.
 Integers can look like this:
>>> print(123123123123123123123123123123123123123123123123123 + 1)
123123123123123123123123123123123123123123123123124

 Floating Point Number:


The difference between floating points and integers is decimal points. Floating point number
can be represented as “1.0”, and integer can be represented as “1”. It is accurate up to 15
decimal places.
 Complex Number:
“x + yj” is the written form of the complex number. Here y is the imaginary part and x is the
real part.

2. Python List

An ordered sequence of items is called List. It is a very flexible data type in Python. There is
no need for the value in the list to be of the same data type. The List is the data type that is
highly used data type in Python. List datatype is the most exclusive datatype in Python for
containing versatile data. It can easily hold different types of data in Python.
It is effortless to declare a list. The list is enclosed with brackets and commas are used to
separate the items.
A list can look like this:
>>> a = [5,9.9,’list’]
One can also alter the value of an element in the list.

3. Python Tuple

A Tuple is a sequence of items that are in order, and it is not possible to modify the Tuples.
The main difference list and tuples are that tuple is immutable, which means it cannot be
altered. Tuples are generally faster than the list data type in Python because it cannot be
changed or modified like list datatype. The primary use of Tuples is to write-protect data.
Tuples can be represented by using parentheses (), and commas are used to separate the
items.
Tuples can look like this:
>>> t = (6,’tuple’,4+2r)
In the case of a tuple, one can use the slicing operator to extract the item, but it will not allow
changing the value.

4. Python Strings

A String is a sequence of Unicode characters. In Python, String is called str. Strings are
represented by using Double quotes or single quotes. If the strings are multiple, then it can be
denoted by the use of triple quotes “”” or ”’. All the characters between the quotes are items
of the string.
One can put as many as the character they want with the only limitation being the memory
resources of the machine system. Deletion or Updation of a string is not allowed in python
programming language because it will cause an error. Thus, the modification of strings is not
supported in the python programming language.
A string can look like this:
>>> s = “Python String”
>>> s = ”’a multi-string
Strings are also immutable like tuples and items can be extracted using slicing operators [].
If one wants to represent something in the string using quotes, then they will need to use
other types of quotes to define the string in the beginning and the ending.
Such as:
>>> print(“This string contains a single quote (‘) character.”)
This string contains a single quote (‘) character.
>>> print(‘This string contains a double quote (“) character.’)
This string contains a double quote (“) character.

5. Python Set

The Collection of Unique items that are not in order is called Set. Braces {} are used to
defined set and a comma is used to separate values. One will find that the items are unordered
in a set data type.
Duplicates are eliminated in a set and set only keeps unique values. Operations like
intersection and union can be performed on two sets.
Python set will look like this:
>>> a = {4,5,5,6,6,6}
>>> a
{4, 5, 6}
The slicing operator does not work on set because the set is not a collection of ordered items,
and that is why there is no meaning to the indexing of set.

6. Python Dictionary

Dictionary is a type of python data type in which collections are unordered, and values are in
pairs called key-value pairs. This type of data type is useful when there is a high volume of
data. One of the best functions of Dictionaries data type is retrieving the data for which it is
optimized. The value can only be retrieved if one knows the key to retrieve it.
Braces {} (curly brackets) are used to define dictionaries data type in Python. A Pair in the
dictionary data type is an item which is represented as key:value. The value and the key can
be of any data type.
Python Dictionary can look like this:
>>> d = {3:’key’,4:’value’}

7. Boolean Type

There can be only two types of value in the Boolean data type of Python, and that is True or
False.
It can look like this:
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>
The true value in the Boolean context is called “truthy”, and for false value in the Boolean
context, it is called “falsy”. Truthy is defined by the objects in boolean, which is equal to
True, and in the same way, Falsy is defined by the objects equal to falsy. One can also
evaluate Non-Boolean objects in a Boolean context.
UNIT- 1 LECTURE-5

Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another which
is useful in day to day and competitive programming. This article is aimed at providing
information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. To get a more clear view
of the topic see the below examples.
Example:

x = 10

print("x is of type:",type(x))

y = 10.6
print("y is of type:",type(y))

x=x+y

print(x)
print("x is of type:",type(x))

Output of the above code will be.

x is of type: <class 'int'>


y is of type: <class 'float'>
20.6
x is of type: <class 'float'>

As we can see the type od ‘x’ got automatically changed to the “float” type from the
“integer” type. this is a simple case of Implicit type conversion in python.

Explicit Type Conversion


In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. Various form of explicit type conversion are explained below:

1. int(a, base): This function converts any data type to integer. ‘Base’ specifies
the base in which string is if the data type is a string.

2. float(): This function is used to convert any data type to a floating-


point number

Example 1:

# Python code to demonstrate Type conversion

# using int(), float()

# initializing string

s = "10010"

# printing string converting to int base 2

c = int(s,2)

print ("After converting to integer base 2 : ", end="")

print (c)

# printing string converting to float

e = float(s)

print ("After converting to float : ", end="")

print (e)

After converting to integer base 2 : 18


After converting to float : 10010.0
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.\

Example 2:

# Python code to demonstrate Type conversion

# using ord(), hex(), oct()

# initializing integer

s = '4'
# printing character converting to integer

c = ord(s)

print ("After converting character to integer : ",end="")

print (c)

# printing integer converting to hexadecimal string

c = hex(56)

print ("After converting 56 to hexadecimal string : ",end="")

print (c)

# printing integer converting to octal string

c = oct(56)

print ("After converting 56 to octal string : ",end="")

print (c)

After converting character to integer : 52


After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

6. tuple() : This function is used to convert to a tuple.

7. set() : This function returns the type after converting to set.

8. list() : This function is used to convert any data type to a list type.

# Python code to demonstrate Type conversion

# using tuple(), set(), list()

# initializing string

s = 'geeks'

# printing string converting to tuple


c = tuple(s)

print ("After converting string to tuple : ",end="")

print (c)

# printing string converting to set

c = set(s)

print ("After converting string to set : ",end="")

print (c)

# printing string converting to list

c = list(s)

print ("After converting string to list : ",end="")

print (c)

After converting string to tuple : ('g', 'e', 'e', 'k', 's')


After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
UNIT- 1 LECTURE-6

Python - Decision Making


Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages −

Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.

Sr.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more statements.

2 if...else statements

An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

Let us go through each decision making briefly −


Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.
Here is an example of a one-line if clause −

#!/usr/bin/python

var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
When the above code is executed, it produces the following result −
Value of expression is 100
Good bye!

Loops and Control Statements

Python programming language provides following types of loops to handle looping


requirements.
While Loop

Syntax :

while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

# prints Hello Geek 3 Times


count = 0

while (count < 3):

count = count+1

print("Hello Geek")

Output:
Hello Geek
Hello Geek
Hello Geek
See this for an example where while loop is used for iterators. As mentioned in the article,
it is not recommended to use while loop for iterators in python.

For in Loop

In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which
is similar to for each loop in other languages.

Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over iterators and a range.

# Iterating over a list

print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)
# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)

# Iterating over a String

print("\nString Iteration")

s = "Geeks"

for i in s :

print(i)

# Iterating over dictionary

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d :
print("%s %d" %(i, d[i]))

Output:
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345
We can use for in loop for user defined iterators. See this for example.

Nested Loops

Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax:

for iterator_var in sequence:


for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as
follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of
loop. For example a for loop can be inside a while loop or vice versa.

from __future__ import print_function

for i in range(1, 5):

for j in range(i):

print(i, end=' ')

print()

Output:
1
22
333
4444
UNIT- 1 LECTURE-7

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.
Continue Statement
It returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

continue

print 'Current Letter :', letter

var = 10

Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement
It brings control out of the loop

for letter in 'geeksforgeeks':


# break the loop as soon it sees 'e'

# or 's'

if letter == 'e' or letter == 's':

break

print 'Current Letter :', letter

Output:
Current Letter : e
Pass Statement
We use pass statement to write empty loops. Pass is also used for empty control statement,
function and classes.

# An empty loop

for letter in 'geeksforgeeks':

pass

print 'Last Letter :', letter

Output:
Last Letter : s

Random Numbers in Python

Python defines a set of functions that are used to generate or manipulate random numbers
through the random module. Functions in the random module rely on a pseudo-random
number generator function random(), which generates a random float number between 0.0
and 1.0. These particular type of functions is used in a lot of games, lotteries, or any
application requiring a random number generation.

Random Number Operations


1. choice() :- choice() is an inbuilt function in the Python programming language that
returns a random item from a list, tuple, or string.
Example:
Python3

# Python3 program to demonstrate the use of

# choice() method

# import random

import random

# prints a random value from the list

list1 = [1, 2, 3, 4, 5, 6]

print(random.choice(list1))

# prints a random item from the string

string = "striver"

print(random.choice(string))

Output:
5
t
2. randrange(beg, end, step):- The random module offers a function that can generate
random numbers from a specified range and also allowing rooms for steps to be included,
called randrange().
Example:
Python

# Python code to demonstrate the working of

# choice() and randrange()

# importing "random" for random operations

import random

# using choice() to generate a random number from a

# given list of numbers.

print("A random number from list is : ", end="")

print(random.choice([1, 4, 8, 10, 3]))

# using randrange() to generate in range from 20

# to 50. The last parameter 3 is step size to skip

# three numbers when selecting.

print("A random number from range is : ", end="")

print(random.randrange(20, 50, 3))

Output:
A random number from list is : 4
A random number from range is : 41
3. random():- This method is used to generate a float random number less than 1 and
greater or equal to 0.
4. seed():- Seed function is used to save the state of a random function so that it can
generate some random numbers on multiple executions of the code on the same machine or
on different machines (for a specific seed value). The seed value is the previous value
number generated by the generator. For the first time when there is no previous value, it
uses current system time.
Example:
Python

# Python code to demonstrate the working of

# random() and seed()

# importing "random" for random operations

import random

# using random() to generate a random number

# between 0 and 1

print("A random number between 0 and 1 is : ", end="")

print(random.random())

# using seed() to seed a random number

random.seed(5)

# printing mapped random number

print("The mapped random number with 5 is : ", end="")


print(random.random())

# using seed() to seed different random number

random.seed(7)

# printing mapped random number

print("The mapped random number with 7 is : ", end="")

print(random.random())

# using seed() to seed to 5 again

random.seed(5)

# printing mapped random number

print("The mapped random number with 5 is : ", end="")

print(random.random())

# using seed() to seed to 7 again

random.seed(7)
# printing mapped random number

print("The mapped random number with 7 is : ", end="")

print(random.random())

Output:
A random number between 0 and 1 is : 0.510721762520941
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
5. shuffle():- It is used to shuffle a sequence (list). Shuffling means changing the position
of the elements of the sequence. Here, the shuffling operation is in place.
Example:
Python3

# import the random module

import random

# declare a list

sample_list = ['A', 'B', 'C', 'D', 'E']

print("Original list : ")

print(sample_list)
# first shuffle

random.shuffle(sample_list)

print("\nAfter the first shuffle : ")

print(sample_list)

# second shuffle

random.shuffle(sample_list)

print("\nAfter the second shuffle : ")

print(sample_list)

Output:
Original list :
['A', 'B', 'C', 'D', 'E']

After the first shuffle :


['A', 'B', 'E', 'C', 'D']

After the second shuffle :


['C', 'E', 'B', 'D', 'A']
6. uniform(a, b):- This function is used to generate a floating point random number
between the numbers mentioned in its arguments. It takes two arguments, lower
limit(included in generation) and upper limit(not included in generation).

Python

# Python code to demonstrate the working of

# shuffle() and uniform()


# importing "random" for random operations

import random

# Initializing list

li = [1, 4, 5, 10, 2]

# Printing list before shuffling

print("The list before shuffling is : ", end="")

for i in range(0, len(li)):

print(li[i], end=" ")

print("\r")

# using shuffle() to shuffle the list

random.shuffle(li)

# Printing list after shuffling

print("The list after shuffling is : ", end="")

for i in range(0, len(li)):


print(li[i], end=" ")

print("\r")

# using uniform() to generate random floating number in range

# prints number between 5 and 10

print("The random floating point number between 5 and 10 is : ", end="")

print(random.uniform(5, 10))

Output:
The list before shuffling is : 1 4 5 10 2
The list after shuffling is : 2 1 4 5 10
The random floating point number between 5 and 10 is : 5.183697823553464
UNIT- 1 LECTURE-8

USER DEFINES FUNCTIONS

A function is a set of statements that take inputs, do some specific computation and produce
output. The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different inputs, we
can call the function.

Functions that readily comes with Python are called built-in functions. Python provides
built-in functions like print(), etc. but we can also create your own functions. These
functions are known as user defines functions.

User defined functions

All the functions that are written by any us comes under the category of user defined
functions. Below are the steps for writing user defined functions in Python.
 In Python, def keyword is used to declare user defined functions.

 An indented block of statements follows the function name and arguments which
contains the body of the function.

Syntax:

def function_name():
statements
.
.
Example:

# Python program to
# demonstrate functions
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()

Output:

Inside function
Parameterized Function
The function may take arguments(s) also called parameters as input within the opening and
closing parentheses, just after the function name followed by a colon.
Syntax:

def function_name(argument1, argument2, ...):


statements
Example:

 Python3

# Python program to

# demonstrate functions

# A simple Python function to check

# whether x is even or odd

def evenOdd( x ):

if (x % 2 == 0):

print("even")

else:

print("odd")

# Driver code

evenOdd(2)

evenOdd(3)

Output:

even
odd
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument.The following example illustrates Default arguments.
Example:

 Python3

# Python program to demonstrate

# default arguments

def myFun(x, y = 50):

print("x: ", x)

print("y: ", y)

# Driver code (We call myFun() with only

# argument)

myFun(10)

Output:

x: 10
y: 50
Note: To know more about default arguments click here.

Keyword arguments
The idea is to allow caller to specify argument name with values so that caller does not
need to remember order of parameters.
Example:

# Python program to demonstrate Keyword Arguments

def student(firstname, lastname):


print(firstname, lastname)

# Keyword arguments

student(firstname ='Geeks', lastname ='Practice')

student(lastname ='Practice', firstname ='Geeks')

Output:

Geeks Practice
Geeks Practice

Variable length arguments


We can have both normal and keyword variable number of arguments.

 The special syntax *args in function definitions in Python is used to pass a variable
number of arguments to a function. It is used to pass a non-keyworded, variable-length
argument list.

 The special syntax **kwargs in function definitions in python is used to pass a


keyworded, variable-length argument list. We use the name kwargs with the double
star. The reason is because the double star allows us to pass through keyword arguments
(and any number of them).

Example:

# Python program to illustrate

# *args and **kwargs

def myFun1(*argv):

for arg in argv:

print (arg)
def myFun2(**kwargs):

for key, value in kwargs.items():

print ("% s == % s" %(key, value))

# Driver code

print("Result of * args: ")

myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')

print("\nResult of **kwargs")

myFun2(first ='Geeks', mid ='for', last ='Geeks')

Output:

Result of *args:
Hello
Welcome
to
GeeksforGeeks

Result of **kwargs
mid == for
first == Geeks
last == Geeks
Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference. When we pass
a variable to a function, a new reference to the object is created. Parameter passing in
Python is same as reference passing in Java. To confirm this Python’s built-in id() function
is used in below example.
Example:
# Python program to

# verify pass by reference

def myFun(x):

print("Value received:", x, "id:", id(x))

# Driver's code

x = 12

print("Value passed:", x, "id:", id(x))

myFun(x)

Output

Value passed: 12 id: 11094656


Value received: 12 id: 11094656
Output:

Value passed: 12 id: 10853984


Value received: 12 id: 10853984
If the value of the above variable is changed inside a function, then it will create a different
variable as a number which is immutable. However, if a mutable list object is modified
inside the function, the changes are reflected outside the function also.

Example:
def myFun(x, arr):
print("Inside function")

# changing integer will

# Also change the reference

# to the variable

x += 10

print("Value received", x, "Id", id(x))

# Modifying mutable objects

# will also be reflected outside

# the function

arr[0] = 0

print("List received", arr, "Id", id(arr))

# Driver's code

x = 10

arr = [1, 2, 3]

print("Before calling function")

print("Value passed", x, "Id", id(x))


print("Array passed", arr, "Id", id(arr))

print()

myFun(x, arr)

print("\nAfter calling function")

print("Value passed", x, "Id", id(x))

print("Array passed", arr, "Id", id(arr))

Output:

Before calling function


Value passed 10 Id 10853920
Array passed [1, 2, 3] Id 139773681420488

Inside function
Value received 20 Id 10854240
List received [0, 2, 3] Id 139773681420488

After calling function


Value passed 10 Id 10853920
Array passed [0, 2, 3] Id 139773681420488

Function with return value


Sometimes we might need the result of the function to be used in further process. Hence, a
function should also returns a value when it finishes it’s execution. This can be achieved by
return statement.
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after
the return statements are not executed. If the return statement is without any expression,
then the special value None is returned.
Syntax:

def fun():
statements
.
.
return [expression]
Example:

# Python program to

# demonstrate return statement

def add(a, b):

# returning sum of a and b

return a + b

def is_true(a):

# returning boolean of a

return bool(a)

# calling function
res = add(2, 3)

print("Result of add function is {}".format(res))

res = is_true(2<5)

print("\nResult of is_true function is {}".format(res))

Output:

Result of add function is 5


Result of is true function is True

You might also like