Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

? Module 1_ Introduction to Python

This document provides an introduction to Python, covering its features, applications, and versions. It explains key concepts such as variables, data types, operators, and control flow statements, emphasizing Python's beginner-friendly nature and versatility. The document includes examples, Q&A, and MCQs to reinforce understanding.

Uploaded by

Rehan Sabir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

? Module 1_ Introduction to Python

This document provides an introduction to Python, covering its features, applications, and versions. It explains key concepts such as variables, data types, operators, and control flow statements, emphasizing Python's beginner-friendly nature and versatility. The document includes examples, Q&A, and MCQs to reinforce understanding.

Uploaded by

Rehan Sabir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

🧠 Module 1: Introduction to Python

✅ Detailed Notes
🔹 What is Python?
Python is a high-level, interpreted, general-purpose programming language known for its
simple syntax and readability. It supports multiple paradigms, including:

●​ Procedural​

●​ Object-Oriented​

●​ Functional programming​

🔹 Features of Python
●​ Easy to learn & use​

●​ Interpreted language​

●​ Dynamically typed​

●​ Large standard library​

●​ Open-source & free​

●​ Portable (cross-platform)​

●​ Supports GUI programming​

●​ Ideal for AI, Data Science, Web Dev, Automation​

🔹 Python Applications
●​ Web Development (e.g., Django, Flask)​

●​ Data Science & Machine Learning​


●​ Scripting & Automation​

●​ Game Development​

●​ Desktop Applications​

●​ Cybersecurity & Ethical Hacking​

🔹 Python Versions
●​ Python 2.x – Legacy​

●​ Python 3.x – Current version (e.g., 3.12)​

❓ Short Q&A
Q1. Who developed Python?​
Ans: Guido van Rossum in 1991.

Q2. Is Python compiled or interpreted?​


Ans: Interpreted.

Q3. What is the file extension for Python files?​


Ans: .py

Q4. What makes Python beginner-friendly?​


Ans: Simple syntax and readability.

Q5. Name two popular Python frameworks.​


Ans: Django and Flask.
📝 MCQs with Answers
1. Python was developed by:​
a) Dennis Ritchie​


b) Bjarne Stroustrup​
c) Guido van Rossum​
d) James Gosling

2. Python is a ______ language.​


a) Low-level​


b) Compiled​
c) High-level​
d) Machine-level

3. Python supports which of the following paradigms?​


a) Object-oriented​
b) Functional​


c) Procedural​
d) All of the above

4. Which of these is not a Python application?​


a) Web Dev​


b) Data Science​
c) Firmware flashing​
d) AI
🔁 Flowchart: Python Execution Process
[ Write Code (.py file) ]

[ Python Interpreter Reads ]

[ Converts to Bytecode (.pyc) ]

[ Bytecode Sent to PVM (Python Virtual Machine) ]

[ Code Executed Line by Line ]

🧭 Mind Map: Introduction to Python

🐍 Python Programming
|
----------------------------------------------------
| | | | |
Features Applications Paradigms Versions Developer
| | | | |
Easy Syntax Web Dev Procedural Python 2.x Guido van
Rossum
Open Source Data Sci OOP Python 3.x
Interpreted AI/ML Functional
GUI Support Automation

✨ Summary:
●​ 🐍 Python is a high-level, interpreted, and object-oriented programming language.​
●​ 💡 It has easy syntax similar to English, making it beginner-friendly.​
●​ 🛠️ Python supports multiple programming paradigms (OOP, functional, procedural).​
●​ 🔄 It is dynamically typed — no need to declare variable types.​
●​ 📚 Widely used in Web Development, Data Science, AI, Automation, etc.​
✅ Conclusion:
●​ 🌟 Python is a powerful, versatile, and easy-to-learn language that forms the base of
many modern applications.​

●​ 🚀 Learning Python gives you the key to enter many tech fields.​

_________________________________________________________________________

🧠 Module 2: Data Types & Variables


✅ Detailed Notes
🔹 What are Variables?
A variable is a container for storing data values. In Python, you don't need to declare the data
type explicitly because Python is dynamically typed.

●​ Syntax: variable_name = value​

🔹 Data Types in Python


Python has several built-in data types:

●​ Numbers:​

○​ int (Integer): Whole numbers, e.g., 10, -50​

○​ float (Floating-point number): Decimal numbers, e.g., 3.14, -0.001​

○​ complex: Numbers with real and imaginary parts, e.g., 2 + 3j​

●​ Strings:​

○​ Text enclosed in single or double quotes, e.g., "Hello" or 'Python'​

●​ Booleans:​

○​ True or False (Used for conditions and logical operations)​

●​ Lists:​

○​ Ordered collection of items, e.g., [1, 2, 3]​

○​ Can contain different data types​


