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

Machine Learning using Python

The document introduces key features of Python, highlighting its readability, high-level nature, and beginner-friendly syntax. It explains Python's dynamic typing, various data types, and the use of input and print functions, along with different types of operators. Additionally, it covers control flow with conditional statements and loops, as well as list processing and the differences between logical and bitwise operators.

Uploaded by

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

Machine Learning using Python

The document introduces key features of Python, highlighting its readability, high-level nature, and beginner-friendly syntax. It explains Python's dynamic typing, various data types, and the use of input and print functions, along with different types of operators. Additionally, it covers control flow with conditional statements and loops, as well as list processing and the differences between logical and bitwise operators.

Uploaded by

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

Introduction of Machine Learning using Python

Unit 4
1.What are the main features of Python that make it a high-level and beginner-friendly programming
language?

1. Easy to Read and Write


 Python looks like plain English.
 No need to use {}, ;, or other confusing symbols.
 Example:

python
CopyEdit
print("Hello, World!")

✅ 2. High-Level Language
 You don’t have to worry about low-level details like memory management.
 Python handles complex stuff like allocating memory automatically.

✅ 3. Interpreted Language
 Python runs line by line, making it easier to test and debug.
 No need to compile code — just run the file directly.

✅ 4. Beginner-Friendly
 Simple syntax and fewer rules = perfect for beginners.
 You can do a lot with just a few lines of code.

✅ 5. Free and Open Source


 Python is free to download and use.
 You can also see and contribute to its source code.

✅ 6. Portable
 Write code on Windows, run it on Mac or Linux.
 Python works on all major operating systems.

✅ 7. Huge Library Support


 Python comes with built-in libraries for:
o Math, file handling, web development, data science, and more.
o Example: math, datetime, os, random, pandas, etc.

✅ 8. Object-Oriented and Procedural


 You can use functions or classes depending on what you're comfortable with.
 Supports OOP (Object-Oriented Programming) fully.

✅ 9. Large Community and Support


 Python has a huge community.
 You can find tutorials, forums, videos, and solutions easily when stuck.

✅ 10. Used in Many Areas


 Web development (Flask, Django)
 Data Science and ML (Pandas, NumPy, Scikit-learn)
 Automation (Selenium, PyAutoGUI)
 Scripting, Game Dev, AI, etc.

🧠 Quick Summary Table

Feature Why It’s Helpful


Simple Syntax Easy to learn & use
Interpreted Run code line-by-line
Free & Open Source No cost, community-driven
Portable Works on all OS
Libraries Ready-made tools for everything
Multi-paradigm Use functions or classes (OOP)
Beginner-Friendly Great for students and professionals
2. Explain the difference between dynamically typed and statically typed languages. What type is Python,
and how does this affect variable declaration?

Dynamically Typed vs Statically Typed Languages


Feature Dynamically Typed Statically Typed
Type Checking Done at runtime (while running the code) Done at compile-time (before running code)
Variable Declaration No need to declare the type Must declare the type of variable
Flexibility More flexible (but can lead to errors later) More strict (catches errors early)
Example Languages Python, JavaScript, Ruby Java, C, C++, C#, Go

✅ Python is Dynamically Typed

That means in Python:

 You don’t have to mention data types when declaring variables.


 Python automatically understands the data type based on the value you assign.

💡 Example:
python
CopyEdit
x = 10 # Python knows this is an integer
x = "Hello" # Now x is a string (and that’s totally fine in Python)

In contrast, in a statically typed language like Java:

java
CopyEdit
int x = 10; // Type must be declared
x = "Hello"; // ❌ Error! You can't change the type

🔍 How Does This Affect Variable Declaration in Python?


 ✅ No need to write int, float, string, etc.
 ✅ Code is shorter and easier to write.
 ⚠️But: You might get type-related bugs only when you run the code (not before).

🎓 In Summary:

Point Python (Dynamically Typed)


Type declaration Not needed
Flexibility High
Error detection Happens during runtime
Point Python (Dynamically Typed)
Ease of learning Very beginner-friendly

3. Describe the various data types available in Python. Give examples of at least five different data types.

1. Numeric Types
a) int – Integer (whole numbers)
python
CopyEdit
x = 10

b) float – Decimal numbers


python
CopyEdit
price = 99.99

c) complex – Complex numbers


python
CopyEdit
z = 2 + 3j

📝 2. String (str) – Text data


python
CopyEdit
name = "Harry"

 Strings can be inside single or double quotes.

