UNIT IV
Python: Introduction to Python - Introduction to Google Colab
Basic Data Types: Integers, Floating Points, Boolean types
Working with String functions - Working with Input, Output functions -
Python-Single and Multi-line Comments/ Error Handling -
Conditional & Looping Statements : If, for, while statements
- Working with List structures - Working with Tuples data structures -
Working with Sets - Working with Dictionaries
- Introduction to Python Libraries - Introduction to Numpy - High
Dimensional Arrays
INTRODUCTION TO PYTHON
• Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
• It was created by Guido van Rossum during 1985- 1990.
• Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000
• Python is interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it.
• Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for the
beginner- level programmers and supports the development of a wide range of
applications.
Python Features(Technical Strength of Python)
• Easy-to-learn: Python is clearly defined and easily readable. The structure of the
program is very simple. It uses few keywords.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Interpreted: Python is processed at runtime by the interpreter. So, there is no need to
compile a program before executing it. You can simply run the program.
• Extensible: Programmers can embed python within their C,C++,Java script ,ActiveX, etc.
• Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
• High Level Language: When writing programs, programmers concentrate on solutions of
the current problem, no need to worry about the low level details.
• Scalable: Python provides a better structure and support for large programs than shell
scripting.
Applications
Python Interpreter
• Interpreter: To execute a program in a high-level language by translating it one
line at a time.
• Compiler: To translate a program written in a high-level language into a low
level language all at once, in preparation for later execution.
MODES OF PYTHON INTERPRETER
• Python Interpreter is a program that reads and
executes Python code.
• It uses 2 modes of Execution.
– Interactive mode
– Script mode
[Link] mode
• Interactive Mode, as the name suggests, allows us to interact with OS
• When we type Python statement, interpreter displays the
result(s) immediately.
Advantages:
v Python, in interactive mode, is good enough to learn, experiment or
explore.
v Working in interactive mode is convenient for beginners and for testing
small pieces of code.
Drawback:
v We cannot save the statements and have to retype all the statements once
again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter
code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
Working Modes of Python –
Interactive Mode
• You can also get help with regards to a particular command in interactive
mode. Just type the help() command on the shell and then hit the enter
key. You will see the following:
Working Modes of Python –
Interactive Mode
Working Modes of Python –
Interactive Mode
21CSS101J PROGRAMMING FOR PROBLEM
11
SOLVING - UNIT IV
2. Script mode:
• In script mode, we type python program in a file and then use
interpreter to execute the content of the file.
• Scripts can be saved to disk for future use. Python scripts
have the extension .py, meaning that the filename ends
with .py
• Save the code with [Link] and run the interpreter in
script mode to execute the script.
Run Python Code in Script Mode
In order to run a code in script mode follow the following steps.
• Step 1: Make a file using a text editor. You can use any text editor of your
choice(Here I use notepad).
• Step 2: After writing the code save the file using “.py” extension.
• Step 3: Now open the command prompt and command directory to the
one where your file is stored.
• Step 4: Type python “[Link]” and press enter.
• Step 5: You will see the output on your command prompt.
Run Python Code in Script Mode
Integrated Development Learning Environment
(IDLE):
• Is a graphical user interface which is completely written in
Python.
• It is bundled with the default implementation of the python
.
language and also comes with optional part of the Python
packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting
Introduction to Google Colab
Google Colab ([Link]
Google Colaboratory, commonly known as Google Colab, is a free, cloud-based platform that
allows users to write and execute Python code directly in their web browsers. It's particularly
popular among data scientists, machine learning practitioners, and educators due to its
accessibility and robust features.
• Key Features of Google Colab:
– No Setup Required: Start coding immediately without any local configuration.
– Free Access to GPUs and TPUs: Leverage powerful hardware accelerators for computational
tasks at no cost.
– Seamless Collaboration: Share notebooks effortlessly with others, enabling real-time
collaboration.
– Integration with Google Drive: Save and manage your notebooks directly within your Google
Drive.
– Pre-installed Libraries: Access a wide range of popular Python libraries without additional
installations.
Getting Started with Google Colab:
1. Accessing Colab:
– Visit Google Colab and sign in with your Google account.
2. Creating a New Notebook:
– Click on "File" > "New Notebook" to start a new project.
3. Writing and Executing Code:
– Enter Python code into the provided cells and execute them by pressing Shift + Enter or
clicking the play button.
4. Utilizing Hardware Accelerators:
– Navigate to "Runtime" > "Change runtime type" and select either GPU or TPU to
enhance computational performance.
5. Saving and Sharing Notebooks:
– Notebooks are automatically saved to your Google Drive.
– To share, click the "Share" button and set the desired permissions for collaborators.
Features
• Free Access to GPUs and TPUs: Colab provides free access to GPUs and TPUs, which
can significantly speed up computations, especially for tasks involving deep learning.
• Easy Sharing and Collaboration: Notebooks can be easily shared and collaborated
on, similar to Google Docs. This makes it convenient for group projects and collaborative
research.
• Pre-installed Libraries: Many popular Python libraries (such as TensorFlow, PyTorch,
and NumPy) are pre-installed, saving time and effort in setting up the environment.
Features
• Integration with Google Drive: Colab integrates seamlessly with Google Drive, allowing
users to save and load notebooks directly from their Drive, making file management
straightforward.
• Interactive Visualizations: Colab supports various visualization libraries like Matplotlib,
Plotly, and Seaborn, enabling interactive data exploration and presentation.
• Free and Accessible: Being a free service, Colab lowers the barrier to entry for individuals
and organizations without the resources to afford expensive computational infrastructure.
Getting Started with Colab
• To get started with Google Colab, you can visit Google Colab and sign in with your Google account.
Getting Started with Colab
• Give the name of the new Notebook as [Link]. By default, the extension is ipynb (Interactive Python
Notebook).
Getting Started with Colab
• Give the name of the new Notebook as [Link]. By default, the extension is ipynb (Interactive Python
Notebook).
Basic Data Types
21CSS101J PROGRAMMING FOR PROBLEM
24
SOLVING - UNIT IV
Statements and expressions
• A statement is an instruction that the Python interpreter can execute.
• A statement is a unit of code like creating a variable or displaying a
value.
• When you type a statement on the command line, Python executes it.
>>> n = 17does not display any results.
The interpreter
>>> print(n)
• An expression is a combination of values, variables, and operators.
• If you type an expression at the Python prompt, the
>>> a+3+2
interpreter evaluates
7 it and displays the result, which is always a value:
>>> z=("hi"+"friend")
>>> print(z)
Hifriend
Expression
• Expressions always returns a value
• Functions are also expressions. Even a non returning function
will still return value, so it is an expression.
• Can print the result value
21CSS101J PROGRAMMING FOR PROBLEM
26
SOLVING - UNIT IV
Expression
21CSS101J PROGRAMMING FOR PROBLEM
27
SOLVING - UNIT IV
Expression
21CSS101J PROGRAMMING FOR PROBLEM
28
SOLVING - UNIT IV
Statements
• A statement never returns a value
• Cannot print any result
• Examples Of Python Statements: Assignment statements, conditional
branching, loops, classes, import, def, try, except, pass, del etc
• Python statements are the code instructions that are executed by the
Python interpreter.
21CSS101J PROGRAMMING FOR PROBLEM
29
SOLVING - UNIT IV
Statements
21CSS101J PROGRAMMING FOR PROBLEM
30
SOLVING - UNIT IV
Values and Types
• A value is one of the most basic things in any program works with.
• A value may be characters i.e. ‘Hello, World!’ or a number like 1,2.2 ,3.5
etc.
• Values belong to different types: 1 is an integer, 2 is a float and ‘Hello,
World!’ is a string etc.
21CSS101J PROGRAMMING FOR PROBLEM
31
SOLVING - UNIT IV
Values and Types
21CSS101J PROGRAMMING FOR PROBLEM
32
SOLVING - UNIT IV
VALUES AND DATA TYPES
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values
Python has four standard data types:
Numbers:
• Number data type stores Numerical Values.
• This data type is immutable [i.e. values/items cannot be changed].
• Python supports integers, floating point numbers and complex numbers.
They are defined as
Numeric Types
• In Python, numeric data type represent the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers.
These values are defined as int, float and complex class in Python.
• Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fraction or decimal). In Python there is
no limit to how long an integer value can be.
21CSS101J PROGRAMMING FOR PROBLEM
35
SOLVING - UNIT IV
Numeric Types
• Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point. Optionally,
the character e or E followed by a positive or negative integer may be
appended to specify scientific notation.
• Complex Numbers – Complex number is represented by complex class.
It is specified as (real part) + (imaginary part)j. For example – 2+3j
21CSS101J PROGRAMMING FOR PROBLEM
36
SOLVING - UNIT IV
Numeric Types
21CSS101J PROGRAMMING FOR PROBLEM
37
SOLVING - UNIT IV
Numeric Types
21CSS101J PROGRAMMING FOR PROBLEM
38
SOLVING - UNIT IV
Basic DataTypes
1. Integers (int): Integers are whole numbers without a fractional
component. They can be positive, negative, or zero.
Python supports integers of arbitrary precision, meaning they can be
as large as the memory allows.
# Examples of integers
positive_int = 42
negative_int = -7
zero = 0
2. Floating-Point Numbers (float): Floating point numbers represent
real numbers with decimal points, allowing fractional values. They
can be positive, negative, or zero.
# Examples of floating-point numbers
positive_float = 3.14
negative_float = -0.001
zero_float = 0.0
3. Booleans (bool): Booleans represent one of two values:
True or False. They are commonly used in conditional
statements and logical operations.
# Examples of booleans
is_active = True
has_access = False
But non-Boolean objects can be evaluated in Boolean context as
well and determined to be true or false. It is denoted by the
class bool.
Set
• Python Set is the unordered collection of the data type.
• It is iterable, mutable(can modify after creation), and has unique
elements.
• In set, the order of the elements is undefined; it may return the changed
sequence of the element.
• The set is created by using a built-in function set(), or a sequence of
elements is passed in the curly braces and separated by the comma.
• It can contain various types of values.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 42
Contd..
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 43
x = 20.5
print(type(x))
y=5
Guess the y=____ (y)
output… fruits = {"apple", "banana", "cherry"}
print(type(fruits))
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 44
Assignments
• In Python, you can create floating-point numbers using different formats. For
example:
• 4. represents a floating-point number with an integer part but no decimal part, which defaults to
__________
• .2 represents a floating-point number with no integer part, which defaults to_________
• Write a Python program to represent different values in List and Tuple.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 45
Sequence
• A sequence is an ordered collection of items, indexed by positive
integers.
• It is a combination of mutable (value can be changed) and
immutable (values cannot be changed) data types.
• There are three types of sequence data type available in Python, they
are
1. Strings
2. Lists
3. Tuples
1. Strings
• A String in Python consists of a series or sequence of characters -
letters, numbers, and special characters.
• Strings are marked by quotes:
– single quotes (' ') Eg, 'This a string in single quotes‘
– double quotes (" ") Eg, "'This a string in double quotes'“
– triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines
and sentences.""“
Individual character in a string is accessed using a subscript (index).
Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
In python there is no character data type, a character is a string of length one. It
• Positive indexing helps in accessing the string from the beginning.
• Negative subscript helps in accessing the string from the end.
• Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
• Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Built-in String Functions
Python includes the following some built-in methods to manipulate strings
1) capitalize() : Python String capitalize() method returns a copy of the string with only its first character
capitalized.
e.g.: str = "this is string example....wow!!!";
print [Link]()
O/P: This is string example....wow!!!
2) center() : Python string method center() returns centered in a string of length width. Padding is done using
the specified fillchar. Default filler is a space.
Syntax: [Link](width [, fillchar])
e.g.: str = "this is string example....wow!!!"
print [Link](40,'@’)
O/P: @@@@this is string example....wow!!!@@@@
21CSS101J PROGRAMMING FOR PROBLEM S 50
OLVING - UNIT IV
Built-in String Functions
3. count():- Python string method count() returns the number of occurrences of substring sub in the
range [start, end]. Optional arguments start and end are interpreted as in slice notation.
Syntax: [Link](sub, start, end)
Parameters: sub − This is the substring to be searched.
start − Search starts from this index. By default search starts from 0 index.
end − Search ends from this index. By default search ends at the last index.
e.g.: str = "this is string example....wow!!!“
sub = "i"
print sub, „ counts „, [Link](sub, 4, 40)
sub = "wow"
print sub, „ counts „, [Link](sub)
O/P: i counts 2 wow counts 1
21CSS101J PROGRAMMING FOR PROBLEM S 51
OLVING - UNIT IV
Built-in String Functions
4) find():- Python string method find() determines index, if string str occurs in string, or in a substring of string
if starting index beg and ending index end are given.
Syntax: [Link](str, beg, end)
This method return index number if str found otherwise -1.
e.g: str1 = "this is string example....wow!!!“
str2 = "exam"
print [Link](str2)
print [Link](str2, 10)
print [Link](str2, 40)
O/P: 15 15 -1
21CSS101J PROGRAMMING FOR PROBLEM S 52
OLVING - UNIT IV
Built-in String Functions
[Link]():- Python string method islower() checks whether all the case-based characters (letters) of the
string are lowercase.
Syntax: [Link]()
e.g.1: str = "THIS is string example....wow!!!"
print [Link]()
O/P: False
e.g.2: str = "this is string example....wow!!!"
print [Link]()
O/P: True
21CSS101J PROGRAMMING FOR PROBLEM S 53
OLVING - UNIT IV
Built-in String Functions
6. isupper():- Python string method isupper() checks whether all the casebased characters (letters) of
the string are uppercase.
Syntax: [Link]()
e.g.1: str = "THIS IS STRING EXAMPLE....WOW!!!"
print [Link]()
O/P: True
e.g.2: str = “THIS is string example....wow!!!"
print [Link]()
O/P: False
21CSS101J PROGRAMMING FOR PROBLEM S 54
OLVING - UNIT IV
Built-in String Functions
7. join(): Python string method join() returns a string in which the string elements of sequence have
been joined by str separator.
Syntax: [Link](sequence)
e.g.: s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print [Link](seq)
O/P: a-b-c
8. len():- Python string method len() returns the length of the string.
Syntax: len(str)
e.g.: str = "this is string example....wow!!!"
print "Length of the string: ",
len(str)
O/P: Length of the string: 32
21CSS101J PROGRAMMING FOR PROBLEM S 55
OLVING - UNIT IV
Built-in String Functions
9. lower() :- Python string method lower() returns a copy of the string in which all case-based
characters have been lowercased.
Syntax: [Link]()
e.g: str = "THIS IS STRING EXAMPLE....WOW!!!"
print [Link]()
O/P: this is string example....wow!!!
10. upper() :- Python string method upper() returns a copy of the string in which all case-based
characters have been uppercased.
Syntax: [Link]()
e.g.: str = " this is string example....wow!!!”
print [Link]()
O/P: THIS IS STRING EXAMPLE....WOW!!!
21CSS101J PROGRAMMING FOR PROBLEM S 56
OLVING - UNIT IV
Strings:
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
String built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method
[Link]()
a=”happy birthday”
here, a is the string name.
String modules:
v
A module is a file containing Python definitions, functions, statements.
v
Standard library of Python is extended as modules.
v
To use these modules in a program, programmer needs to import the module.
v
Once we import a module, we can reference or use to any of its functions or variables in our code.
v
There is large number of standard modules also available in python.
v
Standard modules can be imported the same way as we import our user-defined modules.
Syntax: Example
import module_name import string
print([Link])
print([Link])
print([Link])
print([Link]("happy birthday"))
print([Link])
print([Link])
Working with Input, Output functions
In Python, input( ) function is used to accept data as input at
run time. The syntax for input() function is,
Variable = input (“prompt string”)
Where, prompt string in the syntax is a statement or message
to the user, to know what input can be given.
21CSS101J PROGRAMMING FOR PROBLEM S 61
OLVING - UNIT IV
Cont…
•If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the input
device.
•The input( ) takes whatever is typed from the keyboard and stores the entered data in the given variable.
•If prompt string is not given in input( ) no message is displayed on the screen, thus, the user will not know
what is to be typed as input.
21CSS101J PROGRAMMING FOR PROBLEM S 62
OLVING - UNIT IV
Cont…
Example 1:input( ) with prompt string
>>>city=input (“Enter Your City: ”)
Enter Your City:Madurai
>>>print (“I am from “, city)
I am from Madurai
Example 2:input( ) without prompt string
>>> city=input()
Rajarajan
>>> print (I am from", city)
I am from Rajarajan
21CSS101J PROGRAMMING FOR PROBLEM S 63
OLVING - UNIT IV
Output Functions
•print() function prints the message to the screen or any other standard output device
Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
•value(s): Any value, and as many as you like. Will be converted to a string before
printed
•sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
[Link] :’ ‘
•end=’end’: (Optional) Specify what to print at the [Link] : ‘\n’
•file : (Optional) An object with a write method. Default :[Link]
•flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
21CSS101J PROGRAMMING FOR PROBLEM S 64
OLVING - UNIT IV
Output Functions
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
O/P: Name: John
Age: 30
21CSS101J PROGRAMMING FOR PROBLEM S 65
OLVING - UNIT IV
Coding Assignments
• Write a Python program to remove duplicates from a list.
• Write a Python program to print a specified list after removing the 0th, 4th
and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow’]
Expected Output : ['Green', 'White', 'Black’]
• Write a Python program to find the list of words that are longer than length
of the list.
• Write a Python program to get the smallest number from a list.
• Write a python code to display a table of 10 using List Comprehension
21CSS101J PROGRAMMING FOR PROBLEM
66
SOLVING - UNIT IV
2. Lists
List is an ordered sequence of items.
Values in the list are called elements /
items.
It can be written as a list of comma-
separated items (values)
between square brackets[ ].
Items in the lists can be of different
data types.
Operations on list:
• Indexing
• Slicing
• Concatenation
• Repetitions
• Updation, Insertion, Deletion
List
• A 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.
• It can be written as a list of comma-separated items (values)
between square brackets[ ].
• Items in the lists can be of different data types.
• Lists are used to store multiple items in a single variable.
21CSS101J PROGRAMMING FOR PROBLEM
68
SOLVING - UNIT IV
Creating a List
21CSS101J PROGRAMMING FOR PROBLEM S 69
OLVING - UNIT IV
Contd..
21CSS101J PROGRAMMING FOR PROBLEM S 70
OLVING - UNIT IV
Adding Elements to a List (Append())
21CSS101J PROGRAMMING FOR PROBLEM S 71
OLVING - UNIT IV
Adding Elements to a List (Append())
21CSS101J PROGRAMMING FOR PROBLEM S 72
OLVING - UNIT IV
Adding Elements to a List using Iterator
21CSS101J PROGRAMMING FOR PROBLEM S 73
OLVING - UNIT IV
Adding Elements to a List using Iterator
21CSS101J PROGRAMMING FOR PROBLEM S 74
OLVING - UNIT IV
Adding Elements to a List using insert()
21CSS101J PROGRAMMING FOR PROBLEM S 75
OLVING - UNIT IV
Adding Elements to a List using extend()
21CSS101J PROGRAMMING FOR PROBLEM S 76
OLVING - UNIT IV
List Indexing
21CSS101J PROGRAMMING FOR PROBLEM S 77
OLVING - UNIT IV
List Slicing
21CSS101J PROGRAMMING FOR PROBLEM S 78
OLVING - UNIT IV
List Slicing
21CSS101J PROGRAMMING FOR PROBLEM S 79
OLVING - UNIT IV
Concatenation & Repetition
• We can also use + operator to combine two lists. This is also called concatenation.
• The * operator repeats a list for the given number of times.
21CSS101J PROGRAMMING FOR PROBLEM S 80
OLVING - UNIT IV
Delete / Remove List
21CSS101J PROGRAMMING FOR PROBLEM S 81
OLVING - UNIT IV
Delete / Remove List
21CSS101J PROGRAMMING FOR PROBLEM S 82
OLVING - UNIT IV
Delete / Remove List
21CSS101J PROGRAMMING FOR PROBLEM S 83
OLVING - UNIT IV
Delete / Remove List
21CSS101J PROGRAMMING FOR PROBLEM S 84
OLVING - UNIT IV
List Methods
21CSS101J PROGRAMMING FOR PROBLEM S 85
OLVING - UNIT IV
List Methods
21CSS101J PROGRAMMING FOR PROBLEM S 86
OLVING - UNIT IV
List Traversal / Looping
21CSS101J PROGRAMMING FOR PROBLEM S 87
OLVING - UNIT IV
List Traversal / Looping
21CSS101J PROGRAMMING FOR PROBLEM S 88
OLVING - UNIT IV
List Mutability
21CSS101J PROGRAMMING FOR PROBLEM S 89
OLVING - UNIT IV
List Aliasing
21CSS101J PROGRAMMING FOR PROBLEM S 90
OLVING - UNIT IV
List Aliasing
21CSS101J PROGRAMMING FOR PROBLEM S 91
OLVING - UNIT IV
List Aliasing
21CSS101J PROGRAMMING FOR PROBLEM S 92
OLVING - UNIT IV
List Cloning
• To avoid the disadvantages of copying we are using
cloning. creating a copy of a same list of elements with
two different memory locations is called cloning.
• Changes in one list will not affect locations of another
list.
21CSS101J PROGRAMMING FOR PROBLEM S 93
OLVING - UNIT IV
Cloning using Slicing
21CSS101J PROGRAMMING FOR PROBLEM S 94
OLVING - UNIT IV
Cloning using List( ) method
21CSS101J PROGRAMMING FOR PROBLEM S 95
OLVING - UNIT IV
Cloning using copy() method
21CSS101J PROGRAMMING FOR PROBLEM S 96
OLVING - UNIT IV
List as Parameters
• In python, arguments are passed by reference.
• If any changes are done in the parameter which refers within the
function, then the changes also reflects back in the calling function.
• Passing a list as an argument actually passes a reference to the list,
not a copy of the list.
• Since lists are mutable, changes made to the elements referenced by
the parameter change the same list that the argument is referencing.
21CSS101J PROGRAMMING FOR PROBLEM S 97
OLVING - UNIT IV
List as Parameters
21CSS101J PROGRAMMING FOR PROBLEM S 98
OLVING - UNIT IV
List as Parameters
21CSS101J PROGRAMMING FOR PROBLEM S 99
OLVING - UNIT IV
List as Parameters
21CSS101J PROGRAMMING FOR PROBLEM S 100
OLVING - UNIT IV
List Comprehension
• List comprehensions are used for creating new lists
from other iterables like tuples, strings, arrays, lists,
etc.
21CSS101J PROGRAMMING FOR PROBLEM S 101
OLVING - UNIT IV
List Comprehension
21CSS101J PROGRAMMING FOR PROBLEM S 102
OLVING - UNIT IV
List Comprehension
21CSS101J PROGRAMMING FOR PROBLEM S 103
OLVING - UNIT IV
List Comprehension
21CSS101J PROGRAMMING FOR PROBLEM S 104
OLVING - UNIT IV
List as array:
Array:
Array is a collection of similar elements. Elements in the array can be accessed by index. Index starts with 0.
Array can be handled in python by module named array.
To create array have to import array module in the program.
Example: Program to find sum of
Syntax : array elements
import array
import array
Syntax to create array:
sum=0
Array_name = module_name.function_name(‘datatype’,[elements]) a=[Link]('i',[1,2,3,4])
for i in a:
Example: sum=sum+i
a=[Link](‘i’,[1,2,3,4]) print(sum)
a- array name Output
array- module name 10
i- integer datatype
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
[Link](list_name)
Example
program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=[Link]('i',[])
[Link](l)
for i in a:
sum=sum+i
print(sum)
Output
35
Methods in array
a=[2,3,4,5]
Example: 1 Example: 2
Square root using newtons method GCD of two numbers
def newtonsqrt(n): n1=int(input("Enter a number1:"))
root=n/2 n2=int(input("Enter a number2:"))
for i in range(10):
root=(root+n/root)/2 for i in range(1,n1+1):
print(root) if(n1%i==0 and n2%i==0):
gcd=i
n=eval(input("enter number to find Sqrt: print(gcd)
"))
newtonsqrt(n) output
Enter a number1:8
Output: Enter a number2:24
enter number to find Sqrt: 9 8
3.0
Example: 3 Example: 4
Exponent of number sum of array elements
def power(base,exp): a=[2,3,4,5,6,7,8]
if(exp==1): sum=0
return(base) for i in a:
else: sum=sum+i
return(base*power(base,exp-1)) print("the sum is",sum)
base=int(input("Enter base: ")) output:
exp=int(input("Enter exponential value:")) the sum is 35
result=power(base,exp)
print("Result:",result)
Output:
Enter base: 2
Enter exponential value:3
Result: 8
Guess the
output… a= ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
print(max(a[2:4] + ['grault’]))
print(a[4::-2])
21CSS101J PROGRAMMING FOR PROBLEM
110
SOLVING - UNIT IV
Guess the
output…
21CSS101J PROGRAMMING FOR PROBLEM
111
SOLVING - UNIT IV
Assignments
• Write a Python program to remove duplicates from a list.
• Write a Python program to print a specified list after removing the 0th, 4th and 5th
elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow’]
Expected Output : ['Green', 'White', 'Black’]
• Write a Python program to find the list of words that are longer than length of the list.
• Write a Python program to get the smallest number from a list.
• Write a python code to display a table of 10 using List Comprehension
21CSS101J PROGRAMMING FOR PROBLEM
112
SOLVING - UNIT IV
3. Tuple:
v A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square brackets.
v A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove
elements from the tuple.
Benefit of Tuple:
v Tuples are faster than lists.
v If the user wants to protect the data from accidental changes, tuple can be used.
v Tuples can be used as keys in dictionaries, while lists can't.
Altering the tuple data type leads to error.
Following error occurs when user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Tuples
and Project
Management
(SEPM)
115
Tuple Creation
# Empty tuple
• A tuple is created by placing all the items (elements) inside my_tuple = ()
print(my_tuple)
parentheses (), separated by commas. The parentheses are
optional, however, it is a good practice to use them.
# Tuple having integers
• A tuple can have any number of items and they may be of my_tuple = (1, 2, 3)
print(my_tuple)
different types (integer, float, list, string, etc.).
# tuple with mixed datatypes
Output:
my_tuple = (1, "Hello", 3.4)
()
print(my_tuple)
(1, 2, 3)
(1, 'Hello', 3.4)
# nested tuple
('mouse', [8, 4, 6], (1, 2, 3),{‘a’, ‘b’})
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3),{‘a’, ‘b’})
my_tuple[0] <class 'str'>
print(my_tuple)
my_tuple[1] <class 'list'>
my_tuple[2] <class 'tuple'> and Project
print("my_tuple[0]",type(my_tuple[0]))
my_tuple[3] <class 'set'> Management
(SEPM) print("my_tuple[1]",type(my_tuple[1]))
print("my_tuple[2]",type(my_tuple[2]))
print("my_tuple[3]",type(my_tuple[3]))
116
Accessing Tuples
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
Access Tuple Elements print(my_tuple[5]) # 't'
There are various ways in which we can access the elements of
a tuple. # IndexError: list index out of range
Indexing # print(my_tuple[6])
We can use the index operator [] to access an item in a tuple,
# Index must be an integer
where the index starts from 0. # TypeError: list indices must be integers, not float
So, a tuple having 6 elements will have indices from 0 to 5.
# my_tuple[2.0]
Trying to access an index outside of the tuple index
# nested tuple
range(6,7,... in this example) will raise an IndexError. n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
The index must be an integer, so we cannot use float or
# nested index
other types. This will result in TypeError. print(n_tuple[0][3]) # 's'
Likewise, nested tuples are accessed using nested indexing,
and Project print(n_tuple[1][1]) #4
as shown in the example below. Management
(SEPM)
Output:
pts4
117
Joining and Replicating Tuples
Operator Description Example
Repetition/ The repetition operator enables T1*2 = (1, 2, 3, 4, 5, 1, 2,
Replicating the tuple elements to be 3, 4, 5)
repeated multiple times.
Concatenation It concatenates the tuple T1+T2 = (1, 2, 3, 4, 5, 6,
mentioned on either side of the 7, 8, 9)
operator.
Membership It returns true if a particular item print (2 in T1) prints True.
exists in the tuple otherwise false
Iteration The for loop is used to iterate for i in T1:
over the tuple elements. print(i)Output1 2 3 4 5
Length It isand
used to get the length of the len(T1) = 5
Project
tuple.
Management
(SEPM)
118
Tuple Indexing
The indexing and slicing in the tuple are similar to lists. The
indexing in the tuple starts from 0 and goes to length(tuple)
- 1.
The items in the tuple can be accessed by using the index []
operator. Python also allows us to use the colon operator to
access multiple items in the tuple.
Consider the following image to understand the indexing
and slicing in detail.
and Project
Management
(SEPM)
119
Tuple Indexing
and Project
Management
(SEPM)
120
Tuple Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
and Project
Management
(SEPM)
121
Tuples Slicing
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
# Output: ('r', 'o', 'g') Output:
print(my_tuple[1:4]) ('r', 'o', 'g')
# elements beginning to 2nd ('p', 'r')
# Output: ('p', 'r') ('i', 'z')
print(my_tuple[:-7]) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# elements 8th to end
# Output: ('i', 'z')
print(my_tuple[7:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
and Project
Management
print(my_tuple[:]) (SEPM)
122
Tuple operations
and Project
Management
(SEPM)
123
Example
# Code to create a tuple with repetition
# Code for creating nested tuples
tuple3 = ('python',)*3
tuple1 = (0, 1, 2, 3)
print(tuple3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
Output:
print(tuple3)
('python', 'python', 'python')
((0, 1, 2, 3), ('python', 'geek'))
# Code for deleting a tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Traceback (most recent call last):
File "[Link]", line 6, in <module>
and Project
print(tuple3) Management
NameError: name 'tuple3' is not defined (SEPM)
124
Example-Using cmp(), max() , min()
# A python program to demonstrate the use of
# cmp(), max(), min()
tuple1 = ('python', 'geek') Output
tuple2 = ('coder', 1) Not the same
if (cmp(tuple1, tuple2) != 0): Maximum element in tuples 1,2:
# cmp() returns 0 if matched, 1 when not tuple1 python,coder
# is longer and -1 when tuple1 is shorter Minimum element in tuples 1,2:
print('Not the same') geek,1
else:
print('Same')
print ('Maximum element in tuples 1,2: ' +
str(max(tuple1)) + ',' +
str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' +
and Project
str(min(tuple1)) + ',' + str(min(tuple2)))
Management
(SEPM)
125
Mapping
• This data type is unordered and mutable.
• Dictionaries fall under Mappings
Dictionaries:
v Lists are ordered sets of objects, whereas dictionaries are unordered sets.
v Dictionary is created by using curly brackets. i,e. {}
v Dictionaries are accessed via keys and not via their position.
v A dictionary is an associative array (also known as hashes). Any key of
the dictionary is associated (or mapped) to a value.
v The values of a dictionary can be any Python data type. So dictionaries are
Dictionaries in Python
• Dictionary is mutable and is another container type that can store any number of Python objects,
including other container types. Dictionaries consist of pairs (called items) of keys and their
corresponding values.
• Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows:
• Keys are unique within a dictionary while values may not be. The values of a dictionary can be of
any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
21CSS101J PROGRAMMING FOR PROBLEM
127
SOLVING - UNIT IV
21CSS101J PROGRAMMING FOR PROBLEM
128
SOLVING - UNIT IV
Updating & Deleting the Contents of a
Dictionary
• #updating the dictionary
dict = {‘Name’: ‘SELVAM’, ‘Age’:20, ‘Dept’: ‘IT’}
dict [‘Age’] = 18
dict [‘Dept’] = ‘CinTel’
• #Deleting the dictionary
– dict = {‘Name’: ‘SELVAM’, ‘Age’:20, ‘Dept’: ‘IT’}
– del dict[‘Age’] # removes the entry with key Age
– [Link]() # removes all the entries in the dictionary
– del dict # removes the entire dictionary object dict
21CSS101J PROGRAMMING FOR PROBLEM
129
SOLVING - UNIT IV
Properties of dictionary
• More than one entry per key not allowed. Which means no duplicate key is allowed. When
duplicate keys encountered during assignment, the last assignment wins.
• Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary
keys but something like ['key'] is not allowed..
• Dictionary Keys Are Case-Sensitive
21CSS101J PROGRAMMING FOR PROBLEM
130
SOLVING - UNIT IV
Unordered key-value-pairs (The association of a key and a value is called a key-value pair )
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and
lists.
if you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
Methods Description
[Link]() Removes all elements of dictionary dict
[Link]() Returns a shallow copy of dictionary dict
[Link]() Create a new dictionary with keys from seq and values set to value.
[Link](key, default=None) For key key, returns value or default if key not in dictionary
dict.has_key(key) Returns true if key in dictionary dict, false otherwise
[Link]() Returns a list of dict's (key, value) tuple pairs
[Link]() Returns list of dictionary dict's keys
[Link](key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict
[Link](dict2) Adds dictionary dict2's key-values pairs to dict
[Link]() Returns list of dictionary dict's values
cmp(dict1, dict2) Compares elements of both dict.
len(dict) Gives the total length of the dictionary. This would be equal to the number of items
in the dictionary.
str(dict) Produces a printable string representation of a dictionary
type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.
Python dictionary from keys()
• The method fromkeys() creates a new dictionary with keys from seq and values set to
value.
[Link](seq[, value]))
•seq -- This is the list of values which would be used for dictionary keys preparation.
•value -- This is optional, if provided then value would be set to this value
21CSS101J PROGRAMMING FOR PROBLEM
133
SOLVING - UNIT IV
21CSS101J PROGRAMMING FOR PROBLEM
134
SOLVING - UNIT IV
Python dictionary get() Method
• The method get() return a value for the given key. If key is not available then returns default
value None.
[Link](key, default=None)
21CSS101J PROGRAMMING FOR PROBLEM
135
SOLVING - UNIT IV
Exercises
• Create a dictionary state and their capitals and print capital for the given state.
• Write a program that maps a list of words into a list of integers representing the lengths of the
corresponding words.
• Write a tiny Python program [Link] that makes a dictionary whose keys are the words ‘one’,
‘two’, ‘three’, and ‘four’, and whose corresponding values are the numerical equivalents, 1, 2, 3,
and 4 (ints, not strings). Include code to test the resulting dictionary by referencing several of the
definitions and printing the results.
• Write a program to convert list of Celsius values to Fahrenheit using list comprehension
• Write a program that creates the Pythagorean triples using list comprehension (x**2+y**2 =
z**2) (you can use tuple to store the triples)
21CSS101J PROGRAMMING FOR PROBLEM
136
SOLVING - UNIT IV
Data Type Compile Time Run Time
int a=10 a=int(input(“Enter a “))
float a=10.5 a=float(input(“Enter a “))
char a=“CinTel” a=input(“Enter a string”)
List a=[20,30,40,50] a=list(input(“Enter a list”))
Tuple a=(20,30,40,50) a=tuple(input(“Enter a Tuple”))
Variables
• Variables are containers for storing data values.
• A variable allows us to store a value by assigning it to a name, which can
be used later.
• Named memory locations to store values.
• Programmers generally choose names for their variables that are
meaningful.
• It can be of any length. No space is allowed.
• We don't need to declare a variable before using it. In Python, we simply
assign a value to a variable and it will exist.
Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type,
and can even change type after they have been set
x = 4 # x is of type int
x = "Sally" # x is now of type
str
print(x)
Casting
• If you want to specify the data type of a variable, this can be done with
casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))
Case-Sensitive
• Variable names are case-sensitive.
a = 4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables:
• A variable name 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)
myvar = “Mech A"
my_var = “Mech B" Example
_my_var = “Mech C" Illegal variable names:
myVar = “CSE A" 2myvar = “Mech"
MYVAR = “CSE B" my-var = “Mech"
myvar2 = “CSE C" my var = “Mech"
Remember that variable names are case-sensitive
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Assign Multiple Values
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z) Note: Make sure the number of variables matches
the number of values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you extract the values
into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example
x = "awesome"
print("Python is " + x)
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Example
x = 5
If you try to combine a string and a number, Python
y = 10
will give you an error:
print(x + y)
Example
x = 5
y = "John"
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this
variable will be local, and can only be used inside the function. The
global variable with the same name will remain as it was, global and
with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and
can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Test
Display the sum of 5 + 10, using two variables: x and y
= y = 10
print(x y)
Remove the illegal characters in the variable name:
2my-first_name = "John"
Insert the correct syntax to assign the same value to all three variables in one code line.
X Y Z “Orange”
Insert the correct keyword to make the variable x belong to the global scope.
def myfunc():
x
x = "fantastic"
Keywords
v Keywords are the reserved words in Python.
v We cannot use a keyword as variable name, function name or any other identifier.
v They are used to define the syntax and structure of the Python language.
v Keywords are case sensitive.
Operators
• Operators are used to perform operations on variables
and values.
• Python divides the operators in the following groups:
– Arithmetic operators
– Assignment operators
– Comparison operators
– Logical operators
– Identity operators
– Membership operators
– Bitwise operators
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
• Assignment operators are used to assign values to variables.
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators
• Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
Logical Operators
• Logical operators are used to combine conditional
statements:
Operat Description Example
or
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is x < 5 or x < 4
true
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Identity Operators
• Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object,
with the same memory location:
Operator Description Example
is Returns True if both variables are the same x is y
object
is not Returns True if both variables are not the x is not y
same object
Membership Operators
• Membership operators are used to test if a
sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Bitwise Operators
• Bitwise operators are used to compare (binary)
numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1.
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
Bitwise AND operator
Bitwise or operator
Bitwise not operator
Bitwise xor operator:
Bitwise right shift:
Bitwise left shift
Precedence and Associativity of Operators
• Operator Precedence: This is used in an expression with more than one
operator with different precedence to determine which operation to perform first.
10 + 20 * 30 is calculated as 10
+ (20 * 30) and not as (10 + 20)
* 30
• Operator Associativity: If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It can either be Left to Right or
from Right to Left.
• Example: ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”
OPERATOR DESCRIPTION ASSOCIATIVITY
() Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
Relational less than/less than or equal to
< <=
Relational greater than/greater than or left-to-right
> >=
equal to
== != Relational is equal to/is not equal to left-to-right
is, is not Identity
left-to-right
in, not in Membership operators
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
not Logical NOT right-to-left
and Logical AND left-to-right
or Logical OR left-to-right
right-to-left
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
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.
Creating a Comment
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
Comments does not have to be text to explain the code, it can also be
used to prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
• Python does not really have a syntax for multi line comments.
• To add a multiline comment you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
• Or, not quite as intended, you can use a multiline string.
• Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place your comment inside
it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Python Error Handling
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of
the result of the try- and except blocks.
21CSS101J PROGRAMMING FOR PROBLEM S 171
OLVING - UNIT IV
Exception Handling
• When an error occurs, or exception as we call it,
Python will normally stop and generate an error
message.
• These exceptions can be handled using the try
statement
21CSS101J PROGRAMMING FOR PROBLEM S 172
OLVING - UNIT IV
try:
print(x)
Guess the
output… except:
print("An exception
occurred")
21CSS101J PROGRAMMING FOR PROBLEM S 173
OLVING - UNIT IV
Types of logical conditional
• In python, there are six types of logical conditions:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• These conditions can be used in several ways, most commonly in
"if statements" and loops.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 174
Type of Conditional statments
• If
• If else
• If elif
• Nested if
• If with “AND”
• If with “OR”
• If with “pass”
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 175
Syntax for If statement – in Python
• An "if statement" is written by using the if keyword.
• Following if, we need to type the condition with any
one of the logical conditions.
• Place a colon(:) at the end syntax to indicate to the
compiler that conditions are completed.
• Set of lines or statements to be executed after
checking the condition are to be indented.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 176
If statement - Flow control , Syntax
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 177
Example – if statement
• a = 33
b = 200
if b > a:
print("b is greater than a")
• In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a.
• As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to
screen that "b is greater than a".
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 178
If else : statement in python
• An "if statement" is written by using the if keyword.
• The else keyword catches anything which isn't caught
by the preceding conditions.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 179
If else statement - Flow control , Syntax
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 180
If else: Example and explanation
• a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
• In this example a is greater than b, so the condition is
not true, so we go to the else condition and print to
screen that "a is greater than b".
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 181
Elif Statement in python
• An "if statement" is written by using the if keyword.
• The elif keyword is Python's way of saying "if the
previous conditions were not true, then try this
condition".
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 182
elif statement - Flow control
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 183
elif statement - Syntax
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 184
Elif statement – example and explanation
• a = 200 num = 3.4
if num > 0:
b = 33 print("Positive
if b > a: number")
print("b is greater than a") elif num == 0:
print("Zero")
elif a == b: else:
print("a and b are equal") print("Negative
else: number")
print("a is greater than b")
• In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print
to screen that "a is greater than b".
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 185
Nested if statement - python
• An "if statement" is written by using the if keyword.
• You can have if statements inside if statements, this is called
nested if statements.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 186
Nested if - Flow control
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 187
Nested if - Syntax
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 188
Nested If : example and explanation
• x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20.")
else:
print("but not above 20.")
• In this example x is greater than 10, so the first condition is true, also the
nested if condition is true, so we go to the print statement “and also above
20 ” else condition print that “but not above 20".
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 189
If – with AND
• The and keyword is a logical operator, and is used to
combine conditional statements:
• We can check two or more conditional statements
inside a single if command.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 190
If with AND – example , explanation
• a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
• The above if condition checks for both ‘a’ greater than ‘b’ AND
‘c’ greater than ‘a’.
• Only when both the conditions are true print statement will be
executed.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 191
If – with OR
• The or keyword is a logical operator, and is used to combine
conditional statements:
• When any one condition is true then the statement will be
executed.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 192
If – with OR : Example , Explanation
• a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is
True")
• It compares the variable ‘a’ > ‘b’ OR ‘a’ >
‘c’.
• When anyone condition is true then the print
statement will be executed
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 193
If – with PASS
• if statements cannot be empty, but if you for some reason
have an if statement with no content, put in the pass
statement to avoid getting an error.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 194
If – with PASS: Example , Explanation
• a = 33
b = 200
if b > a:
pass
• If statement will be checked when condition is
true it will pass the line without any error
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 195
Program with all “if” statement
• Suppose you are creating a program to categorize students based on their
grades and attendance:
• If the grade is 90 or above:
• If the attendance is 95% or above, the student is categorized as "Excellent".
• Otherwise, the student is categorized as "Very Good".
• If the grade is between 75 and 89:
• If the attendance is 85% or above, the student is categorized as "Good".
• Otherwise, the student is categorized as "Average".
• If the grade is between 50 and 74:
• The student is categorized as "Pass".
• If the grade is below 50:
• The student is categorized as "Fail".
• URL : [Link]
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 196
Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
print("Select operation.")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
while True:
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Invalid Input")
Looping Statements in python
• Python has two primitive loop commands:
• while loops
• With break
• With continue
• With else
• for loops
• With break
• With continue
• With else
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 202
While loop : in python
• With the while loop we can execute a set of statements as long as a
condition is true.
• Example : To print ‘i’ as long as ‘i’ is less than 6:
• i = 1
while i < 6:
print(i)
i += 1
• The while loop requires relevant variables to be ready, in this
example we need to define an indexing variable, i, which we set to
1.
•
Note: remember to increment i, or else the loop will continue
forever.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 203
While : Syntax
Example:
counter = 1
while counter <= 5:
print(counter)
counter += 1
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 204
While – With break: Flow Chart / Syntax
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
While – with CONTINUE :
• With the continue statement we can stop the current
iteration, and continue with the next:
Continue to the next iteration if
i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 206
While – with ELSE :
• With the else statement we can run a block of code
once when the condition no longer is true:
Print a message once the
condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no
longer less than 6")
For loop: in python
• A for loop is used for iterating over a sequence (that
is either a list, a tuple, a dictionary, a set, or a string).
• This is less like the for keyword in other programming
languages, and works more like an iterator method as
found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 208
For : Flow chart
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
For – with BREAK
• With the break statement we can stop the loop before
it has looped through all the items:
Exit the loop when x is "banana":
fruits =
["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
For – with CONTINUE :
• With the continue statement we can stop the current
iteration, and continue with the next:
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
For – with ELSE :
• With the else statement we can run a block of code
once when the condition no longer is true:
Print a message once the condition is false:
for x in range(6):
print(x)
else:
print("Finally finished!")
For loop with Range
• To loop through a set of code a specified number of
times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
• for x in range(6):
print(x)
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 213
Output
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 214
Range : Example 2 : Guess Output
Using the start parameter:
for x in range(2, 6):
print(x)
• The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 215
Range : Example 3 : Guess Output?
• The range() function defaults to increment the
sequence by 1, however it is possible to specify the
increment value by adding a third
parameter: range(2, 30, 3):
• Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 216
Nested For Loop
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each
iteration of the "outer loop":
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 217
Nested For Loop: Example : Guess O/P?
• Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 218
Output:
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 219
Example:
Output:
for i in range(1,6):
*
* *
for j in range(i):
* **
* ***
print("*",end=' ')
* ****
print()
Coding Assignments
1. Create a program that reads a person's age and categorizes them as follows:
Child (0-12)Teenager (13-19)Adult (20-64)Senior (65 and above)
2. Create a program that calculates the discount on a purchase based on the total amount:
10% discount for purchases over $100.
5% discount for purchases between $50 and $100.
No discount for purchases below $50.
3. Create a program that evaluates the strength of a password based on its length and the
inclusion of uppercase letters, lowercase letters, digits, and special characters. Classify
the password as:
• Weak (less than 8 characters)
• Moderate (8 or more characters, but missing some character types)
• Strong (8 or more characters with all required character types)
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 221
Student Activity
• Write the above assignment in python program.
• Compare both the C program and Python program submit as
a case study.
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT IV 222
Functions and Modules
Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Give the function name after def keyword followed by parentheses in which arguments are
given
End with colon (:)
Inside the function add the program statements to be executed
End with or without return statement
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a
function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
Fruitful Function
· Fruitful function
· Void function
· Return values
· Parameters
· Local and global scope
· Function composition
· Recursion
Fruitful function: Example:
def add():
a=10
A function that returns a value is called fruitful b=20
function. c=a+b
return c
Example: c=add()
Root=sqrt(25) print(c)
Void Function Example:
def add():
a=10
A function that perform action but don’t return any value. b=20
c=a+b
Example: print(c)
print(“Hello”) add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
v Parameters are the variables which used in the function definition. Parameters are inputs to functions.
Parameter receives the input from the function call.
v It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number of arguments in
the function call.
Example
def student( name, roll ): Output:
print(name,roll) George 98
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the parameter according to their position.
When we call functions in keyword parameter, the order of the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
Default parameter:
Python allows function parameter to have default values; if the function is called without the argument, the
argument gets its default value in function definition.
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
Variable length parameter
v Sometimes, we do not know in advance the number of arguments that will be passed into a function.
v Python allows us to handle this kind of situation through function calls with number of arguments.
v In the function definition we use an asterisk (*) before the parameter name to denote this is variable length of
parameter.
Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)
Output:
bala ( 102 ,90)
Local and Global Scope
Global Scope
v The scope of a variable refers to the places that you can see or access a variable.
v A variable with global scope can be used anywhere in the program.
v It can be created by defining a variable outside the function.
Local Scope A variable with local scope can be used only within the function .
Function Composition:
v Function Composition is the ability to call one function from within another function.
v It is a way of combining functions such that the result of each function is passed as the argument of the next
function.
v In other words the output of one function is given as the input of another function is known as function
composition.
Example:
[Link]([Link](10)) Output:
900
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Example
def my_function(fname):
print(fname + " Refsnes") Arguments are often shortened to args in
Python documentations
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Keyword
Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3
= "Linus")
Default Parameter Value
Python allows function arguments to have default values. If the function is called
without the argument, the argument gets its default value.
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
We need to keep the following points in mind while calling functions:
[Link] the case of passing the keyword arguments, the order of arguments is not important.
[Link] should be only one value for one parameter.
[Link] passed keyword name should match with the actual keyword name.
[Link] the case of calling a function containing non-keyword arguments, the order is
important.
Passing a List as an Argument
• You can send any data types of argument to a
function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the
function.
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting an
error.
def myfunction():
pass
Function Prototypes:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments,
but can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
• Lambda functions can take any number of
arguments:
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Types of function
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) User Defined Functions:
User defined functions are the functions that programmers create for their requirement and use.
These functions can then be combined to form module which can be used in other programs
by importing them.
ii) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
Flow of Execution:
• The order in which statements are executed is called the flow of execution.
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.
• Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top
to bottom, but you should skip the statements of the function definition until you reach a
point where that function is called.
Illustrative Programs
Program for SWAPPING(Exchanging )of values
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c=a
a=b
b=c
print("a=“ , a , "b=“ , b )
Illustrative Programs
Program to find distance between two points
import math
x1=int(input("enter x1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance =[Link]((x2-x1)**2)+((y2-y1)**2)
print(distance)
Illustrative Programs
Program to circulate n numbers
a=list(input("enter the list"))
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])
Introduction to Python Libraries
• Python library is simply a collection of codes or modules of
codes used in a program for specific operations
• It contains bundles of code that can be used repeatedly in
different programs. It makes Python Programming simpler and
convenient for the programmer.
• Python libraries play a very vital role in fields of Machine
Learning, Data Science, Data Visualization, etc.
21CSS101J PROGRAMMING FOR PROBLEM
251
SOLVING - UNIT IV
Python libraries widely used
• Numpy: For numerical computations.
• Pandas: For data manipulation and analysis.
• Matplotlib: For data visualization.
• SciPy: For scientific and technical computing.
• scikit-learn: For machine learning.
• TensorFlow: For deep learning.
• Keras: For building and training neural networks.
• Requests: For making HTTP requests.
• BeautifulSoup: For web scraping.
• Django: For web development.
21CSS101J PROGRAMMING FOR PROBLEM
252
SOLVING - UNIT IV
Introduction to Numpy
• The name “Numpy” stands for “Numerical Python”. It is the
commonly used library.
• It is a popular machine learning library that supports large
matrices and multi-dimensional data. It consists of in-built
mathematical functions for easy computations.
• NumPy was created in 2005 by Travis Oliphant. It is an open
source project and you can use it freely.
21CSS101J PROGRAMMING FOR PROBLEM
253
SOLVING - UNIT IV
Numpy
• NumPy is a Python library used for working with arrays.
• NumPy’s high level syntax makes it accessible and productive
for programmers from any background or experience level.
• It also has functions for working in domain of linear algebra,
fourier transform, and matrices.
• Even libraries like TensorFlow use Numpy internally to perform
several operations on tensors. Array Interface is one of the key
features of this library.
21CSS101J PROGRAMMING FOR PROBLEM
254
SOLVING - UNIT IV
Numpy
• After NumPy, the next logical choices for growing data science
and scientific computing capabilities are SciPy and Pandas.
• NumPy provides a foundation on which other data science
packages are built, including SciPy, Scikit-learn, and Pandas.
• SciPy provides a menu of libraries for scientific computations.
It extends NumPy by including integration, interpolation,
signal processing, more linear algebra functions, descriptive
and inferential statistics, numerical optimizations, and more.
21CSS101J PROGRAMMING FOR PROBLEM
255
SOLVING - UNIT IV
Numpy
• Scikit-learn extends NumPy and SciPy with advanced
machine-learning algorithms.
• Pandas extends NumPy by providing functions for exploratory
data analysis, statistics, and data visualization( similar to
Microsoft Excel spreadsheets) for working with and exploring
tabular data.
• NumPy with other Python libraries like Matplotlib can be
considered as a fully-fledged alternative to MATLAB's core
functionality.
21CSS101J PROGRAMMING FOR PROBLEM
256
SOLVING - UNIT IV
High Dimensional Arrays
Lists vs NumPy Array
• Users of Python may wonder why NumPy arrays are needed
when Python lists already exist.
• Lists in Python operate as an array that can contain various
types of elements. A perfectly reasonable question has a
logical answer hidden in how Python stores objects in the
memory.
• A Python object is actually a pointer to a memory location
where all the object's details, such as its bytes and value, are
stored. 21CSS101J PROGRAMMING FOR PROBLEM
SOLVING - UNIT IV
257
High Dimensional Arrays
• This additional information is what makes Python a
dynamically typed language, it also comes at a cost which
becomes apparent when storing a large collection of objects,
like in an array.
• Python lists are an array of pointers where each pointer
pointing to a location contains the relevant information to the
element.
• This thing will significantly increase the memory and
calculation overhead. When all the objects stored in the list
are of the same type then
21CSS101J the majority
PROGRAMMING of this information 258
FOR PROBLEM is
SOLVING - UNIT IV
High Dimensional Arrays
• To overcome this issue, we use NumPy arrays, which only
include homogeneous data (Elements with the same data
type). This makes it more efficient at storing and manipulating
the array.
• This difference becomes evident when the array contains
numerous elements, say thousands or millions. Additionally, it
can do element-wise operations with NumPy arrays, which is
not feasible with Python lists.
• This is the reason why NumPy arrays are preferred over
Python lists when performing mathematical operations on a
large amount of data.
21CSS101J PROGRAMMING FOR PROBLEM
259
SOLVING - UNIT IV
High Dimensional Arrays
How to check python and numpy version:
import numpy as np
import platform
print('Python version is: ' + platform.python_version())
print('Numpy version is: ' + np.__version__)
21CSS101J PROGRAMMING FOR PROBLEM
260
SOLVING - UNIT IV
High Dimensional Arrays
How to check python and numpy version:
Output is:
Python version is: 3.6.6
Numpy version is: 1.15.0
21CSS101J PROGRAMMING FOR PROBLEM
261
SOLVING - UNIT IV