●​ Tuples:​

○​ Ordered, immutable collection of items, e.g., (1, 2, 3)​

●​ Dictionaries:​

○​ Collection of key-value pairs, e.g., {"name": "Alice", "age": 25}​

●​ Sets:​

○​ Unordered collection of unique items, e.g., {1, 2, 3}​

🔹 Variable Assignment
Python allows variables to be assigned values without explicit declaration. The interpreter
assigns the data type based on the value.

x = 10 # int
y = 3.14 # float
z = "Python" # string

🔹 Type Conversion
Python allows implicit or explicit type conversion:

Implicit Conversion: Automatically done by Python when converting between compatible


types.​

Example:​
num = 5 # int
result = num + 3.5 # result is a float (automatically)

●​

Explicit Conversion: Using functions like int(), float(), str() for manual conversion.​

Example:​

num_str = "10"
num_int = int(num_str) # explicit conversion to int
●​

❓ Short Q&A
Q1. What is a variable in Python?​
Ans: A variable is a name that refers to a memory location used to store a value.

Q2. Name the built-in Python data types.​


Ans: int, float, complex, str, bool, list, tuple, set, dict.

Q3. What is the difference between a list and a tuple?​


Ans: Lists are mutable (can be changed), while tuples are immutable (cannot be changed).

Q4. What does implicit conversion mean?​


Ans: Implicit conversion happens automatically when Python converts one type to another,
e.g., from int to float.

Q5. How do you convert a string into an integer?​


Ans: Use the int() function, e.g., int("123").

📝 MCQs with Answers


1. What is the data type of 5.6 in Python?​


a) int​
b) float​
c) str​
d) complex

2. Which of the following is mutable in Python?​


a) Tuple​
✅ b) List​
c) String​
d) Set

3. What is the result of 10 + 3.5 in Python?​


a) 13​
b) 13.5​
c) 10.0​
d) Error

4. Which Python function is used to convert a string to an integer?​


a) str()​
✅ b) int()​
c) float()​
d) bool()

🔁 Flowchart: Variable Assignment in Python


[ Assign Value to Variable ]

[ Data Type Detected Automatically ]

[ Variable Holds Value ]
🧭 Mind Map: Data Types & Variables
Python Variables
|
-----------------------------------
| | | | |
Numbers Strings Booleans Lists Dictionaries
| | | | |
int, float, Single or True/False Ordered, key-value pairs
complex double quotes | mutable |
| |
'Hello' [1,2,3]

✨ Summary:
📦 Variables store data in memory using assignment (=).
🧮 Data Types:
int 🔢 (e.g., 5)

float 💧 (e.g., 3.14)

str ✉️ (e.g., "Hello")

bool 🔘 (True/False)

list, tuple, dict, set 🔁 (Collections)

🧠 Python is dynamically typed, meaning type is auto-assigned.


✅ Conclusion:
🧰 Knowing data types and variables is crucial for handling and processing data correctly in any
program.
🧠 Module 3: Operators
✅ Detailed Notes
🔹 What are Operators?
Operators are symbols used to perform operations on variables or values. Python supports
various types of operators:

1.​ Arithmetic Operators: Used to perform basic arithmetic operations.​

○​ + (Addition)​

○​ - (Subtraction)​

○​ * (Multiplication)​

○​ / (Division)​

○​ // (Floor Division)​
○​ % (Modulus)​

○​ ** (Exponentiation)​

Example:​

a = 10
b=5
print(a + b) # 15
print(a - b) # 5

2.​
3.​ Comparison Operators: Used to compare two values.​

○​ == (Equal to)​

○​ != (Not equal to)​

○​ > (Greater than)​

○​ < (Less than)​

○​ >= (Greater than or equal to)​

○​ <= (Less than or equal to)​

Example:​

x = 10
y = 20
print(x == y) # False
print(x < y) # True

4.​
5.​ Logical Operators: Used to combine conditional statements.​

○​ and (Returns True if both statements are true)​

○​ or (Returns True if at least one statement is true)​


○​ not (Reverses the result, returns False if the result is true)​

Example:​

a = True
b = False
print(a and b) # False
print(a or b) # True

6.​
7.​ Assignment Operators: Used to assign values to variables.​

○​ = (Assign)​

○​ += (Add and assign)​

○​ -= (Subtract and assign)​

○​ *= (Multiply and assign)​

○​ /= (Divide and assign)​

Example:​

c=5
c += 3 # c = c + 3, so c becomes 8

8.​
9.​ Bitwise Operators: Used to perform bit-level operations.​

○​ & (AND)​

○​ | (OR)​

○​ ^ (XOR)​

○​ ~ (NOT)​

○​ << (Left shift)​


○​ >> (Right shift)​

Example:​