✅ 3. Boolean (bool) – True or False


python
CopyEdit
is_active = True
is_paid = False

 Used in conditions and logic.

📚 4. List – Ordered, changeable collection


python
CopyEdit
fruits = ["apple", "banana", "cherry"]

 Allows duplicates, can store different data types.

5. Tuple – Ordered, unchangeable collection


python
CopyEdit
dimensions = (10, 20, 30)

 Like a list, but cannot be modified (immutable).

📦 6. Dictionary (dict) – Key-value pairs


python
CopyEdit
student = {"name": "Harry", "age": 21}

 Access values using keys.

🟩 7. Set – Unordered, unique items


python
CopyEdit
colors = {"red", "green", "blue"}

 Removes duplicates automatically.

🧠 Examples of 5 Different Data Types

Data Type Example Code Description


int x = 5 Whole number
float price = 19.99 Decimal number
str name = "Harry" Text string
list marks = [80, 90, 85] List of values
dict info = {"course": "ML", "year": 3} Dictionary with key-value pairs

4. What is the purpose of using input() and print() functions in Python? Write a program that takes two
numbers as input and displays their sum.
Purpose of input() and print() in Python
✅ input():

 Used to take input from the user.


 Whatever you type is taken as a string by default.

python
CopyEdit
name = input("Enter your name: ")

✅ print():

 Used to display messages or output on the screen.

python
CopyEdit
print("Welcome to Python!")

🧮 Python Program: Add Two Numbers


python
CopyEdit
# Taking input from the user
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")

# Converting input to integers


num1 = int(num1)
num2 = int(num2)

# Calculating the sum


sum = num1 + num2

# Displaying the result


print("The sum is:", sum)

💡 Sample Output:
yaml
CopyEdit
Enter first number: 10
Enter second number: 20
The sum is: 30

🔁 Note: If you're adding decimal numbers, use float() instead of int().

5. List and explain the different types of operators in Python. Include examples of arithmetic, relational,
assignment, and logical operators.
1. Arithmetic Operators
Used for math calculations like add, subtract, multiply, divide, etc.

Operator Meaning Example Output


+ Addition 3 + 2 5
- Subtraction 5 - 3 2
* Multiplication 4 * 2 8
/ Division 10 / 2 5.0
// Floor Division 10 // 3 3
% Modulus (Remainder) 10 % 3 1
** Exponent (Power) 2 ** 3 8

📊 2. Relational / Comparison Operators


Used to compare values. They return True or False.

Operator Meaning Example Output


== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 4 > 2 True
< Less than 3 < 1 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 4 <= 6 True

📥 3. Assignment Operators
Used to assign values to variables.

Operator Meaning Example Same as


= Assign value x = 10
+= Add and assign x += 5 x = x + 5
-= Subtract and assign x -= 3 x = x - 3
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 4 x = x / 4
//= Floor divide and assign x //= 2 x = x // 2
**= Exponent and assign x **= 3 x = x ** 3
%= Modulus and assign x %= 2 x = x % 2

💡 4. Logical Operators
Used to combine conditions. They return True or False.
Operator Meaning Example Result
and True if both are True x > 5 and x < 10 True/False
or True if at least one is True x > 10 or x < 20 True/False
not Inverts the result not(x > 10) True/False

🎯 Example Program
python
CopyEdit
a = 10
b = 5

# Arithmetic
print(a + b) # 15

# Relational
print(a > b) # True

# Assignment
a += 2
print(a) # 12

# Logical
print(a > 5 and b < 10) # True

6. Explain Boolean values in Python. How are Boolean expressions used in conditional execution (if-elif-else)
statements?

Boolean Values in Python

In Python, Boolean values are the two constant values that represent truth values:

 True
 False

They are used to make decisions in programs.

python
CopyEdit
x = True
y = False

🔍 How Boolean Expressions Work

A Boolean expression is any expression that returns either True or False.

For example:

python
CopyEdit
5 > 3 # True
10 == 5 # False
a != b # Depends on the values of a and b

🚦 Using Boolean Values in Conditional Statements

Conditional statements like if, elif, and else check Boolean conditions to decide which block of code to run.

✅ Example 1:
python
CopyEdit
age = 18

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Output:

css
CopyEdit
You are eligible to vote.

✅ The condition age >= 18 returns True, so the code inside the if block runs.

✅ Example 2 (if-elif-else):
python
CopyEdit
marks = 75

if marks >= 90:


print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")

Output:

makefile
CopyEdit
Grade: B

