0% found this document useful (0 votes)
8 views

Unit 3

This document provides an overview of Python programming, covering its syntax, data types, control structures, functions, and modules. It highlights Python's versatility in various application areas such as web development, data science, automation, and more. Additionally, it discusses key features of Python, including its interpreted nature, dynamic typing, and community support.

Uploaded by

amit45bhosale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 3

This document provides an overview of Python programming, covering its syntax, data types, control structures, functions, and modules. It highlights Python's versatility in various application areas such as web development, data science, automation, and more. Additionally, it discusses key features of Python, including its interpreted nature, dynamic typing, and community support.

Uploaded by

amit45bhosale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit :03

Data Processing & Data Structures

Syllabus:
Introduction to Python: Syntax, data types, and control structures, Functions and Modules,
Python Libraries for AI.

Sr. No. Name Page No

Chapter 3 : Data Processing & Data Structures

3.1 Introduction to Python

3.2 Syntax, data types,

3.3 control structures

3.4 Functions

3.5 Modules

3.6 Python Libraries for AI

3.1 Introduction to Python

Python is a high-level, interpreted programming language that emphasizes simplicity and


readability. It was designed to be easy to learn and use, making it an excellent choice for both
beginners and experienced programmers. Python supports multiple programming paradigms,
including procedural, object-oriented, and functional programming, making it highly versatile
and widely used across various domains.

Why Choose Python?


Python has gained immense popularity due to its:

●​ Simple and Readable Syntax – Python code is clean and easy to understand, resembling
natural English.
●​ Cross-Platform Compatibility – Python runs on Windows, macOS, and Linux without
requiring modifications.
●​ Interpreted Language – Python executes code line-by-line, eliminating the need for
compilation.
●​ Dynamic Typing – Variable types are determined at runtime, making coding more
flexible.
●​ Rich Standard Library – Provides built-in modules and functions for various
applications.
●​ Open Source & Community Support – Python is free to use and has an active global
community for support.

History of Python
Python was created by Guido van Rossum and first released in 1991. The language was
designed to be an improvement over ABC (a teaching language) with a focus on code readability
and ease of use. Over the years, Python has evolved with major versions:

●​ Python 2.x – Introduced in 2000, widely used but is now discontinued.


●​ Python 3.x – Introduced in 2008, with improved features and ongoing support.

Application Areas of Python

Python is widely used in various fields due to its versatility and ease of use. Some of the key
application areas include:

1.​ Web Development – Frameworks like Django and Flask help build scalable and secure
web applications.

2.​ Data Science & Machine Learning – Libraries like Pandas, NumPy, and TensorFlow
allow data analysis and AI model development.

3.​ Automation & Scripting – Python is used to automate repetitive tasks such as file
handling, web scraping, and email automation.
4.​ Game Development – Pygame and Panda3D enable game design and interactive
applications.

5.​ Cybersecurity & Ethical Hacking – Used in penetration testing and network security
analysis.

6.​ Embedded Systems & IoT – Python supports microcontrollers and IoT development
through Raspberry Pi and MicroPython.

7.​ Finance & Trading – Used in algorithmic trading, financial modeling, and risk analysis.

8.​ Database Management – Libraries like SQLite3 and SQLAlchemy provide database
connectivity and management.

9.​ Cloud Computing & DevOps – Used for cloud automation, infrastructure management,
and continuous deployment.

10.​Scientific Computing & Research – Used in physics, biology, astronomy, and other
scientific disciplines for simulations and data processing.

Differences between scripting language and programming language:


Key Features of Python

1.​ Easy to Learn and Use​

○​ Python has a simple and clean syntax that resembles natural language, making it
beginner-friendly.​

2.​ Interpreted Language​


○​ Python code is executed line-by-line (interpreted) rather than compiled, which
simplifies debugging.​

3.​ Dynamically Typed​

○​ Variables do not require explicit type declarations; Python assigns types


dynamically at runtime.​

4.​ Object-Oriented Programming (OOP)​

○​ Supports OOP concepts like classes, objects, inheritance, and polymorphism,


enhancing code reusability.​

5.​ Cross-Platform Compatibility​

○​ Python runs on multiple operating systems (Windows, macOS, Linux) without


modification.​

6.​ Large Standard Library​

○​ Comes with built-in modules for web development, file handling, database
management, and more.​

7.​ Extensible and Embeddable​

○​ Python can be extended with C, C++, and other languages or embedded into other
applications.​

8.​ Automatic Memory Management​

○​ Python manages memory allocation and garbage collection automatically,


reducing manual effort.​

9.​ High-Level Language​

○​ Python abstracts complex low-level operations, making coding easier and more
readable.​

10.​Multiparadigm Support​
○​ Supports multiple programming paradigms, including procedural, functional, and
object-oriented.​

11.​Robust Community Support​

●​ A vast global community contributes to Python’s growth, providing extensive


documentation and libraries.​

12.Integration and Scalability​

○​ Easily integrates with other technologies like databases, web frameworks, and
cloud services, making it scalable for large applications.

3.2 Running Python in interactive mode

Without passing python script file to the interpreter, directly execute code to Python prompt.
Once you’re inside the python interpreter, then you can start.
>>> print("hello world")
hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
5
Running Python in script mode:

Alternatively, programmers can store Python script source code in a file with the .py extension,
and use the interpreter to execute the contents of the file. To execute the script by the interpreter,
you have to tell the interpreter the name of the file. For example, if you have a script name
MyFile.py and you're working on Unix, to run the script you have to type:

python MyFile.py