a = 10 # 1010 in binary
b = 4 # 0100 in binary
print(a & b) # 0 (bitwise AND)

10.​
11.​Identity Operators: Used to check if two variables refer to the same object in memory.​

○​ is (Returns True if both variables refer to the same object)​

○​ is not (Returns True if both variables do not refer to the same object)​

Example:​

x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False (different memory locations)

12.​
13.​Membership Operators: Used to test if a value is in a sequence (like a list or string).​

○​ in (Returns True if value is found in the sequence)​

○​ not in (Returns True if value is not found in the sequence)​

Example:​

a = [1, 2, 3]
print(2 in a) # True

14.​

❓ Short Q&A
Q1. What is the difference between = and == in Python?​
Ans: = is an assignment operator, used to assign a value to a variable. == is a comparison
operator, used to compare two values for equality.

Q2. What does the modulus operator % do in Python?​


Ans: The modulus operator returns the remainder of the division between two numbers.

Q3. What is the purpose of logical operators like and, or, and not?​
Ans: Logical operators are used to combine conditional statements or reverse the results of a
condition.

Q4. How do assignment operators work in Python?​


Ans: Assignment operators modify the value of a variable. For example, x += 2 is equivalent
to x = x + 2.

Q5. What is the difference between is and ==?​


Ans: is checks if two variables refer to the same object in memory, while == checks if the
values of the variables are equal.

📝 MCQs with Answers


1. What is the result of 5 // 2 in Python?​


a) 2.5​
b) 2​
c) 3​
d) Error

2. Which operator is used for exponentiation in Python?​


a) *​
✅ b) **​
c) ^​
d) //

3. What does the is not operator do?​


a) Checks if the two objects are equal​
b) Checks if the two objects are not the same​
c) Compares the values of two objects​
d) None of the above

4. Which of the following is a membership operator?​


a) ==​
✅ b) in​
c) &​
d) +

🔁 Flowchart: Arithmetic Operations in Python


Start

[ Operand 1 and Operand 2 ]

[ Select Operation (+, -, *, /, %)]

[ Perform Operation ]

[ Return Result ]

🧭 Mind Map: Operators in Python


Python Operators
|
---------------------------------------------------
| | | | |
Arithmetic Comparison Logical Assignment Bitwise
| | | | |
+, -, *, / ==, !=, < and, or, not =, +=, -= &, |, ^, ~
| | | | |
Floor Division >, <=, >= True/False +=, -= <<, >>

✨ Summary:
●​ ➕ Arithmetic Operators: +, -, *, /, **, %​
●​ ⚖️ Relational/Comparison: ==, !=, >, <, >=, <=​
●​ 🔁 Assignment: =, +=, -=, etc.​
●​ 🤔 Logical: and, or, not​
●​ 🧠 Bitwise: &, |, ^, ~, <<, >>​
●​ 🔍 Membership: in, not in​
✅ Conclusion:
●​ ⚙️ Operators allow you to perform operations, compare values, and create logical
conditions in programs.

🧠 Module 4: Control Flow Statements


✅ Detailed Notes
🔹 What are Control Flow Statements?
Control flow statements allow you to control the execution order of your code based on
conditions and loops. They include:

1.​ If Statements: Used to execute a block of code only if a certain condition is true.​

Syntax:​

if condition:
# block of code

○​

Example:​

a = 10
if a > 5:
print("a is greater than 5")

○​
2.​ If-Else Statements: Used to execute one block of code if the condition is true, and
another block if it is false.​

Syntax:​

if condition:
# block of code if true
else:
# block of code if false

○​

Example:​

a=4
if a > 5:
print("a is greater than 5")
else:
print("a is not greater than 5")

○​
3.​ If-Elif-Else Statements: Used to check multiple conditions.​

Syntax:​

if condition1:
# block of code if condition1 is true
elif condition2:
# block of code if condition2 is true
else:
# block of code if neither condition1 nor condition2 is true

○​

Example:​

a=3
if a > 5:
print("a is greater than 5")
elif a == 3:
print("a is 3")
else:
print("a is less than 5")

○​
4.​ While Loops: Used to repeatedly execute a block of code as long as the condition is
true.​

Syntax:​

while condition:
# block of code

○​

Example:​

i=1
while i <= 5:
print(i)
i += 1

○​
5.​ For Loops: Used to iterate over a sequence (such as a list, tuple, or range).​

Syntax:​

for variable in sequence:
# block of code

○​

Example:​

for i in range(5):
print(i)

○​
6.​ Break Statement: Used to break out of the current loop.​

Example:​

for i in range(5):
if i == 3:
break
print(i)

○​
7.​ Continue Statement: Used to skip the current iteration of the loop and continue with the
next iteration.​

Example:​

for i in range(5):
if i == 3:
continue
print(i)

