DAP_1_module
DAP_1_module
Python's main design philosophy emphasizes code readability and simplicity, allowing
programmers to express concepts in fewer lines of code compared to languages like C++ or
Java.
To write and execute Python programs, one must first install Python and set up an
environment.
• Python programs can also be written in any text editor and run from the command
line:
python myprogram.py
To make programming easier, high-level languages like Python, C, Java, etc., were
developed. These languages are human-readable and easier to understand. However,
computers cannot understand high-level languages directly, so we need translators to
convert them into machine language.
• Interpreter
• Compiler
Translation
Translates line by line Translates the whole program at once
Method
Execution Slower, as it translates each line Faster, as it translates the entire code
Speed at runtime before execution
Error Stops and shows error Shows all errors at the end of
Detection immediately when found compilation
Python uses both a compiler and an interpreter, but not in the traditional sense like C or
Java.
• Python programs are written in .py files using any text editor or IDE like PyCharm,
Jupyter, or IDLE.
• code (hello.py):
print("Hello, Python!")
• Python compiles the code to byte code, which is a low-level set of instructions
understood by the Python Virtual Machine (PVM).
• Byte code is stored in .pyc files inside a folder called __pycache__.
3. Interpretation by PVM
• The PVM (Python Virtual Machine) reads the .pyc file and converts byte code into
machine code based on the OS and processor.
• The machine code is executed by the CPU, and the output is shown.
1. Comments
2. Docstrings
3. Import Statements
6. Control Structures
7. Functions
PYTHON MODULES
Flow Control in Python
Flow control allows you to control the order in which instructions are executed in a
program. These constructs are found in almost every programming language and are
fundamental to logic building.
1. Sequential Execution
a = 10
b = 20
print(a + b)
2. Conditional Execution
age = 18
print("Adult")
else:
print("Minor")
o Types:
for i in range(5):
print(i)
def greet(name):
print("Hello", name)
greet("Alice")
Identifiers
• Identifiers are names used by a programmer to name variables, functions,
classes, modules, and objects.
• Cannot be a keyword.
s of Invalid Identifiers:
• class (keyword)
Good Practice:
total_marks = 450
student_name = "John"
Variables
• A variable is a symbolic name that is a reference to an object.
Important Features:
s:
x = 10 # integer
Tip:
You can assign the same value to multiple variables:
a = b = c = 100
a, b, c = 1, 2, 3
Keywords
• Keywords are special words reserved by the Python language.
Important Notes:
for, while, break, import, def, return, class, try, except, finally, with, as,
if, else, elif
continue pass, lambda
Statements
• A statement is a logical instruction that Python interpreter can execute.
• Statements perform actions like assigning a value, making decisions, looping over
data, etc.
Type
Assignment Statement x = 10
x=5
if x > 0:
print("Positive")
else:
print("Negative")
Expressions
• An expression is a combination of operands (variables, literals) and operators
(like +, *, /) that produces a new value.
Important Features:
Arithmetic 3+5 8
result = (5 + 3) * 2
Operators
Operators are special symbols or keywords in Python that are used to perform
operations on variables and values.
1⃣ Arithmetic Operators
+ Addition 3+5 8
- Subtraction 10 - 4 6
* Multiplication 2*6 12
Operator Meaning Example Output
** Exponent (power) 2 ** 3 8
a = 10
b=3
print(a + b) # 13
print(a // b) # 3
print(a % b) # 1
2⃣ Assignment Operators
= Assign x=5
x=5
x += 2 # x = x + 2 → 7
print(x)
3⃣ Comparison (Relational) Operators
== Equal to 5 == 5 True
a = 10
b = 20
print(a == b) # False
and True if both statements are true (5 > 2) and (4 > 1) True
a = True
b = False
print(a or b) # True
print(not a) # False
5⃣ Bitwise Operators
` ` OR `5
~ NOT ~5 -(5+1) = -6
a = 5 # 0101
b = 3 # 0011
print(a & b) # 1
print(a | b) # 7
not in True if value not found in sequence "x" not in "cat" True
Compare memory locations (whether two variables refer to the same object).
Operator Meaning Example Output
a = [1,2,3]
b=a
c = [1,2,3]
1 () Parentheses
2 ** Exponentiation
8 or Logical OR
Associativity
• Left to Right: Most operators like +, -, *, /, //, % follow left-to-right associativity.
result = (3 + 2) * 4 ** 2 // 5 % 3
# Step-by-step:
# (3 + 2) = 5
# 4 ** 2 = 16
# 5 * 16 = 80
# 80 // 5 = 16
# 16 % 3 = 1
print(result) # 1
Data Types
Data types define the nature of data a variable can hold. Python is dynamically typed,
meaning the type is assigned at runtime.
1. Numbers
Python supports:
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
2. Boolean
• Stores only two values: True or False.
is_valid = True
3. Strings
• A sequence of characters.
• Can be enclosed in single ' ', double " ", or triple quotes ''' '''.
s1 = 'Hello'
s2 = "World"
s3 = '''This is
a multiline
string'''
4️. List
5. Tuple
6️. Dictionary
• Commonly used for initializing variables or returning from functions that don’t return
anything.
x = None
Indentation
• Indentation is mandatory in Python to define blocks of code.
• It improves readability and replaces the need for {} braces like in other languages.
Rules of Indentation:
• Four spaces per indentation level are standard (tabs should be avoided).
if True:
if 5 > 2:
Comments
• Comments are non-executable lines meant to explain code.
• Python supports:
'''
This is a
multiline comment
'''
Best Practices:
• You use placeholders like %s, %d, %f, etc., inside the string.
Syntax:
Common Placeholders:
Placeholder Meaning
%s String
%d Integer (Decimal)
%f Floating-point number
%x / %X Hexadecimal
%o Octal number
name = "Alice"
age = 23
Syntax:
Formatting numbers:
result = 5/3
print("Result: {:.2f}".format(result))
Syntax:
name = "Alice"
age = 23
a=5
b = 10
print(f"Sum is {a+b}")
# Output: Sum is 15
pi = 3.14159
• Secure and safe for user inputs (avoids code injection attacks).
• Useful in situations like web development where strings come from external
sources.
Import it first:
Syntax:
Template('Hello, $name').substitute(name='Alice')
message = temp.substitute(name='Alice')
print(message)
Note:
1. Positional Arguments
➤ 2: Using Indexes
2. Keyword Arguments
Type
Type Conversion in Python
Python is a dynamically typed language, which means you don’t need to declare a
variable’s type before using it. However, there are situations where explicit type
conversion is necessary.
This is where type conversion functions come in handy. Python provides built-in
functions to convert values from one data type to another.
Function Description
int() Function
• It does not round a float, it simply truncates (removes) the decimal part.
print(int('32')) # Output: 32
print(int(-2.3)) # Output: -2
Invalid Case:
print(int('Hello'))
# Output: ValueError: invalid literal for int() with base 10: 'Hello'
float() Function
str() Function
• Happens when Python converts smaller data types to larger ones to avoid data loss.
a=5 # int
b = 2.0 # float
Explanation:
Here, Python automatically converted int (5) to float (5.0) to match 2.0.
Function Description
x = "123"
The type() function returns the type/class of the object passed to it. It is often used for
debugging and verification purposes.
Syntax:
type(variable_or_value)
x = 10
y = 3.14
z = "Hello"
is Operator in Python
Python provides two types of comparisons:
• is operator → checks for identity (are both variables pointing to the same memory
location?)
Identity vs. Equivalence
Concept Description
Equivalent Objects Have the same value but may be different objects
a = 'banana'
b = 'banana'
Even if two strings have the same value from input, they are stored in different memory
locations, so is returns False, but == returns True.
Syntax:
if condition:
# block of code
Explanation:
x = 10
if x > 5:
Notes:
• Python uses indentation to define blocks of code, not curly braces {}.
Syntax:
if condition:
else:
x=4
if x % 2 == 0:
print("Even")
else:
print("Odd")
Explanation:
Use Case:
Useful when you need to choose between two mutually exclusive options, like checking
user authentication, eligibility, etc.
Syntax:
if condition1:
# block A
elif condition2:
# block B
elif condition3:
# block C
else:
# default block
marks = 75
print("Grade A")
print("Grade B")
print("Grade C")
else:
print("Grade D")
Explanation:
Notes:
Syntax:
if condition1:
if condition2:
# inner block
else:
# inner else
else:
# outer else
x = 20
y=5
if x > 10:
if y > 0:
else:
else:
Notes:
• Too much nesting can make code hard to read.
Iteration, combined with conditional execution (e.g., if statements), forms the backbone of
algorithm design. Loops are used to automate repetitive tasks, process collections of data,
or solve problems that require repeated computations.
1. Indefinite loops (e.g., while loops): Used when the number of iterations is unknown
in advance.
2. Definite loops (e.g., for loops): Used when the number of iterations is known or can
be determined.
1. Definite Loops
for i in range(5):
print(i)
2. Indefinite Loops
An indefinite loop is a loop that keeps running until a certain condition becomes false.
n=5
while n > 0:
print(n)
n -= 1
• We don't know in advance exactly how many steps it will take without examining
the code.
3. Finite Loops
A finite loop is any loop (definite or indefinite) that eventually terminates after
completing a certain number of iterations.
Definite Finite:
for i in range(3):
print(i)
Indefinite Finite:
password = ""
print("Access granted!")
An infinite loop is a loop that never ends unless forcibly stopped (manually or with a
break).
while True:
n=5
while n > 0:
print(n)
Summary Table
While Loop
What is a While Loop?
A while loop is an indefinite loop that repeatedly executes a block of code as long as a
specified condition evaluates to True.
It is ideal for situations where the number of iterations is not predetermined, such as
waiting for user input, processing data until a certain condition is met, or performing
calculations until convergence.
while condition:
# Statements to be executed
Flow of Execution
2. If the condition is True, the body of the loop is executed, and the program returns to
step 1.
3. If the condition is False, the loop terminates, and the program proceeds to the next
statement after the loop.
Key Components
• Iteration Variable (Counter Variable): A variable that controls the loop’s execution
by changing its value in each iteration. For , a counter incremented inside the loop.
• Condition Update: The iteration variable must be updated within the loop to
eventually make the condition False. Failure to update the variable can lead to an
infinite loop.
1: Printing Numbers 1 to 5
i=1
while i <= 5:
print(i)
i=i+1
Infinite Loops
An infinite loop occurs when the condition never becomes False, causing the loop to run
indefinitely. This can happen due to:
of an Infinite Loop:
i=1
while i <= 5:
print(i)
# Missing i = i + 1
• Here, i remains 1, and the condition i <= 5 is always True, causing the loop to print 1
indefinitely.
• Always ensure the iteration variable is updated to eventually make the condition
False.
• Use debugging techniques (e.g., print statements) to trace the variable’s value.
• Use break statements to exit the loop under specific conditions (covered later).
Break
The break statement is used to exit a loop prematurely, regardless of whether the loop’s
condition is still True. It is commonly used in while and for loops to provide an alternative
exit condition, especially in indefinite loops or when a specific event occurs.
Syntax
while condition:
# Statements
if some_condition:
break
# More statements
• When the break statement is executed, the program immediately exits the
innermost loop (while or for) and proceeds to the first statement after the loop.
count = 0
if num < 0:
break
count += 1
print("Loop ended.")
Explanation:
• If the user enters a negative number, break is executed, terminating the loop early.
2: Exiting on “done”
while True:
if user_input == "done":
break
print("Finished!")
Explanation:
• The break statement exits the loop when the user types “done”.
• Scope: break only exits the innermost loop. In nested loops, outer loops continue
running.
• Use Case: Ideal for sentinel-controlled loops (e.g., stopping when a specific input is
received).
• Caution: Overusing break can make code harder to read. Use it when the exit
condition is complex or not easily incorporated into the loop’s main condition.
Common Pitfalls
• Forgetting to include the break condition, leading to an infinite loop.
• Placing break in a way that skips important cleanup code in the loop.
Continue
The continue statement is used to skip the rest of the current iteration in a loop and
move to the next iteration. Unlike break, which exits the loop entirely, continue allows the
loop to keep running but bypasses certain iterations based on a condition.
Syntax
while condition:
# Statements
if some_condition:
continue
# More statements
• When continue is executed, the program skips the remaining statements in the
current iteration and returns to the loop’s condition check (for while loops) or the
next item (for for loops).
• The loop continues until its condition becomes False or a break is encountered.
while True:
if line == "done":
break
if line.startswith("#"):
continue
print("Line:", line)
print("Finished!")
i += 1
continue
print(i)
Explanation:
• Use Case: Useful for filtering out specific cases (e.g., skipping invalid inputs or
comments).
• Caution: Ensure continue doesn’t skip critical updates to the iteration variable, as
this could cause an infinite loop.
Common Pitfalls
• Accidentally skipping the update of the iteration variable, leading to an infinite loop.
• Overusing continue, which can make the loop logic harder to follow.
For Loop
A for loop is a definite loop used to iterate over a known set of items, such as a list, tuple,
string, or range of numbers. It is ideal when the number of iterations is predetermined or
can be derived from the data structure being processed.
Syntax
# Statements to be executed
# Statements to be executed
Key Components
• variable: The iteration variable that takes on each value in the sequence or range.
• sequence: A collection (e.g., list, tuple, string) or an iterable object (e.g., range()).
• Body: The indented block of code executed for each value of the iteration variable.
print("Hello,", name)
print(char)
The range() function generates a sequence of numbers, making it ideal for iterating a
specific number of times.
Syntax of range():
1: Printing Numbers 1 to 5
print(i)
print(i)
print(i)
• Use Cases:
Both break and continue work in for loops similarly to while loops.
if i == 5:
break
print(i)
if i % 2 == 0:
continue
print(i)
Pass
• The pass statement in Python is a null operation.
• Python will not throw an error when it encounters pass; it simply moves on.
o Empty functions
o Empty classes
o Empty loops
o Empty conditionals
Syntax:
pass
def future_function():
if x > 0:
else:
print("Negative number")
• Here, pass acts as a placeholder until the if block is properly coded later.
for i in range(5):
Statement Purpose
continue Skip the current iteration and continue with the next iteration.
Functions
A function in Python is a sequence of instructions grouped together to perform a specific,
independent task.
Functions are essential for organizing code, making it reusable, modular, and easier to
maintain.
They allow programmers to avoid repeating code by defining a task once and calling it
multiple times as needed.
• Object Nature: In Python, functions are treated as objects, allowing flexibility (e.g.,
passing functions as arguments to other functions).
Built-in Functions
• Built-in functions are functions already defined by Python.
• These functions are ready to use at any point in the program without needing any
extra coding.
o Displaying output
o Taking input
• These functions are highly reliable, optimized, and error-free because they are
developed and tested by the creators of Python.
• Built-in functions increase productivity because you do not need to "reinvent the
wheel" every time you want to perform a basic task.
Function Purpose
print("Hello")
x = [1, 2, 3]
print(len(x)) # Output: 3
a=5
User-defined Functions
• User-defined functions are functions written by the programmer to perform
specific, customized tasks.
• When built-in functions are not enough, or you want to repeat a task many times
with different values, you create your own function.
• They increase code reusability — you can call the same function multiple times
without writing the same code again.
• In Python, functions are created using the def keyword, followed by:
o A function name (identifier)
o A body of statements
Syntax:
def function_name(parameters):
# statements
return value
def greet():
print("Good Morning!")
greet()
print(a + b)
add(2, 3)
def square(n):
return n * n
print(square(4)) # Output: 16
Type Example
• Easier Maintenance: Update one function without changing the whole program.
Math Module
The math module provides mathematical functions for advanced calculations. To use
these functions, you must import the module using:
import math
Function Description
import math
# Calculate square root
# Trigonometric functions
# Constants
# Logarithm
Random Module
The random module provides functions to generate pseudo-random numbers, which are
useful for applications like games, simulations, and testing.
Function Description
import random
print("Random floats:")
for i in range(5):
print(random.random())
Function Calls
What is Function Calling?
• Function calling means executing or invoking a function that has been defined
earlier.
Syntax:
function_name(arguments)
def greet():
print("Hello, Welcome!")
greet()
Example 2: Calling a function with arguments
print(a + b)
add(2, 3)
Important Points:
• Order Matters: Arguments must match the order and number expected by the
function.
• Return Values: If the function returns a value, you can store it in a variable.
def square(x):
return x * x
print(result)
• Reusability: You can call the same function multiple times without rewriting the
code.
• Flexibility: Functions can be called with different inputs to perform the same task
differently.
Return Statement and Void Functions in Python
The return Statement
o Send a value back to the place where the function was called.
• Without return, a function will perform actions but won't give any output back.
Syntax:
def function_name(parameters):
# code
return value
o A number
o A string
def square(x):
return x * x
result = square(5)
print(result)
print("Sum:", x)
print("Difference:", y)
def greet():
print("Hello!")
return
greet()
• If multiple return statements are there, only the first one that is hit gets executed.
Void Functions
• A Void Function is a function that does NOT return any value to the caller.
• It performs some task (like printing output) but returns None by default.
def display_message():
print("Python is fun!")
display_message()
def hello():
print("Hello World")
result = hello()
print(result)
• Local Variables: Variables defined inside a function, accessible only within that
function's body.
• Global Variables: Exist for the entire duration of the program's execution.
• Local Variables: Exist only during the execution of the function in which they are
defined. They are created when the function is called and destroyed when the
function returns.
• Local Variables: Declared inside a function, they are confined to that function’s
scope. If a local variable has the same name as a global variable, the local variable
shadows (hides) the global one within the function.
x = 10 # Global variable
def my_function():
y = 5 # Local variable
my_function()
Explanation:
Trying to print y outside will cause an error, because local variables exist only inside
their function.
Functional Parameters
Python supports several types of function parameters to make functions flexible and
reusable. Below is a detailed explanation of all types of functional parameters, including
default parameters, keyword arguments, *args, **kwargs, and positional-only/parameters.
1. Positional Parameters
Parameters that are assigned values based solely on the order in which they are passed
during the function call.
• The order of arguments in the function call must exactly match the order in the
function definition.
greet("Alice", 25)
Key Points:
• Position matters.
2. Keyword Parameters
Parameters are explicitly passed by specifying the parameter name in the call.
This improves readability and makes the purpose of each argument immediately clear.
Keyword parameters must match the parameter names defined in the function.
In a function call, all positional arguments must come before any keyword
arguments.
• The order does not matter since each argument is linked by name.
greet(age=25, name="Alice")
Key Points:
Especially important when a function has many parameters or parameters with similar
types.
3. Default Parameters
Parameters that are given a default value during the function definition, allowing the caller
to omit them if desired.
Default values are evaluated once at function definition time, not at each call.
Mutable default values (like lists or dictionaries) can cause unexpected behavior if not
handled carefully.
greet("Bob")
Key Points:
Default parameters are shared across all function calls unless specifically overridden.
Use immutable objects (e.g., integers, strings, tuples) as default values whenever
possible to avoid side effects.
Useful when you do not know in advance how many arguments might be passed.
Inside the function, args is a tuple containing all extra positional arguments.
Syntax:
An asterisk (*) before a parameter name in the function definition.
def add_numbers(*numbers):
print(numbers)
add_numbers(1, 2, 3)
Key Points:
You can still have named positional or keyword parameters along with *args.
Allows a function to accept any number of keyword arguments not explicitly declared in
the function signature.
Syntax:
Two asterisks (**) before the parameter name in the function definition.
def print_info(**info):
print(info)
print_info(name="Alice", age=25)
Key Points:
Like *args, if no extra keyword arguments are passed, kwargs will be an empty dictionary.
**kwargs can also be unpacked when calling another function, forwarding arguments
dynamically.
• Keys are the parameter names; values are the corresponding arguments.
6️. Positional-Only Parameters (introduced in Python 3.8)
Parameters that must be passed by position only and cannot be passed using keyword
syntax.
Key Points:
• Increases code clarity, especially when functions have many optional parameters.
greet(name="Alice", age=25)
Key Points:
Required parameters are those that must be provided with corresponding arguments
when calling the function.
Important Characteristics:
• You must pass the correct number of required arguments during the function call.
• They ensure that the function has enough information to perform its task.
• Required parameters force the caller to think about what information is necessary.
Rule Description
No Defaults Required parameters are ones without any assigned default value.
Correct When calling the function, you must supply arguments in the correct order
Order unless using keyword arguments.
No Skipping You cannot skip required parameters when calling the function.
Type Python doesn't enforce types on required arguments (dynamic typing), but
Flexible logically they should be correct.
• sys.argv
This is a list in Python that contains all command-line arguments passed to the
script.
import sys
print(sys.argv)
import sys
if len(sys.argv) > 1:
Important Notes
o You need to convert them manually if you want numbers (using int(), float(),
etc.).
• Always check the length of sys.argv before accessing an index to avoid IndexError.
import sys
if len(sys.argv) != 3:
else:
name = sys.argv[1]
age = int(sys.argv[2])
Docstrings in Python
• Docstrings are special documentation strings written inside a function, class, or
module.
• They are written inside triple quotes (""" """ or ''' ''').
• They are the first statement after the def, class, or module declaration.
• To help other programmers (or your future self) understand your code.
Syntax
def function_name(parameters):
"""Summary line.
"""
# Function body
return a + b
print(add(5, 3))
print(add.__doc__)
class Calculator:
return x * y
obj = Calculator()
print(obj.multiply(3, 4))
print(Calculator.__doc__)
print(obj.multiply.__doc__)
Important Points
• You can add a more detailed explanation after a blank line if needed.
• It’s a good habit to always add docstrings for functions and classes.
PROGRAM
1. Find Area of Square, Rectangle, Circle
import math
def area_square(side):
def area_circle(radius):
print(area_square(4))
print(area_rectangle(5, 3))
print(area_circle(7))
return a + b
print(add(5, 7))
def is_even(num):
return num % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
print(is_leap(2024)) # True
print(is_leap(1900)) # False
12
123
1234
12345
print(j, end="")
print()
def unique_numbers(numbers):
return list(set(numbers))
nums = [1, 2, 2, 3, 4, 4, 5]
print(unique_numbers(nums))
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(7)
def nth_fibonacci(n):
a, b = 0, 1
for _ in range(n-1):
a, b = b, a + b
return a
print(nth_fibonacci(7))
directory = {}
directory[name] = number
def delete_contact(name):
directory.pop(name, None)
def search_contact(name):
add_contact("Alice", "12345")
add_contact("Bob", "67890")
print(search_contact("Alice"))
delete_contact("Alice")
print(search_contact("Alice"))