🔁 Python evaluates each Boolean expression top to bottom, and executes the first one that is True.

📌 Summary:

Term Description

True / False Boolean values


Term Description

if, elif, else Used to control program flow

Conditions Boolean expressions like x > 5, a == b

7. What is the difference between a while loop and a for loop in Python? Illustrate with appropriate
examples.

1. while Loop

 Repeats as long as a condition is True.


 You must manually update the loop variable inside the loop.
 Useful when the number of repetitions is not known in advance.

✅ Example:
python
CopyEdit
count = 1
while count <= 5:
print("Count is:", count)
count += 1

🧠 Here, the loop runs until count becomes greater than 5.

🔂 2. for Loop

 Repeats over a sequence (like a list, string, or range).


 Python automatically handles the loop variable.
 Used when the number of repetitions is known or you want to loop through a collection.

✅ Example:
python
CopyEdit
for i in range(1, 6):
print("Count is:", i)

🧠 This also runs 5 times, from 1 to 5.

🔍 Key Differences:

Feature while Loop for Loop

Condition-based Yes No (sequence-based)

Known iterations Not required Usually used when count is known


Feature while Loop for Loop

Loop variable update Manually inside loop Automatically handled by Python

Example use case Wait for user input, run until event Repeat something a fixed number of times

🎯 Real-world Analogy:

 while loop: "Keep walking until it rains."


 for loop: "Walk 10 steps."

8. What is a list in Python? How do you create, access, and modify elements in a list? Write a program that
adds 5 elements to a list and displays them.

What is a List in Python?

A list in Python is a collection of items (like numbers, strings, etc.) stored in a single variable.
It is:

 Ordered (items stay in the same order)


 Mutable (you can change it)
 Allows duplicates
 Can store different data types

Creating a List
python
CopyEdit
my_list = [10, 20, 30, 40, 50]

You can also create an empty list:

python
CopyEdit
my_list = []

🔍 Accessing Elements in a List

Use indexing — starts from 0.

python
CopyEdit
print(my_list[0]) # First element
print(my_list[2]) # Third element

✏️Modifying Elements
python
CopyEdit
my_list[1] = 25 # Change second element (index 1) to 25

🧪 Program: Add 5 Elements to a List and Display Them


python
CopyEdit
# Creating an empty list
numbers = []

# Adding 5 elements
numbers.append(10)
numbers.append(20)
numbers.append(30)
numbers.append(40)
numbers.append(50)

# Displaying the list


print("The list of numbers is:", numbers)

✅ Output:

csharp
CopyEdit
The list of numbers is: [10, 20, 30, 40, 50]

✨ Summary:

Operation Code Example


Create a list my_list = [1, 2, 3]
Access an element my_list[0]
Modify an element my_list[1] = 5
Add element my_list.append(6)

9. Differentiate between logical operators (and, or, not) and bitwise operators (&, |, ^). Give suitable
examples of each.

1. Logical Operators (and, or, not)

These operators work with Boolean values (True / False).


Used in conditions and decision-making (e.g., if, while).

Operator Meaning Example Result

and True if both are True True and False False


Operator Meaning Example Result

or True if any one is True True or False True

not Reverses the value not True False

💡 Example:
python
CopyEdit
a = True
b = False

print(a and b) # False


print(a or b) # True
print(not a) # False

✅ 2. Bitwise Operators (&, |, ^)

These work bit by bit on integers (binary representation).

Operator Meaning Example Result

& Bitwise AND (1 if both bits are 1) 5 & 3 1 (0b0001)

` ` Bitwise OR (1 if any bit is 1) `5

^ Bitwise XOR (1 if bits differ) 5 ^ 3 6 (0b0110)

💡 Example:
python
CopyEdit
a = 5 # 0b0101
b = 3 # 0b0011

print(a & b) # 1
print(a | b) # 7
print(a ^ b) # 6

🎯 Key Differences:

Feature Logical Operators Bitwise Operators

Operates on Boolean values (True/False) Integers (bit-level operations)

Used for Decision making (if, while) Low-level operations, optimization

Common symbols and, or, not &, `


🧠 Easy Trick to Remember:

 Logical → Think True/False


 Bitwise → Think 0s and 1s

10. Explain the concept of list processing. Write a Python program that takes a list of numbers and prints
only the even numbers using a loop

What is List Processing in Python?

List processing refers to the act of accessing, manipulating, or performing operations on elements inside a
list.