○​
8.​ Pass Statement: Used as a placeholder for future code.​
Example:​

for i in range(5):
if i == 3:
pass # Placeholder, do nothing
print(i)

○​

❓ Short Q&A
Q1. What is the difference between if and if-else statements?​
Ans: The if statement executes code only when a condition is true, while if-else provides
an alternative block of code that executes when the condition is false.

Q2. What is the purpose of the continue statement in a loop?​


Ans: The continue statement skips the current iteration of the loop and moves to the next
iteration.

Q3. What does the break statement do?​


Ans: The break statement terminates the current loop and exits it immediately.

Q4. How do while and for loops differ?​


Ans: A while loop continues as long as a condition is true, while a for loop iterates over a
sequence (like a list or range).

Q5. What is the pass statement used for?​


Ans: The pass statement is a placeholder for future code, used when a statement is
syntactically required but you don't want to execute any code.

📝 MCQs with Answers


1. What will the following code output?

x = 10
if x > 5:
print("Greater")
else:
print("Smaller")

a) Smaller​
b) Greater​
c) Error​
d) Nothing

2. Which statement will stop the execution of a loop immediately?​


a) continue​


b) pass​
c) break​
d) exit

3. What will the following code print?

for i in range(3):
if i == 1:
continue
print(i)


a) 0 1 2​
b) 0 2​
c) 1 2​
d) 1

4. Which loop will execute its block of code at least once, even if the condition is false?​


a) for loop​
b) while loop​
c) if loop​
d) do-while loop

🔁 Flowchart: If-Else Statement


Start

[Condition]

True/False

[If Block] → [Else Block]

End
🧭 Mind Map: Control Flow Statements
Control Flow
|
----------------------------------------------
| | | |
If Statements Loops Break/Continue Pass Statement
| | | |
if, if-else, while, for break, continue pass
elif |

range, list, tuple, etc.

✨ Summary:
●​ 🤖 Used for decision making.​
●​ ✅ Executes different code blocks depending on conditions.​
🧾 Syntax​

if condition:

# do this
elif another_condition:

# do something else

else:

# default action

✅ Conclusion:
●​

●​ 🧭 Control Flow lets your program make intelligent decisions, just like human thinking.​

🧠 Module 5: Data Types


✅ Detailed Notes
🔹 What are Data Types?
Data types define the type of value a variable holds in Python. They determine what operations
can be performed on a particular value.
1.​ Numeric Types:​

○​ int: Integer numbers (whole numbers).​

■​ Example: a = 10​

○​ float: Floating-point numbers (decimals).​

■​ Example: b = 10.5​

○​ complex: Complex numbers (real and imaginary parts).​

■​ Example: c = 3 + 4j​

2.​ Text Type:​

○​ str: String (text).​

■​ Example: s = "Hello, World!"​

3.​ Sequence Types:​

○​ list: Ordered collection of items (mutable).​

■​ Example: my_list = [1, 2, 3]​

○​ tuple: Ordered collection of items (immutable).​

■​ Example: my_tuple = (1, 2, 3)​

○​ range: Sequence of numbers.​

■​ Example: my_range = range(5)​

4.​ Mapping Type:​

○​ dict: Dictionary (key-value pairs).​

■​ Example: my_dict = {"name": "John", "age": 30}​

5.​ Set Types:​


○​ set: Unordered collection of unique items.​

■​ Example: my_set = {1, 2, 3}​

○​ frozenset: Immutable set.​

■​ Example: my_frozenset = frozenset([1, 2, 3])​

6.​ Boolean Type:​

○​ bool: Boolean value (True or False).​

■​ Example: flag = True​

7.​ Binary Types:​

○​ bytes: Immutable sequence of bytes.​

■​ Example: b = b'Hello'​

○​ bytearray: Mutable sequence of bytes.​

■​ Example: ba = bytearray([1, 2, 3])​

○​ memoryview: A memory view object that exposes an array's memory.​

■​ Example: mv = memoryview(b'Hello')​

8.​ None Type:​

○​ None: Represents the absence of a value.​

■​ Example: x = None​

❓ Short Q&A
Q1. What is the difference between a list and a tuple in Python?​
Ans: A list is mutable, meaning its elements can be changed, while a tuple is immutable,
meaning once created, its elements cannot be modified.
Q2. What is a dictionary in Python?​
Ans: A dictionary is a collection of key-value pairs where each key is unique, and each key
maps to a value.

Q3. What does None represent in Python?​


Ans: None is used to represent the absence of a value or a null value in Python.

Q4. How is a set different from a list?​


Ans: A set is an unordered collection of unique items, whereas a list can have duplicate
elements and maintains the order of insertion.

Q5. What is the purpose of frozenset in Python?​


Ans: A frozenset is an immutable version of a set, which means its elements cannot be
modified after creation.