Working with the interactive mode is better when Python programmers deal with small pieces of
code as you can type and execute them immediately, but when the code is more than 2-4 lines,
using the script for coding can help to modify and use the code in future.

Hello World in Python


To write your first Python program, simply print "Hello, World!" using the following code:

print("Hello, World!")

Output:​
Hello, World!

simple Python program to add two numbers

# Input two numbers


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Add the numbers
sum_result = num1 + num2

# Display the result


print("The sum is:", sum_result)

Output:
Enter first number: 5.5
Enter second number: 4.5
The sum is: 10.0

❖​ Python Indentation:

In Python, indentation is not just a matter of style; it is a fundamental part of the language's
syntax. Where other programming languages use braces {} or keywords to delimit code blocks,
Python uses indentation (whitespace) to define the structure of code.

What is Indentation?

Indentation refers to the spaces at the beginning of a code line. In Python, indentation
indicates a block of code. For example, code inside functions, loops, conditional
statements, and classes must be indented properly.

Why is Indentation Important?

Python uses indentation to define code blocks. Without proper indentation, the Python
interpreter will throw an error. This makes the code clean, readable, and consistent.

Indentation Rules

●​ Python requires indentation for compound statements.​

●​ The recommended indentation is 4 spaces per level.​

●​ Do not mix tabs and spaces; it can lead to TabError.

❖​Comments in Python
In Python, comments are used to make code more understandable for humans. They are ignored
by the Python interpreter, which means they don’t affect how the program runs.

Comments are helpful for:

1.​ Explaining complex logic​

2.​ Marking sections of code​

3.​ Temporarily disabling code​

4.​ Adding reminders or documentation

●​ Types of Comments in Python:

1. Single-Line Comment