Lists are a built-in data type in Python that can hold a collection of items (numbers, strings, etc.). Common
processing tasks include:

 Traversing through list items


 Filtering based on a condition
 Adding, removing, or modifying elements

🎯 Example Task:

Take a list of numbers and print only the even numbers.

✅ Python Program:
python
CopyEdit
# List of numbers
numbers = [10, 15, 20, 25, 30, 35, 40]

# Loop through the list and print even numbers


print("Even numbers in the list are:")
for num in numbers:
if num % 2 == 0:
print(num)

🧠 Explanation:

 for num in numbers: → Loops through each number in the list.


 if num % 2 == 0: → Checks if the number is divisible by 2 (even).
 print(num) → Prints the even number.
🔄 Output:
sql
CopyEdit
Even numbers in the list are:
10
20
30
40
Unit 5
1.What is the difference between a Python module and a Python package? Explain with examples. How are
they useful in large-scale programming?

1. Difference Between a Python Module and a Package

Feature Module Package


A package is a folder containing modules and a special
Definition A module is a single Python file (.py)
__init__.py file
Used to organize related code
Purpose Used to organize multiple modules in a structured way
(functions, classes)
Example math.py, hello.py numpy, pandas, my_project/ (with submodules)
How to import math import numpy.random or from my_project import
import module1

✅ Example of a Module:

Let's say you have a file called calculator.py:

python
CopyEdit
# calculator.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

You can use it in another file:

python
CopyEdit
import calculator

print(calculator.add(10, 5)) # Output: 15

✅ Example of a Package:

Folder Structure:

markdown
CopyEdit
my_package/
__init__.py
math_ops.py
string_ops.py

 math_ops.py contains math functions.


 string_ops.py contains string functions.
 __init__.py makes it a package.
Usage:

python
CopyEdit
from my_package import math_ops
print(math_ops.add(2, 3))

🎯 Why are Modules and Packages Useful in Large-Scale Programming?

1. ✅ Better Code Organization: Split big projects into smaller, manageable files.
2. ✅ Code Reusability: Functions/classes can be reused across projects.
3. ✅ Maintainability: Easier to debug or update specific parts.
4. ✅ Team Collaboration: Multiple team members can work on different modules.

🧠 Easy Way to Remember:

 Module → One Python file.


 Package → Folder of Python files with __init__.py.

2.Compare and contrast for loops and while loops in Python. In which scenarios would one be preferred over
the other?

Comparison: for Loop vs while Loop in Python

Feature for Loop while Loop


Iterates over a sequence (like list, range,
Purpose Repeats as long as a condition is True
string)
Best when the number of iterations is Best when the number of iterations is
Known Iterations
known unknown
Simple and concise for looping over
Structure Useful for looping based on a logical condition
collections
Risk of Infinite Higher (must manually update condition inside
Low (ends after sequence ends)
Loop loop)
Example for i in range(5): while i < 5:

✅ Example of a for loop:


python
CopyEdit
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)

✅ Example of a while loop:


python
CopyEdit
# Print numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1

✅ When to Use Which?

Scenario Use
Iterating over a list, tuple, or range for
Repeating an action until user quits (e.g., menu loop) while
Number of times is fixed for
Looping until a sensor reaches a threshold (unknown) while
Reading file until end while

🧠 Easy Trick to Remember:

 Use for when you know how many times you want to loop.
 Use while when you don’t know how many times and are waiting for a condition.

3.Explain the concept of functions in Python. What is the difference between built-in functions and user-
defined functions? Include examples.

What Is a Function in Python?


A function is a named block of reusable code that performs a specific task. You “call” a function by its name whenever
you need it, which keeps your programs organized and avoids repetition.

python
CopyEdit
def greet(name):
"""Say hello to someone."""
print(f"Hello, {name}!")

greet("Harry") # Output: Hello, Harry!

 def: Keyword to define a new function.


 greet: Function name.
 name: Parameter (input to the function).
 print: Performs the task (inside the function).

🔄 Built-in Functions vs User-defined Functions


Feature Built-in Functions User-defined Functions

Definition Provided by Python out of the box Written by you in your code
Feature Built-in Functions User-defined Functions

Availability Always ready to use (no definition needed) Must be defined before you call them

Examples print(), len(), sum(), max(), type() Any function you create with def

Use Case Common, general-purpose tasks Custom tasks specific to your program’s logic

🔧 Examples

1. Built-in: len()

Returns the length of a sequence (string, list, etc.).

python
CopyEdit
s = "Python"
print(len(s)) # Output: 6