📝 MCQs with Answers


1. Which of the following is a mutable data type in Python?

✅ a) list​

b) tuple​
c) frozenset​
d) str

2. What does the following code print?

x = (1, 2, 3)

x[0] = 5

a) [1, 2, 3]​


b) (1, 2, 3)​
c) Error​
d) 5

3. What is the output of this code?

my_dict = {"name": "John", "age": 30}


print(my_dict["name"])


a) John​
b) "John"​
c) "name"​
d) Error

4. Which data type represents a collection of unique items in Python?​


a) list​


b) tuple​
c) set​
d) dict

5. What does None mean in Python?​


a) False​


b) Null​
c) No value​
d) Empty

🔁 Flowchart: List Operations


Start

[Create List]

[Add Item] → [Remove Item] → [Access Item]


[Print List]

End

🧭 Mind Map: Data Types


Data Types

------------------------------------------------

| | | | |

Numeric Sequence Mapping Set Boolean

| | | | |

int, float, list, tuple, dict set True/False

complex range

✨ Summary:
●​ 🔁 Loops repeat code until a condition is met.​
●​ 🔄 for loop: for iterating over a sequence.​
●​ 📍 while loop: continues while a condition is True.​
●​ 🛑 break: exit loop early.​
●​ ⏭️ continue: skip current iteration.​
●​ 🤫 pass: do nothing (placeholder).​
✅ Conclusion:
●​ 🧩 Loops make programs efficient, shorter, and help handle repetition easily.

🧠 Module 6: Functions
✅ Detailed Notes
🔹 What are Functions in Python?
A function is a block of reusable code that performs a specific task. It allows us to write code
once and reuse it multiple times, improving code readability and reducing redundancy.

1.​ Defining a Function:​

○​ Use the def keyword to define a function.​

Syntax:​

def function_name(parameters):

# function body

return value

○​
Example:​

def greet(name):

return f"Hello, {name}!"

○​
2.​ Function Parameters:​

○​ Functions can accept input values known as parameters (also called arguments).​

○​ You can define parameters in the function's definition.​

Example:​

def add(a, b):

return a + b

○​
3.​ Return Statement:​

○​ The return keyword is used to return a result from the function.​

○​ If a function doesn't have a return statement, it implicitly returns None.​

4.​ Types of Functions:​

○​ Built-in Functions: Functions that come with Python, like print(), len(), etc.​

○​ User-Defined Functions: Functions created by the user.​

5.​ Function Arguments:​

○​ Positional Arguments: Passed to a function in the correct order.​

○​ Keyword Arguments: Passed by explicitly naming the parameter and providing


its value.​

○​ Default Arguments: Parameters with default values if not passed.​


○​ Variable-Length Arguments: Functions that accept any number of arguments
(using *args and **kwargs).​

6.​ Lambda Functions:​

○​ A lambda function is a small anonymous function defined with the lambda


keyword.​

Syntax:​

lambda arguments: expression

○​

Example:​

square = lambda x: x ** 2

○​
7.​ Recursion:​

○​ A function that calls itself is called recursive.​

Example:​

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

○​

❓ Short Q&A
Q1. What is the purpose of the return statement in a function?​
Ans: The return statement is used to return a result or output from the function back to the
caller.

Q2. What are positional arguments?​


Ans: Positional arguments are arguments that must be passed in the correct order when
calling the function.

Q3. What is a lambda function?​


Ans: A lambda function is an anonymous function defined using the lambda keyword. It's
generally used for small, simple operations.

Q4. How can you define a function that accepts an arbitrary number of arguments?​
Ans: You can define a function that accepts an arbitrary number of arguments using *args for
non-keyword arguments and **kwargs for keyword arguments.

Q5. What is recursion?​


Ans: Recursion occurs when a function calls itself to solve a problem. It generally requires a
base case to stop the recursion.

📝 MCQs with Answers


1. What is the output of the following code?

def greet(name):

return f"Hello, {name}!"

print(greet("Alice"))


a) Hello, Alice​
b) "Hello, Alice!"​
c) greet("Alice")​
d) Error

2. Which of the following is used to define a function in Python?​


a) function​


b) define​
c) def​
d) func

3. What will be the output of the following code?


def multiply(a, b=2):

return a * b

print(multiply(3))

a) 3​


b) 6​
c) 6​
d) Error

4. How do you define a function that accepts an arbitrary number of arguments?​


a) def function(*args, **kwargs):​


b) def function(args, kwargs):​
*c) def function(args):​
d) def function(args):

5. What is the correct syntax for defining a lambda function?​


a) lambda function(args):​
b) lambda args: expression​
c) def lambda(args):​
d) lambda expression(args):

🔁 Flowchart: Function Call


Start

[Define Function]

[Call Function]


[Return Value]