A single-line comment begins with the hash symbol (#). Everything after # on that line is
considered a comment.

Ex.

# This is a single-line comment

print("Hello, World!") # This prints a greeting

2. Multi-Line Comment

Python doesn’t have a specific syntax for multi-line comments like some other languages (e.g., /*
*/ in C). Instead, you can use multiple # symbols:

Ex.

# This is a multi-line comment

# written using several

# single-line comments.
Alternatively, you can use triple quotes (''' or """) for block comments or documentation,
though this is technically a multi-line string, not a true comment. It's often used in docstrings.

Ex.

'''

This is a multi-line comment-like block.

Useful for documentation or disabling blocks temporarily.

'''

❖​ Python Keywords:

Keywords in Python are reserved words that have special meanings and serve
specific purposes in the language syntax. Python keywords cannot be used as
the names of variables, functions, and classes or any other identifier.

❖​Python Variables

In Python, variables are used to store data that can be referenced and manipulated during
program execution. A variable is essentially a name that is assigned to a value. Unlike
many other programming languages, Python variables do not require explicit declaration
of type. The type of the variable is inferred based on the value assigned.
Ex.
# Variable 'x' stores the integer value 10
x=5

# Variable 'name' stores the string "Samantha"


name = "Samantha"

print(x)
print(name)

Output:

Samantha

❖​ Data types in Python:

The data stored in memory can be of many types. For example, a student roll number is stored as
a numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

A data type in Python defines the kind of value a variable can hold. Python has various built-in
data types, categorized as follows:
1.​ Numeric Types:

The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined as
Python int, Python float and Python complex classes in Python.
●​ Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.
●​ Float – This value is represented by the float class. It is a real number with a
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 – A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example – 2+3j
Ex.

# Integer Example
a = 10
print("Integer:", a)

# Float Example
b = 5.5
print("Float:", b)

# Complex Number Example


c = 3 + 4j
print("Complex Number:", c)

Output:

Integer: 10

Float: 5.5

Complex Number: (3+4j)

# To verify the type of any object in Python, use the type() function:

# Define numbers
a = 10 # Integer
b = 5.5 # Float
c = 3 + 4j # Complex

# Print values and types


print(type(a))
print(type(b))
print(type(c))
Output:

<class 'int'>
<class 'float'>
<class 'complex'>

2.​ Boolean Data Type in Python

Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and determined to be true or false. It is
denoted by the class bool.

Ex. Check if a Number is Positive

# Input a number
num = float(input("Enter a number: "))

# Check if the number is positive


is_positive = num > 0 # Boolean expression

# Print the result


print("Is the number positive?", is_positive)

Output:
Enter a number: 5

Is the number positive? True


3.​ Dictionary Data Type:

A dictionary in Python is a collection of data values, used to store data values like a map, unlike
other Python Data Types that hold only a single value as an element, a Dictionary holds a key:
value pair. Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.

Create a Dictionary in Python

Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable. The dictionary can also be created by the built-in function
dict().
Ex.
# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary without using dict() keyword


student = {
"name": "Alice",
"age": 20,
"course": "Computer Science"
}

# Creating a dictionary using dict() keyword


employee = dict(name="Bob", age=25, department="IT")

# Printing dictionaries
print("Empty Dictionary:", empty_dict)
print("Student Dictionary (Without dict()):", student)
print("Employee Dictionary (Using dict()):", employee)

Output:

Empty Dictionary: {}
Student Dictionary (Without dict()): {'name': 'Alice', 'age': 20, 'course': 'Computer
Science'}
Employee Dictionary (Using dict()): {'name': 'Bob', 'age': 25, 'department': 'IT'}
Accessing Key-value in Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. Using get() method we can access the dictionary elements.

Ex.

# Creating a dictionary
student = {"name": "Alice", "age": 20, "course": "CS"}

# Accessing values
print(student["name"]) # Alice
print(student.get("age")) # 20

Output:
Alice
20

4.Set Data Type in Python

In Python Data Types, Set is an unordered collection of data types that is iterable, mutable, and
has no duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.

A Set in Python is used to store a collection of items with the following properties.
●​ No duplicate elements. If try to insert the same item again, it overwrites previous one.
●​ An unordered collection. When we access all items, they are accessed without any
specific order and we cannot access items using indexes as we do in lists.
●​ Internally use hashing that makes set efficient for search, insert and delete operations.
It gives a major advantage over a list for problems with these operations.
●​ Mutable, meaning we can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.
Set Representation:
myset = {"apple", "banana", "cherry"}

Ex.of creating set:

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Printing the set


print(fruits)

# Printing the type of the set


print(type(fruits))

Output:
{'banana', 'apple', 'cherry'}
<class 'set'>

Ex. Set Operations program

# Creating two sets


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Displaying sets
print("Set 1:", set1)
print("Set 2:", set2)

# Union (Combining elements of both sets)


union_set = set1 | set2
print("Union:", union_set) # {1, 2, 3, 4, 5, 6, 7, 8}

# Intersection (Common elements in both sets)


intersection_set = set1 & set2
print("Intersection:", intersection_set) # {4, 5}

# Difference (Elements in set1 but not in set2)


difference_set = set1 - set2
print("Difference (set1 - set2):", difference_set) # {1, 2, 3}
# Symmetric Difference (Elements in either set, but not both)
symmetric_diff_set = set1 ^ set2
print("Symmetric Difference:", symmetric_diff_set) # {1, 2, 3, 6, 7, 8}

# Adding an element to a set


set1.add(10)
print("After adding 10 to Set 1:", set1)

# Removing an element from a set


set1.remove(2)
print("After removing 2 from Set 1:", set1)

OutPut:

Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (set1 - set2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
After adding 10 to Set 1: {1, 2, 3, 4, 5, 10}
After removing 2 from Set 1: {1, 3, 4, 5, 10}

5. Python Lists

In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can
store all types of items (including another list) in a list. A list may contain mixed type of items,
this is possible because a list mainly stores references at contiguous locations and actual items
maybe stored at different locations.
●​ List can contain duplicate items.
●​ List in Python are Mutable. Hence, we can modify, replace or delete the items.
●​ List are ordered. It maintain the order of elements based on how they are added.
●​ Accessing items in List can be done directly using their position (index), starting from
0.
Representation of List:

mylist = ["apple", "banana", "cherry"]

Ex. Creating List:

# Creating a list
fruits = ["apple", "banana", "cherry"]

# Printing the list


print(fruits)

# Checking the type


print(type(fruits))

Output:

['apple', 'banana', 'cherry']

<class 'list'>

Ex. list operation program :

# Creating a list
numbers = [10, 20, 30, 40, 50]

# Append (Adding an element)


numbers.append(60)
print("After Append:", numbers)

# Extend (Adding multiple elements)


numbers.extend([70, 80, 90])
print("After Extend:", numbers)

# Insert (Adding at a specific index)


numbers.insert(2, 25)
print("After Insert:", numbers)

# Remove (Deleting an element)


numbers.remove(30)
print("After Remove:", numbers)
# Pop (Removing last element)
numbers.pop()
print("After Pop:", numbers)

# Pop (Removing element at a specific index)


numbers.pop(3)
print("After Pop at index 3:", numbers)

# Slicing (Extracting a part of the list)


print("Sliced List:", numbers[1:4])

# Sorting the list


numbers.sort()
print("After Sorting:", numbers)

# Sorting in descending order


numbers.sort(reverse=True)
print("After Descending Sort:", numbers)

# Reversing the list


numbers.reverse()
print("After Reverse:", numbers)

# Finding the index of an element


print("Index of 40:", numbers.index(40))

# Counting occurrences of an element


print("Count of 20:", numbers.count(20))

# Copying a list
copy_numbers = numbers.copy()
print("Copied List:", copy_numbers)

# Clearing the list


numbers.clear()
print("After Clear:", numbers)
Output:

After Append: [10, 20, 30, 40, 50, 60]


After Extend: [10, 20, 30, 40, 50, 60, 70, 80, 90]
After Insert: [10, 20, 25, 30, 40, 50, 60, 70, 80, 90]
After Remove: [10, 20, 25, 40, 50, 60, 70, 80, 90]
After Pop: [10, 20, 25, 40, 50, 60, 70, 80]
After Pop at index 3: [10, 20, 25, 50, 60, 70, 80]
Sliced List: [20, 25, 50]
After Sorting: [10, 20, 25, 50, 60, 70, 80]
After Descending Sort: [80, 70, 60, 50, 25, 20, 10]
After Reverse: [10, 20, 25, 50, 60, 70, 80]
Index of 40: 3
Count of 20: 1
Copied List: [10, 20, 25, 50, 60, 70, 80]
After Clear: []

6. Python tuple:
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but
unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can
hold elements of different data types. The main characteristics of tuples are being ordered ,
heterogeneous and immutable.

Properties of Tuple in Python

1.​ Ordered – Tuples maintain the order of elements as they are inserted.​

2.​ Immutable – Once created, elements in a tuple cannot be modified, added, or removed.​

3.​ Allows Duplicate Values – Tuples can contain repeated elements.​

4.​ Supports Multiple Data Types – A tuple can store integers, strings, lists, or even other
tuples.​

5.​ Indexing and Slicing Supported – Elements can be accessed using index positions or
sliced into sub-tuples.​

6.​ Can Be Nested – Tuples can contain other tuples, forming nested structures.​
7.​ Memory Efficient – Tuples use less memory compared to lists since they are immutable.​

8.​ Supports Packing & Unpacking – Values can be grouped into a tuple (packing) and
extracted into variables (unpacking).​

9.​ Concatenation Possible – While tuples cannot be modified, they can be combined using
the + operator.​

10.​Used in Function Returns – Tuples are commonly used to return multiple values from
functions.

Representation of tuple:

mytuple = ("apple", "banana", "cherry")

Ex. Creating a Tuple

# Creating a tuple
fruits = ("apple", "banana", "cherry")

# Printing the tuple


print("Tuple:", fruits)

# Checking the type


print("Type:", type(fruits))

Output:

Tuple: ('apple', 'banana', 'cherry')

Type: <class 'tuple'>


Ex. Operation on tuple:

# Creating tuples
tuple1 = (10, 20, 30, 40, 50)
tuple2 = ("apple", "banana", "cherry")

# Accessing elements (Indexing)


print("First element:", tuple1[0])
print("Last element:", tuple1[-1])

# Slicing a tuple
print("Slice (2nd to 4th element):", tuple1[1:4])

# Concatenation (Merging tuples)


merged_tuple = tuple1 + tuple2
print("Merged Tuple:", merged_tuple)

# Repeating a tuple
repeated_tuple = tuple2 * 2
print("Repeated Tuple:", repeated_tuple)

# Checking if an element exists


print("Is 30 in tuple1?", 30 in tuple1)

# Finding the length of a tuple


print("Length of tuple1:", len(tuple1))

# Counting occurrences of an element


tuple3 = (1, 2, 3, 2, 4, 2)
print("Count of 2 in tuple3:", tuple3.count(2))

# Finding index of an element


print("Index of 'banana':", tuple2.index("banana"))

Output:
First element: 10
Last element: 50
Slice (2nd to 4th element): (20, 30, 40)
Merged Tuple: (10, 20, 30, 40, 50, 'apple', 'banana', 'cherry')
Repeated Tuple: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Is 30 in tuple1? True
Length of tuple1: 5
Count of 2 in tuple3: 3
Index of 'banana': 1

7. String
A string in Python is a sequence of characters enclosed within single ('), double ("), or triple ('''
or """) quotes. Strings are immutable, meaning their values cannot be changed after creation.

Ex. Creating Strings

print("Hello")
print('Hello')

Output:
print("Hello")
print('Hello')

●​ Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Ex.
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Output:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
●​ Strings are Arrays:

Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a
length of 1.

Square brackets can be used to access elements of the string.

Ex.
a = "Hello, World!"
print(a[1])

Output:
E

Ex. String operation

# Creating a string
my_string = "Hello, Python!"

# 1. Accessing characters
print("First character:", my_string[0])
print("Last character:", my_string[-1])

# 2. Slicing
print("Substring (0:5):", my_string[0:5])

# 3. Length of string
print("Length of string:", len(my_string))

# 4. String concatenation
str1 = "Hello"
str2 = "World"
print("Concatenated string:", str1 + " " + str2)

# 5. String repetition
print("Repeated string:", str1 * 3)
# 6. Checking substring
print("Is 'Python' in string?", "Python" in my_string)

# 7. String case conversion


print("Uppercase:", my_string.upper())
print("Lowercase:", my_string.lower())

# 8. Replacing substring
print("Replaced string:", my_string.replace("Python", "World"))

# 9. Splitting string
words = my_string.split(", ")
print("Splitted words:", words)

# 10. Stripping whitespace


extra_space_str = " Hello, Python! "
print("Stripped string:", extra_space_str.strip())

# 11. Finding substring


print("Index of 'Python':", my_string.find("Python"))

# 12. Counting occurrences of a character


print("Count of 'l':", my_string.count("l"))

Output:
First character: H
Last character: !
Substring (0:5): Hello
Length of string: 14
Concatenated string: Hello World
Repeated string: HelloHelloHello
Is 'Python' in string? True
Uppercase: HELLO, PYTHON!
Lowercase: hello, python!
Replaced string: Hello, World!
Splitted words: ['Hello', 'Python!']
Stripped string: Hello, Python!
Index of 'Python': 7
Count of 'l': 2
3.3 Control structures

In any programming language a program may execute sequentially, selectively or iteratively.


Every programming language provides constructs to support Sequence, Selection and Iteration.
In Python all these construct can broadly categorized in 2 categories.
A.Conditional Control Construct (Selection, Iteration)
B.Un- Conditional Control Construct (break, continue)

Python have following types of control statements

1. Selection ( branching) Statement


2. Iteration ( looping) Statement
3. Jumping (break / continue)Statement

●​ Python Selection Statements

Python have following types of selection statements


1.if statement
2.if else statement
3. Ladder if else statement (if-elif-else)
4.Nested if statement

1.​ Python If statements:


This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block given below it.

Syntax:

if expression:
# statement(s) to be executed
Example:.

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

# Checking conditions
if age >= 18:
print("You are eligible to vote")

if age < 0:
print("You entered a Negative Number")

Output:

Enter Age: 20
You are eligible to vote
2. if - else statements

This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below it. If condition evaluates result as false, it will
executes the block given below else.

Syntax:

if expression:
​ # code block to be executed
​ # when expression is true
else:
​ # code block to be executed
​ # when expression is false

Flowchart:
Example:
# Taking input for age
age = int(input("Enter Age: "))

# Checking voting eligibility


if age >= 18:
print("You are eligible to vote")
else:
print("You are not eligible to vote")

Output:

Enter Age: 5
You are not eligible to vote

3.Ladder if else statements (if-elif-else):

The if elif else statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.

Similar to the else block, the elif block is also optional. However, a program can contains only
one else block whereas there can be an arbitrary number of elif blocks following an if block.

Syntax:

if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
FlowChart:

Ex. Check if a number is positive, negative, or zero


# Simple program using if-elif-else

# Take input from the user


num = int(input("Enter a number: "))

# Ladder if-elif-else
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

Output:
Enter a number: -5
The number is negative.

4.Nested if statements:
Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement.

There may be a situation when you want to check for additional conditions after the initial one
resolves to true. In such a situation, you can use the nested if construct.

Syntax:
if expression1:
statement(s)
if expression2:
statement(s)

Ex.

num = 36
print ("num = ", num)
if num % 2 == 0:
if num % 3 == 0:
print ("Divisible by 3 and 2")
print("....execution ends....")

Output:
num = 36
Divisible by 3 and 2
....execution ends....
5.Nested if Statement with else Condition

As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is
true, the first if-else statement will be executed otherwise, statements inside the else block will
be executed.

Syntax:

if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)

Ex.

num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

Output:
num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3

6.match-case Statement(Switch Statement):

A Python match-case statement takes an expression and compares its value to successive
patterns given as one or more case blocks. Only the first pattern that matches gets executed. It is
also possible to extract components (sequence elements or object attributes) from the value into
variables.

With the release of Python 3.10, a pattern matching technique called match-case has been
introduced, which is similar to the switch-case construct available in C/C++/Java etc.

Syntax

match variable:
case value1:
# Code block for value1
case value2:
# Code block for value2
case value3:
# Code block for value3
case _:
# Default case (like `default` in switch)

Example:
choice = int(input("Enter a number (1-3): "))
match choice:
case 1:
print("You selected option 1")
case 2:
print("You selected option 2")
case 3:
print("You selected option 3")
case _:
print("Invalid option")
Output:
Enter a number (1-3): 2
You selected option 2

2.Python Iteration Statements:

The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition
meets True result. As soon as condition meets false result, the iteration stops.

Python supports following types of iteration statements


1. while
2. for

Four Essential parts of Looping:


i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable

1.​ while Loop


A while loop in Python programming language repeatedly executes a target statement as long as
the specified boolean expression is true. This loop starts with while keyword followed by a
boolean expression and colon symbol (:). Then, an indented block of statements starts.

Here, statement(s) may be a single statement or a block of statements with uniform indent. The
condition may be any expression, and true is any non-zero value. As soon as the expression
becomes false, the program control passes to the line immediately following the loop.

If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped. Such
a loop is called infinite loop, which is undesired in a computer program.
Syntax of while Loop
while expression:
​ statement(s)

Flow chart:

Example:

# Initialize variable
num = 1

# While loop condition


while num <= 5:
print(num) # Print the current number
num += 1 # Increment by 1

Output:
1
2
3
4
5

2.For Loop:

The for loop in Python provides the ability to loop over the items of any sequence, such as a list,
tuple or a string.
It performs the same action on each item of the sequence.
This loop starts with the for keyword, followed by a variable that represents the current item in
the sequence.
The in keyword links the variable to the sequence you want to iterate over. A colon (:) is used at
the end of the loop header, and the indented block of code beneath it is executed once for each
item in the sequence.

Syntax of Python for Loop

for iterating_var in sequence:


statement(s)

Here, the iterating_var is a variable to which the value of each sequence item will be assigned
during each iteration. Statements represents the block of code that you want to execute
repeatedly.

Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if any) is
evaluated first. Then, the first item (at index 0) in the sequence is assigned to iterating_var
variable.

During each iteration, the block of statements is executed with the current value of iterating_var.
After that, the next item in the sequence is assigned to iterating_var, and the loop continues until
the entire sequence is exhausted.
Flowchart of Python for Loop

Ex.
for i in range(5):
print("Hello, World!")

Output:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
❖​range() with for loop:

Ex.
Iterating Over Tuple, List, and Set:

# Defining a tuple, list, and set


my_tuple = (10, 20, 30, 40)
my_list = [1, 2, 3, 4, 5]
my_set = {100, 200, 300, 400}

# Iterating over tuple


print("Tuple elements:")
for item in my_tuple:
print(item)

# Iterating over list


print("\nList elements:")
for item in my_list:
print(item)
# Iterating over set
print("\nSet elements:")
for item in my_set:
print(item)

Output:
Tuple elements:
10
20
30
40

List elements:
1
2
3
4
5

Set elements:
100
200
300
400

●​ Python break Statement

Python break statement is used to terminate the current loop and resumes execution at the next
statement, just like the traditional break statement in C.

The most common use for Python break statement is when some external condition is triggered
requiring a sudden exit from a loop. The break statement can be used in both Python while and
for loops.

If you are using nested loops in Python, the break statement stops the execution of the innermost
loop and start executing the next line of code after the block.
Syntax of break Statement

looping statement:
condition check:
Break

Flow chart:

Ex.
for letter in 'Python':
if letter == 'h':
break
print ("Current Letter :", letter)
print ("Good bye!")

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Good bye!
●​ Python continue Statement

Python continue statement is used to skip the execution of the program block and returns the
control to the beginning of the current loop to start the next iteration. When encountered, the
loop starts next iteration without executing the remaining statements in the current iteration.

The continue statement is just the opposite to that of break. It skips the remaining statements in
the current loop and starts the next iteration.

Syntax of continue Statement

looping statement:
condition check:
Continue

Flow Diagram of continue Statement



Ex:
for letter in 'Python':
if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!

3.4 Functions

A Python function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
A top-to-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other function by
passing required data (called parameters or arguments). The called function returns its result
back to the calling environment.

Types of Python Functions


1.​ Built-in functions:
Python's standard library includes number of built-in functions. Some of Python's built-in
functions are print(), int(), len(), sum(), etc. These functions are always available, as they
are loaded into computer's memory as soon as you start Python interpreter.
2.​ Functions defined in built-in modules:
The standard library also bundles a number of modules. Each module defines a group of
functions. These functions are not readily available. You need to import them into the
memory from their respective modules.
3.​ User-defined functions
In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions. These functions are called user-defined functions.
●​ Defining a Python Function

You can define custom functions to provide the required functionality. Here are simple rules to
define a function in Python −

​ Function blocks begin with the keyword def followed by the function name and
parentheses ().
​ Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
​ The first statement of a function can be an optional statement; the documentation string
of the function or docstring.
​ The code block within every function starts with a colon (:) and is indented.
​ The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.

Syntax to Define a Python Function

def function_name( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.

Once the function is defined, you can execute it by calling it from another function or directly
from the Python prompt.

Example to Define a Python Function

def greetings():
"This is docstring of greetings function"
print ("Hello World")
Return

Output:
Hello World
●​ Calling a Python Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code. Once the basic structure of a function is finalized, you
can call it by using the function name itself. If the function requires any parameters, they should
be passed within parentheses. If the function doesn't require any parameters, the parentheses
should be left empty.

Example to Call a Python Function

def printme( str ):


"This prints a passed string into this function"
print (str)
return;

# Now you can call the function


printme("I'm first call to user defined function!") # Calling Function
printme("Again second call to the same function") # Calling Function

Output:
I'm first call to user defined function!
Again second call to the same function

❖​ Python Function Arguments

Function arguments are the values or variables passed into a function when it is called. The
behavior of a function often depends on the arguments passed to it.

While defining a function, you specify a list of variables (known as formal parameters) within
the parentheses. These parameters act as placeholders for the data that will be passed to the
function when it is called. When the function is called, value to each of the formal arguments
must be provided. Those are called actual arguments.
Example

Let's modify greetings function and have name an argument. A string passed to the function as
actual argument becomes name variable inside the function.

def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

Output:
Hello Samay
Hello Pratima
Hello Steven

➢​ Types of Python Function Arguments

1.Positional or Required Arguments:

Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition,
otherwise the code gives a syntax error.
Example

def greet(name, age):


print("Hello", name + "!", "You are", age, "years old.")

# Calling the function with positional arguments


greet("Alice", 25)
greet("Bob", 30)

Output:
Hello Alice! You are 25 years old.
Hello Bob! You are 30 years old.

2. Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name. This allows you to skip
arguments or place them out of order because the Python interpreter is able to use the keywords
provided to match the values with parameters.

Example:
def greet(name, age):
print("Hello", name + "!", "You are", age, "years old.")

# Calling the function with keyword arguments


greet(name="Alice", age=25)
greet(age=30, name="Bob") # Order can be changed

Output:
Hello Alice! You are 25 years old.
Hello Bob! You are 30 years old.

3.Default Arguments

A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

Example:
def greet(name="Guest", age=18): # Default values assigned
print("Hello", name + "!", "You are", age, "years old.")

# Calling the function with different arguments


greet("Alice", 25) # Both arguments provided
greet("Bob") # Only name provided, age takes default (18)
greet() # No arguments provided, both take default values

Output:
Hello Alice! You are 25 years old.
Hello Bob! You are 18 years old.
Hello Guest! You are 18 years old.

4.Keyword-only arguments

Those arguments that must be specified by their name while calling the function is known as
Keyword-only arguments. They are defined by placing an asterisk ("*") in the function's
parameter list before any keyword-only parameters. This type of argument can only be passed to
a function as a keyword argument, not a positional argument.

Example:

def greet(*, name, age): # * forces name and age to be keyword-only


print("Hello", name + "!", "You are", age, "years old.")

# Calling the function with keyword arguments


greet(name="Alice", age=25) # Correct usage
greet(age=30, name="Bob") # Order can be changed


# This will cause an error because arguments are not passed as keywords
# greet("Alice", 25) TypeError: greet() takes 0 positional arguments but 2 were given

Output:
Hello Alice, you are 25 years old.
Hello Bob, you are 30 years old.
5.Arbitrary or Variable-length Arguments

You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.

In Python, sometimes we don’t know in advance how many arguments a function will receive.​
To handle variable-length arguments, Python provides:

●​ *args → for positional variable-length arguments.​

●​ **kwargs → for keyword variable-length arguments.​

1.*args (Arbitrary Positional Arguments)

✅ *args allows a function to accept any number of positional arguments.​


✅ These arguments are stored in a tuple.
Example:
def add_numbers(*args): # Accepts multiple positional arguments
total = sum(args) # Sums all values in args
print("Sum:", total)

# Calling the function with different numbers of arguments


add_numbers(10, 20, 30)
add_numbers(5, 15, 25, 35, 45)

Output:
Sum: 60
Sum: 125

2. **kwargs (Arbitrary Keyword Arguments)

✅ **kwargs allows a function to accept any number of keyword arguments.


✅ These arguments are stored in a dictionary (key: value pairs).
Example:
def student_info(**kwargs): # Accepts multiple keyword arguments
for key, value in kwargs.items():
print(f"{key}: {value}")

# Calling the function with different keyword arguments


student_info(name="Alice", age=20, course="Computer Science")
print() # New line
student_info(name="Bob", age=22, university="XYZ University", city="New York")

Output:
name: Alice
age: 20
course: Computer Science

name: Bob
age: 22
university: XYZ University
city: New York

●​ Function with Return Type:

Python does not enforce types, but we can use type hints for clarity.

Syntax:

def function_name(parameters) -> return_type:


# function body
return value

Example:
def add(a: int, b: int) -> int: # Function hints that it returns an int
return a + b

result = add(10, 5)
print("Sum:", result)

Output:
Sum: 15
Explanation:
a: int, b: int → Indicates parameters should be integers.​

-> int → Specifies return type is an integer.​

The function returns the sum of two numbers.

3.5 Python Modules


The concept of module in Python further enhances the modularity. You can define more than one
related functions together and load required functions. A module is a file containing definition of
functions, classes, variables, constants or any other Python object. Contents of this file can be
made available to any other program. Python has the import keyword for this purpose.

Example of Python Module

import math
print ("Square root of 100:", math.sqrt(100))

Output:
Square root of 100: 10.0

1.​ Python User-defined Modules

Any text file with .py extension and containing Python code is basically a module. It can contain
definitions of one or more functions, variables, constants as well as classes. Any Python object
from a module can be made available to interpreter session or another Python script by import
statement. A module can also include runnable code.

●​ Creating a Python Module


Creating a module is nothing but saving a Python code with the help of any editor. Let us save
the following code as mymodule.py

def SayHello(name):
print ("Hi {}! How are you?".format(name))
Return

You can now import mymodule in the current Python terminal.

>>> import mymodule


>>> mymodule.SayHello("Harish")

Output:
Hi Harish! How are you?

●​ The import Statement

In Python, the import keyword has been provided to load a Python object from one module. The
object may be a function, class, a variable etc. If a module contains multiple definitions, all of
them will be loaded in the namespace.

Let us save the following code having three functions as mymodule.py.

def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

The import mymodule statement loads all the functions in this module in the current namespace.
Each function in the imported module is an attribute of this module object.

To call any function, use the module object's reference. For example, mymodule.sum().
import mymodule
print ("sum:",mymodule.sum(10,20))
print ("average:",mymodule.average(10,20))
print ("power:",mymodule.power(10, 2))

Output:
sum:30
average:15.0
Power:100

●​ The from ... import Statement

The import statement will load all the resources of the module in the current namespace. It is
possible to import specific objects from a module by using this syntax. For example −

Out of three functions in mymodule, only two are imported in following executable script
example.py

Example:
from mymodule import sum, average
print ("sum:",sum(10,20))
print ("average:",average(10,20))

Output:
sum: 30
average: 15.0

3.6 Python Libraries for AI

Python offers powerful libraries for Artificial Intelligence (AI), including Machine Learning
(ML), Deep Learning (DL), Natural Language Processing (NLP), and Computer Vision (CV).
Below is a detailed explanation of each important AI library.
1. Scikit-Learn

Purpose: General-purpose ML library built for simplicity and performance in traditional


machine learning tasks.

Key Features:

●​ Algorithms: SVM, Logistic Regression, Naïve Bayes, Random Forest, Gradient


Boosting, etc.​

●​ Tools: Feature scaling, encoding, imputation, and model evaluation​

●​ Model Selection: Cross-validation, grid/randomized search​

●​ Dimensionality Reduction: PCA, t-SNE​

●​ Compatible with Pandas and NumPy​

Advantages:

●​ Easy integration into end-to-end ML pipelines​

●​ Excellent for academic and industry-level ML projects​

●​ Active community and regular updates​

Limitations:

●​ Not optimized for deep learning​

●​ Limited support for GPU acceleration​

Real-World Example: Predicting loan approval based on customer data using Random Forest.

2. XGBoost

Purpose: Optimized distributed gradient boosting framework tailored for high-performance ML


on structured data.

Key Features:

●​ Implements gradient boosting decision trees​

●​ Built-in regularization (L1, L2)​


●​ Sparse-aware algorithm handling missing values​

●​ Cross-platform (Windows, Linux, macOS)​

●​ Visualization of tree models​

Advantages:

●​ Often outperforms traditional ML models​

●​ Excellent scalability for large datasets​

●​ Fast training with early stopping​

Limitations:

●​ Complex for beginners to tune hyperparameters​

Real-World Example: Fraud detection in financial systems using boosting ensembles.

3. LightGBM

Purpose: Gradient boosting framework for faster training and better accuracy in large-scale
datasets.

Key Features:

●​ Leaf-wise tree growth (depth-first) for accuracy​

●​ Histogram-based algorithm for speed​

●​ GPU and distributed learning support​

●​ Native handling of categorical features​

Advantages:

●​ Faster training and low memory usage​

●​ High accuracy on imbalanced datasets​


●​ Scales easily with more data​

Limitations:

●​ Overfitting possible on small datasets​

Real-World Example: Predicting click-through rate (CTR) in online advertising.

4. TensorFlow

Purpose: Google’s ML and DL framework used extensively in research and production-level AI


systems.

Key Features:

●​ Model training on CPUs, GPUs, TPUs​

●​ APIs in Python, C++, JavaScript​

●​ TensorBoard: Visualization and debugging tool​

●​ Model deployment: TensorFlow Serving, Lite, JS​

●​ Dataset pipeline management (tf.data)​

Advantages:

●​ Enterprise-level scalability​

●​ Broad community and Google support​

●​ Built-in model saving/loading​

Limitations:

●​ Steeper learning curve for beginners​

Real-World Example: Training a CNN to detect cancer cells in histopathology images.


5. PyTorch

Purpose: Research-first deep learning framework developed by Facebook AI Research.

Key Features:

●​ Dynamic computational graph (eager execution)​

●​ Built-in automatic differentiation​

●​ TorchText, TorchVision, and TorchAudio modules​

●​ Native C++ support via LibTorch​

●​ Compatible with Hugging Face, PyG, MONAI​

Advantages:

●​ Intuitive debugging with Python-style code​

●​ Ideal for research, custom model architectures​

●​ Smooth transition from research to production (TorchScript)​

Limitations:

●​ Slightly slower training than TensorFlow in some production settings​

Real-World Example: Training a GPT-based text generator for creative writing.

6. Keras

Purpose: High-level neural network API simplifying deep learning model design and training.

Key Features:

●​ Layer-wise model building​

●​ Pre-trained models (VGG16, MobileNet, ResNet)​

●​ Callbacks: EarlyStopping, ModelCheckpoint​


●​ Built-in metrics, loss functions, optimizers​

●​ Multi-GPU support via tf.distribute​

Advantages:

●​ Beginner-friendly and readable​

●​ Rapid prototyping and testing​

●​ Seamless switch from research to production​

Limitations:

●​ Less control over lower-level operations​

Real-World Example: Image classification using pre-trained ResNet for vehicle recognition.

7. NLTK (Natural Language Toolkit)

Purpose: Legacy NLP toolkit ideal for language research and text mining.

Key Features:

●​ Linguistic tools: POS tagging, chunking, parsing​

●​ Corpus support: Brown, Gutenberg, WordNet​

●​ Text classification models​

●​ Lexical analysis tools​

Advantages:

●​ Educational and research-friendly​

●​ Rich set of corpora and resources​

●​ Suitable for grammar-based tasks​

Limitations:
●​ Slower than modern NLP tools (e.g., spaCy, Transformers)​

Real-World Example: Analyzing political speech sentiment using tokenization and POS
tagging.

8. spaCy

Purpose: High-speed, production-ready NLP library optimized for real-world tasks.

Key Features:

●​ Tokenization, parsing, NER, POS tagging​

●​ Support for multiple languages​

●​ Built-in word vectors and pipelines​

●​ Transformer-based models (spacy-transformers)​

Advantages:

●​ Faster and lighter than NLTK​

●​ Ready for large-scale production NLP​

●​ Compatible with ML/DL workflows​

Limitations:

●​ Less granular linguistic detail than NLTK​

Real-World Example: Entity recognition in resumes for automated HR screening.

9. OpenCV

Purpose: Cross-platform computer vision library used for real-time image/video processing.

Key Features:
●​ Image transformation, filtering, and enhancement​

●​ Face and object detection (Haar, DNN)​

●​ Camera calibration and tracking​

●​ Optical flow and motion analysis​

●​ Integration with TensorFlow, ONNX, and PyTorch​

Advantages:

●​ High-speed real-time processing​

●​ Support for 3D vision and stereo imaging​

●​ Platform-agnostic (C++, Python, Java)​

Limitations:

●​ Requires deep learning library for complex AI tasks​

Real-World Example: Detecting lane markings in autonomous driving systems.

10. Scikit-Image

Purpose: Image processing library that complements Scikit-Learn with scientific computing
tools.

Key Features:

●​ Feature extraction and edge detection​

●​ Filters, morphology, and thresholding​

●​ Region-based segmentation​

●​ Object counting and labeling​

●​ Works well with NumPy, SciPy, and Matplotlib​

Advantages:
●​ Simple to use and learn​

●​ Good for research, prototyping, and teaching​

●​ Easily integrated into ML workflows​

Limitations:

●​ Not suited for deep learning-based vision tasks​

Real-World Example: Detecting micro-cracks in material images from a microscope.

Unit 3

No Questions Marks
1 Explain different data types supported by Python. 2
2 What are identifiers? List the rules to name an identifier. 2
3 Explain the use of Indentation in Python 2
4 Explain for loop with example 2
5 Explain while loop with example 2
6 What is a dictionary? 2
7 Write syntax of function 2
8 List types of operators in python 2

1 Explain different data types in Python. 4


2 Explain selection/conditional statements in Python. 4

Write a program in Python to find whether gives is even


3 4
or odd.
4 Differentiate between list and set data type. 4

What is a list and set?Explain accessing and removing


5 4
of elements from list and set with example.
What is a list and set? Explain adding and display of
6 4
elements in set and list with example.
Write a program to print the following pattern.
*
**
7 4
***
****
*****
List down types of operators in Python. Explain
8 4
arithmaticoperators

Explain following data types in Python with example.


i) Set
1 6
ii) List
iii) Dictionary
Explain following selection/decision making statements
in Python with example
2 i) If statement. 6
ii) If...else statement.
iii) If..elif..else statement.
What is a list?
Display the elements of the list.
3 Determine the length of the list. 6
Insert new elements at specific positions.
Delete elements by value or index.
What is a tuple?
Access and display elements of the tuple.
4 6
Determine the length of the tuple.
Explain the following types of function arguments in
Python with examples:

Default Argument
5 6

Keyword Argument

Positional Argument
Compare the following data types in Python : List, Set,
6 6
and Tuple
Explian following list method append() count() insert()
7 6
pop() reverse() sort()
8 Write a program to find largest of three numbers. 6
9 Write a program to find factorial of a number. 6

You might also like