2. Built-in: sum()

Adds up all items in a list or tuple of numbers.

python
CopyEdit
nums = [10, 20, 30]
print(sum(nums)) # Output: 60

3. User-defined: is_even()

Checks if a number is even.

python
CopyEdit
def is_even(n):
"""Return True if n is even, else False."""
return n % 2 == 0

print(is_even(4)) # True
print(is_even(5)) # False

4. User-defined: square_list()

Returns a new list of squares of input numbers.

python
CopyEdit
def square_list(numbers):
"""Return list of squares for each number."""
result = []
for x in numbers:
result.append(x*x)
return result

print(square_list([1, 2, 3])) # [1, 4, 9]

🎯 Why Use Functions?


 Modularity: Break big problems into small, manageable pieces.
 Reusability: Write once, call many times.
 Readability: Clear names (like calculate_tax()) explain intent.
 Maintainability: Fix or update in one place, and all calls benefit.

4.What are tuples in Python? How do they differ from lists in terms of mutability and usage?

What Are Tuples in Python?

A tuple is a collection of items just like a list, but unlike lists, tuples are immutable, meaning you cannot change, add, or
remove items after the tuple is created.

🧠 Syntax of a Tuple:
python
CopyEdit
my_tuple = (10, 20, 30)
print(my_tuple[0]) # Output: 10

Even single-item tuples need a comma:

python
CopyEdit
single = (5,) # This is a tuple
not_a_tuple = (5) # This is just an integer

🔄 Tuple vs List

Feature Tuple List

Mutability Immutable (can’t be changed) Mutable (can be modified)

Syntax Defined using () Defined using []

Speed Faster than lists Slightly slower

Usage Good for fixed data (e.g. coordinates, days of week) Good for dynamic data (to-do lists, items, etc.)

Methods Limited methods (like count, index) Many methods (append, pop, insert, etc.)
✅ Examples:

📌 List (Mutable)
python
CopyEdit
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']

📌 Tuple (Immutable)
python
CopyEdit
colors = ("red", "green", "blue")
# colors.append("yellow") ❌ This will give an error
print(colors[1]) # Output: green

🎯 When to Use Tuples:

 When data should not change


 For faster performance in large programs
 As dictionary keys (lists can’t be keys because they’re mutable)

📝 Conclusion:

 Use lists when you need to modify, add, or delete items.


 Use tuples when you want data to remain constant and secure.

👉 Tip to remember:
“Tuple = fixed, List = flexible” ✅

5.What is a dictionary in Python? Describe its properties and use cases. How is it different from a list or a
tuple?

What is a Dictionary in Python?

A dictionary in Python is an unordered, mutable collection of key-value pairs. It's used to store data values
like a real-life dictionary — you look up a key to find its value.

🧠 Syntax:
python
CopyEdit
my_dict = {
"name": "Harry",
"age": 21,
"course": "ML"
}

You access values using the key:

python
CopyEdit
print(my_dict["name"]) # Output: Harry

🧱 Properties of Dictionary:

Property Description
Key-value pairs Each element is stored as a pair
Keys are unique No two keys can be the same
Values can repeat Same value can appear multiple times
Mutable You can add, update, or delete items
Unordered (Python < 3.7) No fixed order before Python 3.7

🔄 Dictionary vs List vs Tuple:

Feature Dictionary List Tuple


Structure Key-value pairs Indexed by position Indexed by position
Mutable Yes Yes No
Syntax {} [] ()
Access Via keys (dict["key"]) Via index (list[0]) Via index (tuple[0])
Ordering Maintains insertion order (3.7+) Ordered Ordered

🔧 Common Dictionary Operations:


python
CopyEdit
# Add or update
my_dict["age"] = 22

# Delete a key
del my_dict["course"]

# Loop through keys and values


for key, value in my_dict.items():
print(key, ":", value)

🎯 Use Cases:

 Storing object-like data (student record, employee info)


 Counting frequency (e.g. character count)
 JSON data (used in APIs)
 Fast lookups (e.g. searching by ID or key)
✅ Example:
python
CopyEdit
student = {
"roll_no": 101,
"name": "Deepak",
"marks": 89
}

# Access value
print(student["marks"]) # 89

# Add new entry


student["subject"] = "Python"

📝 Summary:

 ✅ Use dictionary when you need to map keys to values (e.g., name to number, product to price).
 ✅ Unlike lists/tuples, you don’t use numeric indexes, but meaningful keys.
 ✅ Ideal for structured data and fast key-based access.