End

🧭 Mind Map: Functions


Functions

----------------------------------------------------

| | | | |

Definition Parameters Return Types Recursion

| | | | |

def function pos, kw, def return value built-in, user calls itself

✨ Summary:
🧵 A string is a sequence of characters inside quotes.
📐 Strings are immutable (cannot be changed after creation).
🛠️ Useful Methods: .lower(), .upper(), .replace(), .find(), .split(), etc.
🔢 Indexing and slicing supported: "Hello"[1:4] → 'ell'

✅ Conclusion:
📝 Strings are essential for handling text-based data — very common in every application

🧠 Module 7: Control Flow


✅ Detailed Notes
🔹 What is Control Flow?
Control flow refers to the order in which individual statements, instructions, or function calls are
executed or evaluated in a program. Python provides control flow statements that allow us to
modify the flow of execution in our programs.

🔸 Conditional Statements (If, Elif, Else)


1.​ if statement:​
○​ Used to test a condition.​

○​ If the condition is True, the code block inside the if will execute.​

Syntax:​

if condition:

# code to execute

○​
2.​ elif statement:​

○​ Stands for "else if" and allows checking multiple conditions.​

○​ Only the first condition that evaluates to True will execute.​

Syntax:​

if condition1:

# code

elif condition2:

# code

○​
3.​ else statement:​

○​ Executes when all preceding if and elif conditions are False.​

Syntax:​

else:

# code

○​

Example:

x = 10
if x > 5:

print("x is greater than 5")

elif x == 5:

print("x is equal to 5")

else:

print("x is less than 5")

🔸 Loops (For, While)


1.​ for loop:​

○​ Used to iterate over a sequence (like a list, tuple, string, etc.).​

Syntax:​

for item in sequence:

# code to execute

○​

Example:​

for i in range(5):

print(i)

2.​
3.​ while loop:​

○​ Repeats a block of code as long as a condition is True.​

Syntax:​

while condition:
# code to execute

○​

Example:​

count = 0

while count < 5:

print(count)

count += 1

4.​

🔸 Break, Continue, and Pass Statements


1.​ break:​

○​ Exits the loop completely.​

Example:​

for i in range(10):

if i == 5:

break

print(i)

○​
2.​ continue:​

○​ Skips the current iteration and moves to the next iteration.​

Example:​

for i in range(5):

if i == 2:
continue

print(i)

○​
3.​ pass:​

○​ A placeholder that does nothing.​

○​ Useful when you want to define an empty loop or function body.​

Example:​

for i in range(5):

pass

○​

❓ Short Q&A
Q1. What is the purpose of the elif statement?​
Ans: The elif statement allows checking multiple conditions sequentially. If the previous if
or elif conditions are False, it checks the next one.

Q2. How does a for loop work in Python?​


Ans: A for loop is used to iterate over a sequence, such as a list, tuple, or string, and
executes a block of code for each item in the sequence.

Q3. What is the difference between break and continue?​


Ans:

●​ break exits the loop completely.​


●​ continue skips the current iteration and moves to the next one.​

Q4. What is the use of the pass statement?​


Ans: The pass statement is used as a placeholder when you don't want to execute any code in
a loop or function.

📝 MCQs with Answers


1. What is the output of the following code?

x = 10

if x > 5:

print("x is greater than 5")

else:

print("x is less than 5")


a) x is equal to 5​
b) x is greater than 5​
c) Error​
d) x is less than 5

2. Which of the following is used to stop a loop in Python?​


a) continue​
b) break​
c) pass​
d) exit

3. What will be the output of the following code?

for i in range(3):
if i == 1:

continue

print(i)

a) 1​


b) 0 1 2​
c) 0 2​
d) Error

4. Which of the following will cause an infinite loop?​


a) while False:​
✅ b) while True:​
c) for i in range(0, 0):​
d) None of the above

5. What is the correct syntax for an if statement in Python?​


a) if condition then:​
b) if condition:​
c) if (condition) then:​
d) if: condition

🔁 Flowchart: Control Flow


Start

[Condition]----Yes---> [Code Block 1] --> [Exit]

No


[Code Block 2] --> [Exit]

🧭 Mind Map: Control Flow


Control Flow

-----------------------------------------------

| | | |

If-Else Loops Break Continue

| | | |

Checks condition Repeats code Exits loop Skips iteration

✨ Summary:
●​ 🔄 Converts one data type to another.​
●​ 🔢 Example:​
○​ int("5") → 5​

○​ str(10) → "10"​

○​ float("3.14") → 3.14​

●​ ✅ Ensures correct operations (e.g., adding int + int not int + str)

✅ Conclusion:
●​ 🧪 Type casting helps avoid errors and ensures compatibility between different data
types.

