Machine Learning using Python
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?
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.
✅ 6. Portable
Write code on Windows, run it on Mac or Linux.
Python works on all major operating systems.
💡 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)
java
CopyEdit
int x = 10; // Type must be declared
x = "Hello"; // ❌ Error! You can't change the type
🎓 In Summary:
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
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():
python
CopyEdit
name = input("Enter your name: ")
✅ print():
python
CopyEdit
print("Welcome to Python!")
💡 Sample Output:
yaml
CopyEdit
Enter first number: 10
Enter second number: 20
The sum is: 30
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.
📥 3. Assignment Operators
Used to assign values to variables.
💡 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?
In Python, Boolean values are the two constant values that represent truth values:
True
False
python
CopyEdit
x = True
y = False
For example:
python
CopyEdit
5 > 3 # True
10 == 5 # False
a != b # Depends on the values of a and b
Conditional statements like if, elif, and else check Boolean conditions to decide which block of code to run.
✅ Example 1:
python
CopyEdit
age = 18
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
Output:
makefile
CopyEdit
Grade: B
🔁 Python evaluates each Boolean expression top to bottom, and executes the first one that is True.
📌 Summary:
Term Description
7. What is the difference between a while loop and a for loop in Python? Illustrate with appropriate
examples.
1. while Loop
✅ Example:
python
CopyEdit
count = 1
while count <= 5:
print("Count is:", count)
count += 1
🔂 2. for Loop
✅ Example:
python
CopyEdit
for i in range(1, 6):
print("Count is:", i)
🔍 Key Differences:
Example use case Wait for user input, run until event Repeat something a fixed number of times
🎯 Real-world Analogy:
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.
A list in Python is a collection of items (like numbers, strings, etc.) stored in a single variable.
It is:
Creating a List
python
CopyEdit
my_list = [10, 20, 30, 40, 50]
python
CopyEdit
my_list = []
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
# Adding 5 elements
numbers.append(10)
numbers.append(20)
numbers.append(30)
numbers.append(40)
numbers.append(50)
✅ Output:
csharp
CopyEdit
The list of numbers is: [10, 20, 30, 40, 50]
✨ Summary:
9. Differentiate between logical operators (and, or, not) and bitwise operators (&, |, ^). Give suitable
examples of each.
💡 Example:
python
CopyEdit
a = True
b = False
💡 Example:
python
CopyEdit
a = 5 # 0b0101
b = 3 # 0b0011
print(a & b) # 1
print(a | b) # 7
print(a ^ b) # 6
🎯 Key Differences:
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
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:
🎯 Example Task:
✅ Python Program:
python
CopyEdit
# List of numbers
numbers = [10, 15, 20, 25, 30, 35, 40]
🧠 Explanation:
✅ Example of a Module:
python
CopyEdit
# calculator.py
def add(a, b):
return a + b
python
CopyEdit
import calculator
✅ Example of a Package:
Folder Structure:
markdown
CopyEdit
my_package/
__init__.py
math_ops.py
string_ops.py
python
CopyEdit
from my_package import math_ops
print(math_ops.add(2, 3))
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.
2.Compare and contrast for loops and while loops in Python. In which scenarios would one be preferred over
the other?
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
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.
python
CopyEdit
def greet(name):
"""Say hello to someone."""
print(f"Hello, {name}!")
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()
python
CopyEdit
s = "Python"
print(len(s)) # Output: 6
2. Built-in: sum()
python
CopyEdit
nums = [10, 20, 30]
print(sum(nums)) # Output: 60
3. User-defined: 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()
python
CopyEdit
def square_list(numbers):
"""Return list of squares for each number."""
result = []
for x in numbers:
result.append(x*x)
return result
4.What are tuples in Python? How do they differ from lists in terms of mutability and usage?
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
python
CopyEdit
single = (5,) # This is a tuple
not_a_tuple = (5) # This is just an integer
🔄 Tuple vs List
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
📝 Conclusion:
👉 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?
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"
}
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
# Delete a key
del my_dict["course"]
🎯 Use Cases:
# Access value
print(student["marks"]) # 89
📝 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.
✅ Common Functions:
python
CopyEdit
import csv
✅ Common Functions:
python
CopyEdit
import pandas as pd
# Filter rows
print(df[df['Marks'] > 90])
✅ Common Functions:
python
CopyEdit
import json
🧠 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:
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.
📋 List Methods
Lists are ordered collections that can be changed (mutable). They support many useful methods.
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 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.
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
4o mini
9.Explain the concepts of local and global variables in Python. How does the scope of a variable affect its
accessibility?
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
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
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.
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.
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
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.).
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 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.
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.
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}!")
In this example:
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.
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
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:
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.
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()
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.