Remember:
Dictionary = Word → Meaning
Python Dictionary = Key → Value

6.How does Python support data processing through modules like csv, pandas, or json? Mention key
functions or methods commonly used.

1. csv Module – For Reading/Writing CSV Files


The csv module helps in reading and writing .csv (comma-separated values) files, commonly used in
spreadsheets and databases.

✅ Common Functions:
python
CopyEdit
import csv

# Reading a CSV file


with open('data.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

# Writing to a CSV file


with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Harry", 22])

🔹 2. pandas Module – For Advanced Data Analysis


pandas is one of the most powerful Python libraries for data analysis, manipulation, and cleaning. It works
with structured data using DataFrames.

✅ Common Functions:
python
CopyEdit
import pandas as pd

# Read CSV into DataFrame


df = pd.read_csv('data.csv')

# Show first few rows


print(df.head())

# Get column data


print(df['Name'])

# Add a new column


df['Marks'] = [85, 90, 95]

# Filter rows
print(df[df['Marks'] > 90])

🔥 Other Useful Methods:

 df.describe() – Statistical summary


 df.info() – Basic info (rows, columns, types)
 df.to_csv('output.csv') – Save to CSV
 df.drop() – Remove column or row

🔹 3. json Module – For Reading/Writing JSON Data


The json module is used to work with JSON (JavaScript Object Notation) files, commonly used in web data
and APIs.

✅ Common Functions:
python
CopyEdit
import json

# JSON string to Python dict


json_data = '{"name": "Harry", "age": 22}'
python_dict = json.loads(json_data)

# Python dict to JSON string


json_str = json.dumps(python_dict)
# Reading JSON file
with open('data.json') as file:
data = json.load(file)

# Writing JSON file


with open('output.json', 'w') as file:
json.dump(python_dict, file)

🧠 Summary Table:
Module Use Case Key Functions
csv Read/write CSV files reader(), writer(), writerow()
pandas Analyze large datasets read_csv(), head(), describe(), to_csv()
json Handle JSON data load(), dump(), loads(), dumps()

💡 Tip:

 Use csv for basic tabular files.


 Use pandas for complex data processing and analysis.
 Use json for structured data exchange (especially in APIs or web apps).

7.Discuss five commonly used string methods and five list methods in Python. Explain each with an example.

String Methods
Strings are sequences of characters. Python provides many built-in methods to manipulate them.

1. upper() – Converts all characters to uppercase


python
CopyEdit
text = "hello"
print(text.upper()) # Output: HELLO

2. lower() – Converts all characters to lowercase


python
CopyEdit
text = "HELLO"
print(text.lower()) # Output: hello

3. strip() – Removes whitespace from the beginning and end


python
CopyEdit
text = " hello "
print(text.strip()) # Output: "hello"
4. replace(old, new) – Replaces part of the string
python
CopyEdit
text = "hello world"
print(text.replace("world", "Python")) # Output: hello Python

5. split(separator) – Splits string into a list


python
CopyEdit
text = "apple,banana,cherry"
print(text.split(",")) # Output: ['apple', 'banana', 'cherry']

📋 List Methods
Lists are ordered collections that can be changed (mutable). They support many useful methods.

1. append(item) – Adds an item to the end of the list


python
CopyEdit
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']

2. insert(index, item) – Inserts an item at a specific position


python
CopyEdit
fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']

3. remove(item) – Removes the first occurrence of the item


python
CopyEdit
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'cherry']

4. pop(index) – Removes and returns the item at the given index


python
CopyEdit
last_item = fruits.pop() # By default, removes last item
print(last_item) # Output: cherry
print(fruits) # Output: ['apple', 'orange']

5. sort() – Sorts the list in ascending order


python
CopyEdit
numbers = [4, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 9]
🧠 Summary Table:
String Method Description Example Output
upper() All uppercase "HELLO"
lower() All lowercase "hello"
strip() Remove spaces "hello"
replace() Replace text "hello Python"
split() Convert string to list ['apple', 'banana']

List Method Description Example Output

append() Add to end ['a', 'b', 'c']

insert() Add at position ['a', 'x', 'b']

remove() Remove by value ['a', 'c']

pop() Remove and return item 'c'

sort() Sort list [1, 2, 3]

8.What is exception handling in Python? Why is it important? Describe the use of try, except, finally, and
raise statements.

Exception Handling in Python