🧠 Module 8: Functions
✅ Detailed Notes
🔹 What are Functions?
A function is a block of code that only runs when it is called. Functions allow you to organize
and reuse code. They can accept inputs (parameters), process them, and return outputs
(results).

🔸 Defining a Function
Syntax to define a function:​

def function_name(parameters):

# code to execute

return result

1.​
Example:​

def greet(name):

return f"Hello, {name}!"

print(greet("Alice"))

2.​

🔸 Function Parameters
1.​ Positional Parameters:​

○​ Parameters defined in the function signature are positional parameters, meaning


the order in which they are passed is important.​

Example:​

def add(a, b):

return a + b

print(add(2, 3)) # Outputs: 5

2.​
3.​ Keyword Parameters:​

○​ You can pass arguments to a function using the parameter name. The order
doesn't matter here.​

Example:​

def add(a, b):

return a + b
print(add(b=3, a=2)) # Outputs: 5

4.​
5.​ Default Parameters:​

○​ Default values can be set for parameters, making them optional when calling the
function.​

Example:​

def greet(name, message="Hello"):

return f"{message}, {name}!"

print(greet("Alice")) # Outputs: Hello, Alice!

print(greet("Bob", "Goodbye")) # Outputs: Goodbye, Bob!

6.​
7.​ Variable-length Parameters:​

○​ Use *args for non-keyword variable-length arguments (tuple).​

○​ Use **kwargs for keyword variable-length arguments (dictionary).​

Example:​

def greet(*args, **kwargs):

print("Args:", args)

print("Kwargs:", kwargs)

greet("Alice", "Bob", message="Hello", time="Morning")

8.​

🔸 Returning Values
●​ Functions can return values using the return keyword.​

Once a function encounters return, it exits, and the value is returned.​



Example:​

def multiply(a, b):

return a * b

result = multiply(3, 4)

print(result) # Outputs: 12

●​

🔸 Lambda Functions (Anonymous Functions)


●​ A lambda function is a small anonymous function defined with the lambda keyword.​

●​ It can take any number of arguments, but only one expression.​

Lambda functions are typically used for short, one-line functions.​



Syntax:​

lambda arguments: expression

Example:​

square = lambda x: x ** 2

print(square(5)) # Outputs: 25

●​

❓ Short Q&A
Q1. What is a function in Python?​
Ans: A function is a block of code that performs a specific task. It can accept inputs
(parameters) and return outputs (results).

Q2. What is the difference between *args and **kwargs?​


Ans:

●​ *args allows a function to accept a variable number of non-keyword arguments, which


are stored as a tuple.​

●​ **kwargs allows a function to accept a variable number of keyword arguments, which


are stored as a dictionary.​

Q3. Can you explain the use of the return statement in a function?​
Ans: The return statement is used to send back a result from a function. It allows the function
to output a value after performing its task.

Q4. What is a lambda function?​


Ans: A lambda function is a short, anonymous function defined with the lambda keyword. It
can take any number of arguments, but only one expression.

📝 MCQs with Answers


1. What will the following code output?

def greet(name, message="Hi"):

return f"{message}, {name}!"

print(greet("Alice"))


a) Hello, Alice!​
b) Hi, Alice!​
c) Alice!​
d) Error
2. How do you define a function in Python?​


a) function(){}​
b) def function_name():​
c) function_name()​
d) create function function_name():

3. What is the output of the following code?

multiply = lambda x, y: x * y

print(multiply(3, 4))

a) 7​


b) 12​
c) 12​
d) Error

4. What will be printed if the following code is executed?

def func(*args):

for arg in args:

print(arg)

func(1, 2, 3)

a) 1​


b) 1 2 3​
c) 1 2 3​
d) Error

5. What does the return statement do in a function?​


a) It stops the function execution​


b) It outputs a value from the function​
c) It exits the function and sends a result back to the caller​
d) It defines the function
🔁 Flowchart: Functions
Start

[Define Function]

[Call Function]

[Execute Code]

[Return Value] --> [Exit]

🧭 Mind Map: Functions


Functions

------------------------------------------------

| | |

Definition Parameters Returning Values

| | |

def function_name() Positional, Keyword, With `return` statement


| Default, *args, **kwargs

Executes code

✨ Summary:
⚙️ A block of reusable code that performs a task.
🔑 Defined using def keyword.
📥 Takes parameters and returns output using return.
🧱 Example:
def greet(name): return "Hello " + name

✅ Conclusion:
🛠️ Functions make code modular, readable, reusable, and easier to manage.

🧠 Module 9: Modules and Packages


✅ Detailed Notes
🔹 What are Modules and Packages?
●​ Modules are files containing Python code that define functions, classes, and variables,
and also include runnable code.​
●​ Packages are a way of structuring Python’s module namespace by using “dotted
module names.” A package is simply a directory that contains multiple modules or
sub-packages.​

