Unit 3
Unit 3
Syllabus:
Introduction to Python: Syntax, data types, and control structures, Functions and Modules,
Python Libraries for AI.
3.4 Functions
3.5 Modules
● 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 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.
○ Python has a simple and clean syntax that resembles natural language, making it
beginner-friendly.
○ Comes with built-in modules for web development, file handling, database
management, and more.
○ Python can be extended with C, C++, and other languages or embedded into other
applications.
○ 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.
○ Easily integrates with other technologies like databases, web frameworks, and
cloud services, making it scalable for large applications.
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.
print("Hello, World!")
Output:
Hello, World!
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.
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
❖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.
1. Single-Line Comment
A single-line comment begins with the hash symbol (#). Everything after # on that line is
considered a comment.
Ex.
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.
# 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.
'''
'''
❖ 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
print(x)
print(name)
Output:
Samantha
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)
Output:
Integer: 10
Float: 5.5
# 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
<class 'int'>
<class 'float'>
<class 'complex'>
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.
# Input a number
num = float(input("Enter a number: "))
Output:
Enter a number: 5
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’.
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 = {}
# 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
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"}
# Creating a set
fruits = {"apple", "banana", "cherry"}
Output:
{'banana', 'apple', 'cherry'}
<class 'set'>
# Displaying sets
print("Set 1:", set1)
print("Set 2:", set2)
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:
# Creating a list
fruits = ["apple", "banana", "cherry"]
Output:
<class 'list'>
# Creating a list
numbers = [10, 20, 30, 40, 50]
# Copying a list
copy_numbers = numbers.copy()
print("Copied List:", copy_numbers)
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.
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.
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:
# Creating a tuple
fruits = ("apple", "banana", "cherry")
Output:
# Creating tuples
tuple1 = (10, 20, 30, 40, 50)
tuple2 = ("apple", "banana", "cherry")
# Slicing a tuple
print("Slice (2nd to 4th element):", tuple1[1:4])
# Repeating a tuple
repeated_tuple = tuple2 * 2
print("Repeated Tuple:", repeated_tuple)
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.
print("Hello")
print('Hello')
Output:
print("Hello")
print('Hello')
● Multiline Strings
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.
Ex.
a = "Hello, World!"
print(a[1])
Output:
E
# 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)
# 8. Replacing substring
print("Replaced string:", my_string.replace("Python", "World"))
# 9. Splitting string
words = my_string.split(", ")
print("Splitted words:", words)
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
Syntax:
if expression:
# statement(s) to be executed
Example:.
# 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: "))
Output:
Enter Age: 5
You are not eligible to vote
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:
# 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
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
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.
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
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.
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:
Output:
Tuple elements:
10
20
30
40
List elements:
1
2
3
4
5
Set elements:
100
200
300
400
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.
looping statement:
condition check:
Continue
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.
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.
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.
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.
Output:
I'm first call to user defined function!
Again second call to the same function
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
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
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.")
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.")
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:
❌
# 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:
Output:
Sum: 60
Sum: 125
Output:
name: Alice
age: 20
course: Computer Science
name: Bob
age: 22
university: XYZ University
city: New York
Python does not enforce types, but we can use type hints for clarity.
Syntax:
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.
import math
print ("Square root of 100:", math.sqrt(100))
Output:
Square root of 100: 10.0
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.
def SayHello(name):
print ("Hi {}! How are you?".format(name))
Return
Output:
Hi Harish! How are you?
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.
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 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
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
Key Features:
Advantages:
Limitations:
Real-World Example: Predicting loan approval based on customer data using Random Forest.
2. XGBoost
Key Features:
Advantages:
Limitations:
3. LightGBM
Purpose: Gradient boosting framework for faster training and better accuracy in large-scale
datasets.
Key Features:
Advantages:
Limitations:
4. TensorFlow
Key Features:
Advantages:
● Enterprise-level scalability
Limitations:
Key Features:
Advantages:
Limitations:
6. Keras
Purpose: High-level neural network API simplifying deep learning model design and training.
Key Features:
Advantages:
Limitations:
Real-World Example: Image classification using pre-trained ResNet for vehicle recognition.
Purpose: Legacy NLP toolkit ideal for language research and text mining.
Key Features:
Advantages:
Limitations:
● Slower than modern NLP tools (e.g., spaCy, Transformers)
Real-World Example: Analyzing political speech sentiment using tokenization and POS
tagging.
8. spaCy
Key Features:
Advantages:
Limitations:
9. OpenCV
Purpose: Cross-platform computer vision library used for real-time image/video processing.
Key Features:
● Image transformation, filtering, and enhancement
Advantages:
Limitations:
10. Scikit-Image
Purpose: Image processing library that complements Scikit-Learn with scientific computing
tools.
Key Features:
● Region-based segmentation
Advantages:
● Simple to use and learn
Limitations:
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
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