Exception handling in Python is a mechanism that allows a program to respond to runtime errors (exceptions) in
a controlled way. It enables a program to continue execution even after encountering unexpected situations or
errors, instead of crashing or terminating abruptly.

Why is it Important?

 Graceful error handling: It allows programs to handle errors without terminating them unexpectedly.
 Debugging and logging: It helps capture errors for debugging purposes and provides a clear
understanding of what went wrong.
 User experience: By handling exceptions, the program can provide meaningful feedback to the user
instead of crashing.

Python provides several key keywords for exception handling:

1. try Block

The try block lets you test a block of code for errors. If an error occurs inside the try block, Python will stop
executing that block and move to the except block.

python
CopyEdit
try:
# Code that might raise an exception
x = 5 / 0 # Division by zero will raise an exception

2. except Block

The except block allows you to handle the exception. It can catch a specific type of exception or any exception.
You can specify the type of exception you expect, like ZeroDivisionError or ValueError, or use a general
Exception.

python
CopyEdit
try:
x = 5 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")

3. finally Block

The finally block will always execute, regardless of whether an exception occurred or not. This is typically
used for clean-up actions, such as closing files or releasing resources.

python
CopyEdit
try:
x = 5 / 1
except ZeroDivisionError:
print("Division by zero error")
finally:
print("This will always be executed.")

4. raise Statement

The raise statement is used to manually trigger an exception. You can raise exceptions for custom error
handling or when certain conditions are met in your code.

python
CopyEdit
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older")
else:
print("Age is valid")

try:
check_age(16)
except ValueError as e:
print(f"Error: {e}")

Summary

 try: Contains the code that might throw an exception.


 except: Catches and handles the exception.
 finally: Executes code that should run regardless of whether an exception occurred.
 raise: Manually triggers an exception.
Exception handling improves the robustness and stability of the program, making it easier to manage errors
gracefully and improve the overall user experience.

4o mini

9.Explain the concepts of local and global variables in Python. How does the scope of a variable affect its
accessibility?

Local and Global Variables in Python

In Python, the concept of variables is tied to their scope, which determines where in the program a variable can be
accessed. A variable’s scope depends on where it is defined — whether inside a function or outside. Based on this,
variables are categorized into two types:

1. Local Variables
2. Global Variables

1. Local Variables

A local variable is a variable that is defined within a function and can only be accessed or modified inside that function.
It is created when the function is called and destroyed when the function execution is completed.

Example:

python
CopyEdit
def example_function():
x = 10 # x is a local variable
print(x) # This will work because x is accessible inside the function

example_function()
# print(x) # This will give an error because x is not accessible outside the function

 Scope of a local variable: It is limited to the function where it is defined.


 Lifetime: Exists only as long as the function is executing.

2. Global Variables

A global variable is a variable that is defined outside of any function, usually at the top of the script. It can be accessed
and modified by any function in the program, provided that the variable is not redefined as local within the function.

Example:

python
CopyEdit
x = 20 # x is a global variable

def example_function():
print(x) # Accessing global variable inside a function

example_function() # This will print 20


print(x) # This will print 20, because x is accessible globally
 Scope of a global variable: It is accessible throughout the entire program (across all functions).
 Lifetime: Exists as long as the program is running.

Variable Scope and Accessibility

The scope of a variable determines where the variable can be accessed or modified. It is the region in the code where
the variable is recognized and valid.

Global Scope:

 A global variable is accessible from any part of the program, including inside functions. However, if you try to
modify a global variable inside a function, you must use the global keyword.

Example of modifying a global variable inside a function:

python
CopyEdit
x = 10 # Global variable

def modify_global():
global x # Declare x as global to modify it
x = 20

modify_global()
print(x) # This will print 20, because the global variable was modified

Local Scope:

 Local variables are only accessible within the function where they are defined. They are not accessible outside
the function.

Example of local variable scope:

python
CopyEdit
def my_function():
y = 5 # Local variable
print(y) # Works inside the function

# print(y) # This will give an error because y is not accessible outside the function

LEGB Rule (Lookup Order)

Python uses the LEGB rule to look for variables in the following order of scope:

 Local scope: The innermost scope where the variable is looked for (within a function).
 Enclosing scope: The scope of any enclosing functions (closures).
 Global scope: The module-level scope where variables are defined.
 Built-in scope: The scope of Python’s built-in names (like print(), len(), etc.).

Example: LEGB Lookup


python
CopyEdit
x = 100 # Global variable
def outer():
x = 200 # Enclosing scope variable

def inner():
x = 300 # Local variable
print(x) # This will print 300, the local variable