🔸 Using Modules
1.​ Importing a Module:​

○​ You can import a module using the import keyword.​

Example:​

import math

print(math.sqrt(16)) # Outputs: 4.0

2.​
3.​ Import Specific Functions or Variables:​

○​ You can import specific functions or variables from a module.​

Example:​

from math import pi

print(pi) # Outputs: 3.141592653589793

4.​
5.​ Renaming Modules:​

○​ You can rename a module during import using the as keyword.​

Example:​

import math as m

print(m.sqrt(25)) # Outputs: 5.0

6.​
🔸 Creating Your Own Module
1.​ Defining a Module:​

○​ Any Python file (.py) can be a module. To create your own module, define
functions and variables in a .py file.​

Example (in mymodule.py):​



def add(a, b):

return a + b

def subtract(a, b):

return a - b

2.​
3.​ Using Your Module:​

○​ Once you have created a module, you can import it into another script using the
import statement.​

Example:​

import mymodule

print(mymodule.add(5, 3)) # Outputs: 8

4.​

🔸 Python Standard Library


Python comes with a wide range of built-in modules, called the Standard Library, which
includes useful modules like math, os, sys, datetime, json, and more.

Example:
import os

print(os.getcwd()) # Outputs the current working directory

🔸 Packages
1.​ Creating a Package:​

○​ A package is a directory containing multiple modules or sub-packages. It must


contain a special __init__.py file (which can be empty) to indicate that the
directory is a Python package.​

2.​ Using a Package:​

○​ After creating a package, you can import it similarly to modules.​

Example (in mypackage/__init__.py):​



def greet(name):

return f"Hello, {name}!"

To use the package:​



from mypackage import greet

print(greet("Alice")) # Outputs: Hello, Alice!

3.​

❓ Short Q&A
Q1. What is the difference between a module and a package in Python?​
Ans: A module is a single Python file containing code, whereas a package is a collection of
modules stored in a directory.

Q2. How do you import specific functions from a module?​


Ans: You can use the from module import function syntax.
Q3. What is __init__.py file used for?​
Ans: It is used to mark a directory as a Python package. It can be empty or contain initialization
code for the package.

Q4. Can you create your own modules?​


Ans: Yes, any Python file with .py extension can be a module, and you can create your own
by defining functions or variables in that file.

📝 MCQs with Answers


1. What does the following code do?

import math

print(math.pow(2, 3))


a) Prints 2 raised to the power of 3​
b) Prints 8​
c) Prints 6​
d) Error

2. Which of the following is a correct way to import a function from a module?​


a) from math import sqrt()​
✅ b) from math import sqrt​
c) import sqrt from math​
d) import sqrt as math

3. How do you define a package in Python?​


a) Create a .py file in a directory​
✅ b) Create a directory with __init__.py file inside​
c) Create a module.py file​
d) Create a .zip file containing Python scripts

4. Which of the following Python modules help in working with JSON data?​
a) os​
b) datetime​
✅ c) json​
d) math
5. What is the purpose of the __init__.py file in a Python package?​
a) It contains the main function of the package​


b) It defines the functions of the package​
c) It marks the directory as a package​
d) It is not necessary for a package

🔁 Flowchart: Modules and Packages


Start

[Create Module (.py file)]

[Define Functions/Variables]

[Import Module]

[Use Functions/Variables]

[Exit]

🧭 Mind Map: Modules and Packages


Modules and Packages

|
-----------------------------------------------------------

| | |

Importing Creating Your Own Python Standard Library

| Module |

import module def module_name() os, sys, math, json, etc.

from module import function

✨ Summary:
●​ 🧯 Prevents program from crashing on error.​
●​ 🔐 Use try, except, else, finally blocks.​
❗ Example:​

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!")

✅ Conclusion:
●​

●​ 🔒 Exception handling makes code robust, user-friendly, and safe from unexpected
crashes.​
__________________________________________________________________

🌟 Final Wish & Motivation 🌟


💬 "Success doesn’t come from what you do occasionally, it comes from what you do
consistently."

📚 You’ve put in the effort, revised with focus, and prepared every concept with clarity.​
Now, go to your exam with confidence in your heart ❤️, clarity in your mind 🧠, and faith in
your hard work 💪.

🔥 Believe in yourself. You were born to achieve greatness.​


No paper is bigger than your preparation, no question harder than your determination.

🌈 “When you feel like quitting, remember why you started.”​


You’ve already done the hard part — trust yourself and shine! ✨
🎓 May you pass with flying colors, and may this exam become a stepping stone toward
your bright future. Ameen.

📝👩‍💻 These notes and this journey were lovingly created by​
Shasmeen Zahra

💖

– with dedication, heart, and hope for your success.

You might also like