inner()

outer()

Summary:

 Local variables are defined inside a function and are accessible only within that function. They are created when
the function is called and destroyed when it finishes.
 Global variables are defined outside any function and are accessible throughout the program, including inside
functions (unless shadowed by a local variable).
 The scope of a variable determines where it can be accessed. A variable's scope is governed by the LEGB rule,
which follows a specific order for variable lookup.

10.What is modular programming? How does using functions and modules help in writing clean and
maintainable Python code

Modular Programming in Python

Modular programming is a software design technique that emphasizes breaking down a program into smaller,
manageable, and reusable parts called modules or functions. Each module or function is responsible for a specific task,
and these components can be developed, tested, and maintained independently. The core idea is to organize code into
logically separated units, which enhances readability, maintainability, and reusability.

In Python, modular programming can be achieved using functions, classes, and modules.

Benefits of Modular Programming

1. Readability: By dividing the code into smaller, focused functions or modules, it’s easier to understand and read.
2. Reusability: Once a module or function is written, it can be reused in other parts of the program or even in
different programs. This avoids code duplication.
3. Maintainability: It’s easier to maintain code when it’s divided into smaller modules. If a change is needed, it can
be made in one place without affecting the entire program.
4. Collaboration: Multiple programmers can work on different modules simultaneously, improving efficiency in
team-based projects.
5. Debugging: Smaller units of code (functions or modules) make it easier to isolate and fix bugs.
6. Testing: Modular programs are easier to test because each module can be tested independently.

Using Functions to Promote Modularity

A function is a block of code that performs a specific task. Functions can be called multiple times from different parts of
the program. This makes code more organized and reusable.
Example of a function:
python
CopyEdit
def greet_user(name):
"""Function to greet a user by their name."""
print(f"Hello, {name}!")

# Calling the function


greet_user("Alice")
greet_user("Bob")

In this example:

 The function greet_user is defined to greet a user.


 The function is called multiple times, and each time it can handle different input values.

How Functions Help:

 Avoid code repetition: Instead of writing the same code multiple times, you write it once inside a function and
call it whenever needed.
 Simplify complex tasks: Functions break down complex operations into smaller, more manageable tasks.
 Encapsulation: Functions encapsulate a specific piece of logic, making the program easier to understand and
modify.

Using Modules to Promote Modularity

A module in Python is a file containing Python definitions and statements. Modules allow you to organize functions,
variables, and classes into separate files that can be imported and reused in other parts of the program.

Example of a module:

Let's say we have a module math_utils.py with functions for basic arithmetic:

python
CopyEdit
# math_utils.py

def add(a, b):


return a + b

def subtract(a, b):


return a - b

Now, in your main Python script, you can import this module and use its functions:

python
CopyEdit
# main.py
import math_utils

result = math_utils.add(5, 3)
print(f"The sum is: {result}")

result = math_utils.subtract(10, 4)
print(f"The difference is: {result}")
In this example:

 The math_utils.py file is a separate module containing functions.


 The main script main.py imports the math_utils module and calls its functions.

How Modules Help:

 Code Reusability: Once a module is written, it can be reused across different projects or parts of the program.
 Better Organization: Large projects can have many modules, each handling a specific functionality (like file
handling, network communication, user interface, etc.), making the codebase easier to navigate and manage.
 Namespace Management: Modules help avoid naming conflicts by grouping related functions, classes, and
variables together under one module name.

Example of Combining Functions and Modules

Here’s an example of a more complex project that uses functions and modules:

python
CopyEdit
# file_operations.py

def read_file(filename):
"""Function to read contents of a file."""
with open(filename, 'r') as file:
return file.read()

def write_file(filename, content):


"""Function to write content to a file."""
with open(filename, 'w') as file:
file.write(content)
python
CopyEdit
# main.py
import file_operations

# Using functions from the file_operations module


content = file_operations.read_file('data.txt')
print(content)

file_operations.write_file('output.txt', 'Hello, World!')

In this example:

 The file_operations.py module contains functions for reading and writing files.
 The main.py script imports the module and uses its functions, keeping the file operations separate from the
main logic.

Summary:

 Modular Programming breaks down a program into smaller, independent pieces (modules or functions) to
improve readability, reusability, and maintainability.
 Functions allow you to group related code together, making it easier to manage and debug.
 Modules help organize the code into logical sections, enabling easier reuse and reducing complexity.
 By combining functions and modules, you can write clean, maintainable, and scalable Python code.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy