CSE101 Lecture Notes for Mid Term Exams
CSE101 Lecture Notes for Mid Term Exams
Learning Objectives:
Grasp the fundamental idea behind programming and how it relates to problem-solving in
everyday life.
Understand the role of algorithms in programming and how they serve as a blueprint for solving
problems.
Set up your Python development environment, including installing an Integrated Development
Environment (IDE) and the Python interpreter.
Learn the basics of Python’s syntax and write your first “Hello, World!” program.
Explore essential programming elements like variables, data types, and functions.
Begin your journey toward understanding Python as an object-oriented language and what that
means for how you approach programming.
Gain a brief understanding of machine code: how computers store data in the form of 0s and 1s
and execute instructions using 0s and 1s.
What Is Programming?
Programming is simply the process of giving instructions to a computer to perform specific tasks. You
do this by writing lines of code in a programming language, like Python. Just like a recipe helps you
bake a cake, a program helps the computer follow precise steps to achieve a goal.
Real-World Example:
To understand the importance of programming, imagine you have a long list of tasks to complete.
Instead of manually writing everything down and checking items off one by one, what if you could
create a program to automate the process?
In essence, programming can automate tasks that would otherwise be time-consuming, repetitive, or
prone to human error. Apps like Google Calendar, calculators, and even social media platforms like
Instagram are built on similar principles of task automation using programming.
Mini Code Snippets:
Below are some simple Python programs to help you understand how Python works:
Here, the print() function is used to display the message "Hello, World!" . The quotation marks
indicate that "Hello, World!" is a string, a type of data representing text.
In this code, name = "Alice" assigns the string "Alice" to the variable name . The + operator
concatenates (joins) strings together, so the output would be "Hello, Alice!" .
input() allows the user to enter data, but it is stored as a string. int() is used to convert the string
into an integer for further calculations.
1. Thought Exercise: Imagine you are giving instructions to a robot to make a cup of coffee. What
steps would you include in your instructions? How might that translate to an algorithm in
programming?
2. Exercise: Write a Python program that asks for the user’s name and greets them with:
"Hello, [NAME]!" .
Hint: Use the input() function to take the user’s name as input, and then use print() to display
the greeting.
3. Challenge: Think of an everyday task you do manually. How would you break it down into smaller,
more manageable steps (i.e., an algorithm) that a computer could perform?
if True:
print("This line is indented correctly!")
Mixing Data Types: Another common issue is trying to mix incompatible data types without
converting them. For instance, adding an integer to a string will cause an error.
Example of an error:
age = 25
print("You are " + age + " years old!") # This will cause an error!
Using Functions Incorrectly: Forgetting the parentheses when using functions like print() can
lead to errors. Always remember that print needs parentheses, like this: print("Hello") .
1. Introduction to Programming
What is Programming?
In the simplest terms, programming is giving instructions to a computer to perform specific tasks. Think
of it like giving directions to a friend on how to reach your house. But instead of using words like "turn
left," we use a programming language that the computer understands. In this lecture, we’ll explore the
basics of programming and set you up to write your first lines of code.
Algorithm : A step-by-step process to solve a problem. Example: A recipe for baking a cake.
Source Code : The text or instructions written in a programming language.
Compiler/Interpreter: Tools that convert your code into a form that the computer can understand.
Text Editor or IDE: Install an Integrated Development Environment (IDE) like PyCharm or
VSCode. These tools make coding easier by highlighting syntax errors and offering auto-
completions.
Python Interpreter: Make sure Python is installed on your computer. You can download it from
Python's official website.
Your First Program
Let’s start with the classic “Hello, World!” program. It’s a simple
way to see how programming works.
print("Hello, World!")
Explanation:
screen.
Real-Life Example:
Imagine programming like a conversation. Here, you’re telling your computer to say “Hello, World!” like
how you might greet someone.
Indentation: In Python, indentation (spaces before lines of code) is crucial. For example:
if True:
print("This is indented!")
Comments: Use the # symbol to add comments in your code. Comments help you explain what the
code does but don’t affect how it runs.
Problem Statement:
Write a Python program to print your name.
Example:
name = "Alice"
age = 21
Here, name is a variable storing the string "Alice" , and age is a variable storing the number 21 .
Real-Life Example:
If you think of a contact form on a website, the name you enter is string
a , your age is an integer, and
whether you agree to the terms might be a boolean.
Variable: A value that can change. Example: Your age changes every year.
Constant : A value that doesn’t change. Example: The number of days in a week is always 7.
The f in the print(f"...") statement is used for f-string formatting, introduced in Python 3.6. An f-
string allows you to embed expressions inside string literals, using curly braces {}. It stands for
formatted string literal.erywhere! It’s even used by NASA.
Solution
# Defining product 1 details
product1_name = "Apples"
product1_price = 1.50
product1_quantity = 3
product1_total = product1_price * product1_quantity # Calculating total cost for product 1
Output
Product 1: Apples, Quantity: 3, Price per unit: $1.5
Product 1 Total: $4.50
Example:
age = "21"
age = int(age) # Converts the string "21" into an integer 21
Introduction to Objects
Python is an object-oriented language. This means that everything in Python is an object, and
objects have attributes (data) and methods (functions that act on the data). For example, a string is
an object in Python with built-in methods like .upper() to convert it to uppercase.
Example:
name = "alice"
print(name.upper()) # Outputs 'ALICE'
Step-by-Step Solution:
Solution:
Hint: Use input() to take input and int() to convert strings to integers.
Pre-Class Reading: Mathematical Operator and Comparison
Operator
Learning Objectives:
1. Arithmetic Operators: Perform basic math operations like addition, subtraction, multiplication,
etc.
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus), // (Floor
Division), ** (Exponentiation).
2. Relational Operators: Compare two values and return True or False .
== (Equal to), != (Not equal to), > (Greater than), < (Less than), >= (Greater than or
equal to), <= (Less than or equal to).
3. Logical Operators: Combine multiple conditions and return True or False .
and , or , not .
4. Assignment Operators: Assign or update values in variables.
= , += , -= , *= , /= , %= , etc.
Real-World Example:
Imagine you're shopping and comparing prices between two items. Let’s say Item A costs
200andItemBcosts150. You can use relational operators in Python to check which one is more
expensive.
Example:
price_A = 200
price_B = 150
item_1 = 50
item_2 = 30
total = item_1 + item_2
num1 = 10
num2 = 5
a = 10
b = 20
score1 = 60
score2 = 45
1. Write down a short Python code that adds two numbers and prints the result.
2. Try to use the modulus operator ( % ) to find the remainder when you divide 10 by 3. What result
do you get?
3. Write a Python statement using relational operators to check if 7 is less than 10.
1. Division Confusion: In Python, / always returns a float even if the result is a whole number. If
you want an integer result, use // (floor division).
Example: 10 / 3 returns 3.333 , while 10 // 3 returns 3 .
2. Logical Operators: Beginners often confuse and and or . Remember, and requires both
conditions to be true, while or requires just one condition to be true.
In the upcoming class, we will explore how to make decisions in your code using Conditional
Statements. We will also dive into the powerful concepts of While Loops and For Loops, which allow
you to repeat tasks and iterate through data efficiently. Get ready to understand how Python enables
you to write smarter, more dynamic programs by controlling the flow of your code!
Notes for CSE101 - Programming Fundamentals (Lecture 2)
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction,
multiplication, and more.
Real-Life Example:
Think of arithmetic operators like basic math you perform in everyday life. If you have 5 apples and
you give 2 away, you can use the subtraction operator to find out how many you have left: 5 - 2 = 3 .
2. Relational (Comparison) Operators
Relational operators compare two values or variables and return a Boolean ( True or False ). They are
often used in conditional statements like if statements.
Real-Life Example:
Imagine you're shopping and comparing the prices of two items. If the price of item A is 200 and item
B is 150 , you could use a relational operator to check which one is more expensive: 200 > 150
returns True .
3. Logical Operators
Logical operators are used to combine multiple conditions and return either True or False based on the
evaluation of those conditions. They are most often used with if statements to control the flow of a
program.
Is it sunny outside?
Do you have free time?
If both conditions are true ( sunny and free_time ), you go for a walk (just like an and operator).
4. Assignment Operators
Assignment operators are used to assign values to variables. The most basic one is = (equal), but
Python has several other assignment operators that combine mathematical operations with
assignment.
Real-Life Example:
Imagine your bank account has a balance of 500 dollars. If you deposit 100 dollars, the assignment
operator can update the balance:
balance = 500
balance += 100 # Now, balance becomes 600
Problem Statements and Solutions
Problem 1:
Write a program given two numbers and performs the following operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
Solution:
num1 = 5;
num2 = 13;
# Performing operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
# Displaying results
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")
print(f"Modulus: {modulus}")
Problem 2:
Write a Python program to compare two ages and print whether the first person is older, younger, or
the same age as the second person.
Solution:
# Taking input
age1 = int(input("Enter the age of the first person: "))
age2 = int(input("Enter the age of the second person: "))
Fun Fact:
Did you know? Python was initially created as a hobby project by Guido van Rossum in the late
1980s. It has since grown to become one of the most popular programming languages in the
world!
Extra Challenge:
Write a Python program that asks the user to enter three test scores. Use logical operators to check if
all three scores are above 50. If true, print "Pass", otherwise print "Fail".
Pre-Class Reading: Mastering Conditional Statements, While Loops, and For Loops in Python
Learning Objectives
In this session, you will:
if condition:
# code that runs if the condition is true
2. Else Statement:
Paired with an if statement, else allows you to specify what should happen if the condition is false.
The else block will only execute if the if condition is false.
Example:
if condition:
# code if true
else:
# code if false
3. Elif Statement:
Short for "else if," this allows you to check multiple conditions. If the initial if condition is false,
Python moves to check the elif conditions in sequence until one is true or defaults to the else block
if none are true.
Example:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if neither condition is true
4. Nested Conditions:
This refers to placing an if statement inside another if or else block. It's useful for making
decisions that depend on a sequence of conditions.
Example:
if condition1:
if condition2:
# code if both conditions are true
else:
# code if condition1 is false
5. While Loop:
A loop that keeps running as long as a specified condition remains true. This is useful when you don’t
know in advance how many times the code should be repeated.
Example:
while condition:
# code that runs while the condition is true
6. For Loop:
A loop that iterates over a sequence (like a list or range of numbers) and executes a block of code a
specific number of times or for each element in the sequence.
Example:
7. Ternary Operator:
A shorthand way of writing an if-else statement. It’s used when you want to assign a value based on
a condition and keep it concise.
Example:
8. Indentation:
Unlike many other programming languages, Python relies on indentation to define blocks of code. This
means it's crucial to maintain consistent indentation when writing conditional statements and loops.
Code Analogy:
button_pressed = True
if button_pressed:
print("Change the light to allow crossing.")
else:
print("Continue with regular light cycle.")
Example 2: Repeating Tasks with a While Loop
Imagine you are building a password prompt that continues asking the user for a password until the
correct one is entered.
Code Analogy:
correct_password = "python123"
password = ""
print("Access granted!")
Code Analogy:
age = 20
temperature = 22
attempts = 0
while attempts < 3:
password = input("Enter password: ")
if password == "secret":
print("Access granted")
break
attempts += 1
for i in range(5):
print(f"This is loop iteration {i}")
In the next class, we’ll explore how nested loops can be used with data structures like lists to process
complex data more efficiently.
Lecture Notes: Conditional Statements and Loops
Introduction
In this lecture, we will explore conditional statements and loops, two essential concepts in Python
programming. These tools will help us write more efficient, dynamic, and interactive programs.
1. Conditional Statements
Conditional statements allow your code to make decisions based on certain conditions. Imagine a
situation where you need to decide whether to carry an umbrella. You’ll carry one if it’s raining, but not
otherwise. This decision-making process is similar to what happens in conditional statements.
Syntax:
if condition:
# Instructions when condition is true
else:
# Instructions when condition is false
Example:
temperature = 25
if temperature > 30:
print("It's a hot day.")
else:
print("It's a nice day.")
Real-Life Example:
Syntax:
if condition1:
# If condition1 is true
elif condition2:
# If condition2 is true
else:
# If neither condition is true
Example:
temperature = 25
if temperature > 30:
print("It's a hot day.")
elif temperature > 20:
print("It's a warm day.")
else:
print("It's a cold day.")
Problem 1:
Write a Python program to check if a number is positive, negative, or zero using if-else .
Solution:
age = 18
if age > 0:
if age >= 18:
print("You're an adult.")
else:
print("You're a minor.")
else:
print("Invalid age.")
Trick Question:
If the number is 0 , what will the following code print?
if number > 0:
print("Positive")
else:
if number < 0:
print("Negative")
else:
print("Zero")
2. Loops
Loops allow you to execute a block of code multiple times. Think of loops like brushing your teeth
every day. You don’t write a new instruction every day; instead, you repeat the same action.
Syntax:
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Real-Life Example:
Imagine you want to greet all your friends one by one. You could use a for loop to print a
message for each friend.
Syntax:
Example:
Problem 2:
What will the following code output?
Solution:
The code prints the numbers: 1, 3, 5, 7, 9.
Syntax:
while condition:
# Instructions
Example:
count = 1
while count <= 5:
print(count)
count += 1
Real-Life Example:
Trick Question:
What will happen if you forget to update the count variable in the previous example?
Example:
for i in range(5):
if i == 3:
break
print(i)
3.2 Continue
The continue statement skips the rest of the code in the current iteration and moves to the next one.
Example:
for i in range(5):
if i == 3:
continue
print(i)
Output: 0, 1, 2, 4 (The loop skips 3 .)
Summary
Conditional Statements help you make decisions in your code:
if-else : Basic two-way decisions.
elif : For multiple conditions.
Nested if : To handle more complex scenarios.
Loops allow for repetition:
for loops for sequences like lists.
while loops for repeating actions as long as a condition is true.
Loop control ( break , continue ) helps manage loop execution.
2. Write a Python program to print all even numbers between 1 and 20 using a for loop.
3. Real-World Examples
Imagine you are organizing a school with multiple classes, and you need to print the names of
students in each class. To do this, you would go through each class (outer loop) and then list the
students in that class (inner loop). This is exactly how a nested loop operates.
Similarly, think of a spreadsheet where each row has several columns. If you want to process each
cell, you'd first go through the rows (outer loop) and then the columns within each row (inner loop).
Explanation:
The outer loop ( for i in range(1, 4) ) goes through the numbers 1, 2, and 3.
The inner loop ( for j in range(1, 4) ) does the same, but for each i , it runs completely before
moving to the next i .
The result is the multiplication table for 1 to 3.
Explanation:
We have a list of lists ( classes ), where each inner list contains names of students in a class.
The outer loop goes through each class, and the inner loop prints the students' names in that
class.
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
* * *
* * *
* * *
3. Create a list of three of your favorite foods, and use a nested loop to print each character in each
food's name.
This reading prepares you to dive into nested loops and lists. Don’t worry if it feels tricky at first—
working with loops becomes much easier with practice!
Lecture Notes: Nested Loops and Lists in Python
Introduction
In this lecture, we covered two powerful tools in Python: nested loops and lists. Both are
fundamental concepts that help us handle repetitive tasks and store collections of data, respectively.
1. Nested Loops
*
* *
* * *
* * * *
Here, the outer loop controls the rows, and the inner loop controls how many stars are printed on each
row.
Real-Life Analogy:
Think of nested loops like having two clocks. The outer clock (hours) ticks once, and for every tick of
the outer clock, the inner clock (minutes) completes a full rotation. It’s like how nested loops work —
the inner loop completes fully for every iteration of the outer loop.
for i in range(2):
for j in range(2):
print(i, j)
Think: How many times will the inner loop run for each iteration of the outer loop?
2. Lists in Python
What is a List?
A list is a collection of items that can be stored in a single variable. In Python, lists are dynamic, which
means you can add, remove, or change the items in the list. Lists are ordered, changeable, and allow
duplicate values.
my_list = [1, 2, 3, 4, 5]
print(my_list)
print(my_list[0]) # Output: 1
List Operations:
Appending: Adds an item to the end of the list.
my_list.append(6)
my_list.remove(2)
Real-Life Analogy:
Think of a list like a grocery shopping list. You write down items (which can be numbers, strings, etc.),
and you can add more items, remove items, or modify them as needed.
my_list = [1, 2, 3, 4]
my_list[1] = 10
print(my_list)
3. List Comprehensions
List Comprehension is a shorter way to create a new list by using a loop in a single line of code. It’s
very efficient and makes your code cleaner.
Example:
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
In this example, the outer loop iterates over each row, and the inner loop iterates over each element in
that row.
Example:
Strings are a crucial part of Python programming, and we’ll dive deeper into their methods and uses.
Pre-Class Reading: Strings in Python
Welcome to Today's Topic: Strings in Python!
Here, we'll be diving into one of the most fundamental concepts in programming—strings.
Understanding how to work with strings will allow you to handle text data effectively in Python, and
you'll find this skill useful in almost every programming task, whether you're building apps, scraping
data from websites, or even analyzing text in data science!
1. Learning Objectives
By the end of this session, you will be able to:
3. Real-World Examples
Imagine you're building a simple chatbot that greets users by their name. You'd need to work with
strings to format the message. For example, if the user inputs their name, your program could reply
with something like:
name = "Alice"
greeting = "Hello, " + name + "! How can I assist you today?"
print(greeting)
In this case, "Hello, " and "! How can I assist you today?" are strings that get concatenated with
the user's name to form a personalized message.
String concatenation:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
Indexing a string:
word = "Python"
first_letter = word[0]
print(first_letter) # Output: P
Slicing a string:
word = "Python"
first_three_letters = word[0:3]
print(first_three_letters) # Output: Pyt
1. What do you think will happen if you try to concatenate a number (like 5 ) with a string in Python?
2. Try slicing different sections of a string, like the first half or the last three characters.
3. Play with the .upper() and .lower() string methods. How do they affect different strings?
age = 25
print("I am " + age + " years old.") # This will cause an error!
Off-By-One Errors in Indexing: Remember that Python uses zero-based indexing, meaning
the first character of a string is at index 0. Beginners often assume the first letter is at index 1.
Immutable Strings: Strings in Python are immutable, meaning once they are created, they
cannot be changed. You can create a new string based on an old one but cannot modify the
original string directly.
In the lecture, we’ll dive into more advanced string manipulations and learn how to handle tasks like
this using Python string methods! You'll also get hands-on practice writing code that can solve such
problems.
This pre-class reading gives you a foundation for our upcoming session. Feel free to try the small
exercises and get comfortable with the basic concepts, and we’ll explore much more during the class!
Lecture Notes: Strings in Python
Introduction
In today’s lecture, we discussed strings, one of the most commonly used data types in Python. Just
like the words we use every day, strings in Python allow us to handle text. Whether it’s crafting
messages for a mobile app, organizing names in a school system, or sending emails, strings play a
crucial role in programming.
These notes will help you recap the important points, and there are some tricky questions included to
test your understanding. Let’s dive in!
Example:
Real-life analogy: Think of a string as a banner at a wedding or a shop sign that displays a message
like “Congratulations, newlyweds!” or “Welcome to ABC Electronics.” Just like these signs store
messages, Python strings store text.
Concatenation: Joining two strings together using the + operator. Think of it like joining two
sentences in a WhatsApp message.
first = "Hello"
second = "India"
result = first + " " + second
print(result) # Output: Hello India
Accessing Characters: You can access individual characters in a string using their index. In
Python, indexing starts from 0 (zero-based indexing). So, the first character of a string is at
position 0.
name = "Sharma"
print(name[0]) # Output: S
3. String Slicing
You can extract portions of a string using slicing. This is like cutting a specific part of a banner or
getting only part of the text. The syntax for slicing is string[start:end] , which extracts characters
from the start index up to but not including the end index.
Example:
Slicing with omitted start: string[:n] slices from the beginning to n-1 .
Slicing with omitted end: string[n:] slices from index n to the end.
Trick Question #1
What will be the output of this code?
Solution:
The output will be ome to . The slicing starts from index 4 and stops at index 9.
4. String Methods
Python offers several methods to work with strings. Let’s explore some useful ones:
.upper(): Converts all characters in the string to uppercase. This is like writing in capital letters on
a poster.
city = "delhi"
print(city.upper()) # Output: DELHI
.lower(): Converts all characters to lowercase. Think of this as casual, informal text.
.replace(): Replaces a part of the string with another string. For instance, changing “Ganga” to
“Yamuna.”
.split(): Splits a string into a list of words based on spaces (or any other separator). This is like
breaking a long sentence into individual words.
Trick Question #2
What will be the result of this code?
Solution:
The output will be ANDA SHANANG . The upper() method first converts the phrase to uppercase, and
then replace() replaces all instances of "I" with "A".
5. String Immutability
In Python, strings are immutable. This means that once a string is created, it cannot be changed.
Instead, any operation that modifies a string creates a new string.
Example:
word = "Mumbai"
word[0] = "D" # This will raise an error
You cannot change a character of a string directly, but you can create a new string.
Real-life analogy: Think of a string as a printed certificate. Once printed, you cannot change it. If
you want to make corrections, you need to print a new one!
Trick Question #3
What happens if you run this code?
message = "India"
message[0] = "A"
Solution:
This will cause an error because strings in Python are immutable. You cannot modify individual
characters.
6. String Formatting
Often, we want to include variables inside a string in a clear and readable way. Python provides
several ways to format strings:
Old-Style Formatting ( % ):
You can use % to insert values into a string. For example, inserting someone’s name and age.
name = "Raj"
age = 20
print("Name: %s, Age: %d" % (name, age)) # Output: Name: Raj, Age: 20
.format() Method:
A flexible way to insert values into placeholders ( {} ) in a string.
f-strings (modern):
The most convenient method in Python 3.6+ is using f-strings, where variables can be inserted
directly into a string with curly braces {} .
cricket_scores = [
[100, 50, 75],
[60, 80, 45]
]
print(cricket_scores[0][1]) # Output: 50
We will also learn about functions, which allow you to create reusable blocks of code to simplify
complex programs.
These notes should help you review today’s concepts and get a sneak peek into the next lecture.
Make sure to try the trick questions and check the solutions to sharpen your understanding!
Pre-Class Reading: Introduction to
Functions and Multidimensional Lists in
Python
Welcome to our pre-class reading! Today, we’ll explore two key concepts in Python: functions and
multidimensional lists. Understanding these topics will help you write cleaner, more organized code
and manage complex data structures with ease. Let’s dive in!
1. Learning Objectives
In today’s class, you will learn to:
Understand what functions are and how they help organize code.
Write basic functions in Python.
Understand and work with multidimensional lists (lists of lists).
In this example, say_hello() is our function. Every time we call it, it prints "Hello!".
board = [
["X", "O", "X"],
["O", "X", "O"],
["X", " ", "O"]
]
3D Lists:
Represents a collection of 2D lists.
Example: A 3D list representing a Rubik’s Cube:
cube = [
[[1, 2], [3, 4]], # Side 1
[[5, 6], [7, 8]], # Side 2
]
1.3 Accessing Elements in Multidimensional Lists
2D Lists: Access using two indices (e.g., list[row][column] ).
Example:
board[1][1] = 9
print(board) # Outputs [[1, 2, 3], [4, 9, 6]]
Section 2: Functions
2.1 What are Functions?
Definition: Functions are reusable blocks of code designed to perform a specific task.
Syntax:
def function_name(parameters):
# Code block
return value # Optional
def greet(name):
return f"Hello, {name}!"
square = lambda x: x ** 2
These notes, along with the provided examples and trick questions, will help solidify your
understanding of multidimensional lists and functions.
Pre-Class Reading: Understanding Classes and Inbuilt Functions in Python
Welcome to today’s reading! You’ll be learning about two important concepts in Python that make your
code more organized, powerful, and easier to reuse. With Classes and Inbuilt Functions, you’ll be
able to create structures that represent real-world items in code, making your programming experience
more intuitive.
1. Learning Objectives
By the end of the session, you will be able to:
Class: Think of a class as a template or blueprint for something you want to create, like a “recipe”
for a cake. For example, a Car class would outline what all cars should have (e.g., color, make,
model) and what they should be able to do (e.g., drive, park, honk).
Object: When you use a class to make something specific, like a red Toyota Camry, that’s an
object. An object is an actual instance created from the class. You can make multiple objects from
a single class, each with its own unique attributes.
Method: A function that’s defined inside a class. Methods are the actions or behaviors that objects
of the class can perform, like starting the engine of a car or checking the mileage.
Attribute: These are the properties or characteristics of an object. For a car, attributes could be
color , make , model , or year . Each object can have its own unique attribute values.
Inbuilt Functions: Python provides many ready-made functions that can help you work with
classes, objects, and other data more easily. For example, len() gives the length of an object,
type() shows the type of an object, and isinstance() checks if an object belongs to a specific
class.
For example:
This makes managing books easier since each book can be created and updated with just a few lines
of code, rather than managing each one separately.
Inbuilt functions like type() and isinstance() help us confirm that my_book is indeed a Book object
and has the attributes we expect.
5. Pre-Reading Questions or Simple Exercises
1. Identify a Real-World Example: Think of a real-life object that could be represented as a class in
Python. What attributes and methods would it need? For instance, a Car class could have
attributes like color , make , model , and speed , with methods like drive() and stop() .
2. Create a Basic Class: Try writing a simple class. You could create a class named Person with
attributes like name and age . Add a method that prints a greeting using the name.
3. Experiment with Inbuilt Functions: Create an instance of your class and use type() ,
isinstance() , and hasattr() to check its type, class, and attributes.
Confusing the Class with the Object: Remember, the class is just a blueprint. The actual items
you create from that blueprint are the objects.
Forgetting to Use self : In Python, self must be the first parameter in each method inside a
class. It refers to the specific object instance being used. If you forget to add self , you may get
an error saying Python doesn’t know which instance you mean.
Misusing Inbuilt Functions: For example, isinstance() checks if an object belongs to a
specific class. If used incorrectly, it may not return the result you expect. Always double-check
which object and class you are using.
Understanding classes and inbuilt functions opens up a new world of organized, efficient
programming. Once you grasp these concepts, you'll start to see how Python can create solutions for
complex real-world problems in just a few lines of code!
Lecture Notes on Classes and Inbuilt
Functions in Python
Real-life Analogy: Think of a blueprint of a house. The blueprint (class) defines what a house
should be like, but it’s not an actual house. When a house is built (object), it follows the blueprint but
has its own unique features, like a different paint color or flooring.
Trick Question:
Q: If OOP provides modularity, can we use functions alone instead of classes? Why or why not?
Solution: While functions are useful for isolated tasks, OOP is preferred for organizing data and
functionality, especially in larger projects, where modularity, encapsulation, and reusability are
beneficial.
2. What is a Class?
A Class is a blueprint for creating objects, defining the structure, attributes, and behaviors that
objects of that type will have.
Example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
Trick Question:
Q: What will be the output if we create two objects, car1 = Car("Toyota", "Corolla") and
car2 = Car("Honda", "Civic") ?
Solution: Each object will have its own unique make and model . car1 has "Toyota, Corolla,"
while car2 has "Honda, Civic."
Real-life Analogy: If Person is a class, then each person you know is an object of that class, with
unique characteristics like name and age .
Trick Question:
class Person:
def __init__(self, name):
name = name
john = Person("John")
print(john.name)
Solution: Yes, it will. Since self.name was not used, name was not set as an attribute for the
object john , causing an AttributeError.
4. Instance, Class, and Static Methods
Instance Methods: Operate on instances of the class and can modify instance attributes.
Class Attributes: Shared across all instances, defined within the class but outside __init__ .
Class Methods: Use @classmethod and cls parameter to modify class-level attributes.
Static Methods: Do not access or modify any class or instance data and are used like regular
functions but belong to the class.
Example:
class Car:
wheels = 4 # Class attribute
@classmethod
def change_wheels(cls, new_count):
cls.wheels = new_count # Modifies class attribute
@staticmethod
def car_type():
return "Vehicle"
Trick Question:
Mathematical Functions
abs(x) : Returns the absolute value.
round(x) : Rounds a number.
pow(x, y) : Raises x to the power of y .
Trick Question:
String Functions
len() : Returns length.
upper() : Converts to uppercase.
replace() : Replaces part of the string.
Trick Question:
List Functions
len() : Length of the list.
append() : Adds an element.
pop() : Removes the last element.
Trick Question:
Q: If we start with numbers = [1, 2, 3] and run numbers.pop() , what will numbers be?
Solution: [1, 2] since pop() removes the last element.
Utility Functions
type() : Checks the type.
isinstance() : Checks if an object is an instance of a class.
print() and input() for displaying and reading user input.
6. Takeaways
Classes allow structuring code and data efficiently.
Methods in classes (instance, class, static) provide various functionalities.
Built-in functions are versatile, helping with common tasks across data types.
Primitive Data Structures: These include basic types like integers, floats, strings, and booleans.
Abstract Data Structures: We’ll look at structures like stacks, queues, and linked lists, which
help organize and manage complex data efficiently.
This comprehensive note covers the core elements of today’s lecture with real-life analogies, example
codes, and trick questions for deeper understanding. Use this as a reference, and don’t hesitate to
experiment with the examples provided!
Pre-Class Reading: Primitive & Abstract
Data Structures in Python
1. Learning Objectives
In today’s session, you will learn:
By the end of the class, you’ll understand which data structures to use for different programming tasks
and why they’re crucial in creating efficient code.
# String (text)
name = "Alice" # Person's name
# Boolean (True/False)
is_student = True # Indicates if the person is a student
Abstract Data Structures
List
# Accessing an item
print(fruits[1]) # Outputs "banana"
# A queue of people
queue = deque(["Alice", "Bob", "Charlie"])
Looking forward to helping you build a solid foundation in Python data structures!
Lecture Notes: Primitive & Abstract Data Structures in
Python
1. Primitive Data Structures: Basic types like integers, floats, strings, and booleans.
2. Abstract Data Structures: Collections of elements, including lists, tuples, dictionaries, and sets.
a. Integer ( int )
Used to store whole numbers.
# Example of integer
age = 25
print(age) # Output: 25
b. Float ( float )
Used to store decimal (floating-point) numbers.
# Example of float
price = 19.99
print(price) # Output: 19.99
c. String ( str )
A sequence of characters enclosed in quotes (single or double).
# Example of string
greeting = "Hello, World!"
print(greeting) # Output: Hello, World!
d. Boolean ( bool )
Represents a truth value ( True or False ).
# Example of boolean
is_active = True
print(is_active) # Output: True
Trick Question 1
Question: What happens when you add an int to a bool ?
# Code
score = 100
is_winner = True
final_score = score + is_winner
print(final_score) # What will this print?
a. Lists
Definition: A mutable (changeable) collection of elements.
Syntax: Defined using square brackets [] .
Example Use: Storing an inventory of items in a store.
# Creating a list
inventory = ["apple", "banana", "cherry"]
# Removing an item
inventory.remove("banana")
print(inventory) # Output: ['apple', 'cherry', 'date']
Trick Question 2
Question: What will inventory[1] print after executing the code above?
# Code
print(inventory[1])
Answer: cherry , because after removing "banana" , "cherry" moves to the 1st index.
b. Tuples
Definition: An ordered, immutable collection of elements.
Syntax: Defined using parentheses () .
Example Use: Storing constant values like geographical coordinates.
# Creating a tuple
coordinates = (40.7128, 74.0060)
Answer: No, tuples are immutable, so attempting to change any element will result in an error.
c. Dictionaries
Definition: A collection of key-value pairs.
Syntax: Defined using curly braces {} .
Example Use: Storing user profile information where each piece of data is associated with a
unique key.
# Creating a dictionary
user_profile = {
"name": "Alice",
"age": 30,
"location": "New York"
}
Trick Question 4
Question: What happens if you try to access a key that doesn’t exist in the dictionary?
# Code
print(user_profile.get("phone", "Not available"))
Answer: It will print Not available because "phone" is not a key in user_profile .
d. Sets
Definition: An unordered collection of unique elements.
Syntax: Defined using curly braces {} .
Example Use: Tracking unique user IDs or removing duplicates from a list.
# Creating a set
unique_items = {"apple", "banana", "cherry"}
# Adding an element
unique_items.add("date")
print(unique_items) # Output might vary in order
Trick Question 5
Question: What will len(unique_items) print after adding "apple" again?
Answer: The length will remain the same because sets do not store duplicate values.
List: Use when you need an ordered, mutable collection (e.g., to-do list).
Tuple: Use for fixed data that shouldn’t change (e.g., coordinates).
Dictionary: Use for data with unique identifiers (e.g., student records).
Set: Use for unique items and quick membership tests (e.g., unique tags).
Preview for Next Lecture: Lists & Strings, and Brute Force
Approach
In our next class, we’ll go into more detail about Lists & Strings:
1. Learning Objectives
After this class, you’ll be able to:
Use advanced techniques to manipulate lists and strings for flexible data handling in Python.
Differentiate between list and string manipulation techniques like indexing, slicing, and list
comprehensions.
Apply the Brute Force approach, understanding its advantages and limitations in problem-solving.
Analyze the time and space complexity of simple algorithms and identify efficient approaches.
3. Real-World Example
Let’s consider a real-world example of a Brute Force approach. Imagine you’re locked out of your
smartphone and forgot the 4-digit PIN. Using a brute-force method, you could try each combination
from “0000” to “9999” until you find the correct code. With 10,000 possibilities, this approach might
work reasonably fast if the PIN is short, but if the PIN were longer (say, 10 digits), brute force would
take an impractical amount of time due to the explosion in possibilities.
Another example involves text analysis. Suppose you want to find all instances of a word in a long
document. A brute-force search would involve checking each position in the text to see if it matches
the word, which is simple to implement but can be inefficient, especially with larger documents.
Indexing and slicing are ways to access parts of a list. Indexing accesses a single element, while
slicing can retrieve multiple elements by specifying a range.
Python provides a variety of built-in methods to manipulate strings, which is useful for tasks like
formatting text or parsing input data.
sentence = "Python makes coding fun!"
# Convert to lowercase
lower_sentence = sentence.lower() # Output: "python makes coding fun!"
List comprehensions are a concise way to create lists. They’re powerful, especially when combined
with conditions.
In this example, we use brute force to find a target number in a list by checking each element.
For larger lists, brute force becomes inefficient, as it requires examining each element. Later, we’ll
explore optimized methods for such searches.
5. Pre-Reading Questions or Simple Exercises
1. Practice Slicing: Given nums = [5, 10, 15, 20, 25, 30, 35] , try slicing to get only
[10, 20, 30] .
2. List Comprehension Exercise: Create a list of cubes of numbers from 1 to 6 using a list
comprehension.
3. String Manipulation: Given the sentence text = "Data science is amazing" , use string methods
to (a) find the position of "science", (b) replace "amazing" with "challenging", and (c) convert the
entire sentence to uppercase.
4. Brute Force Thought Exercise: If you were to guess a 6-character password using brute force,
how long do you think it would take if each character can be any letter in the alphabet?
By exploring these concepts in Python, you’ll gain powerful tools for data manipulation and an
understanding of when brute force is effective (and when it isn’t). Be ready for a fun, hands-on class!
Pre-Class Reading: Complexity Analysis in Python
Learning Objectives
By the end of this lesson, you should be able to:
Algorithm
An algorithm is a series of steps designed to accomplish a specific task. Every program is essentially a set of algorithms working in tandem.
Complexity Analysis
Complexity analysis evaluates an algorithm’s efficiency by focusing on two key factors:
1. Time Complexity: Measures how execution time grows as input size increases.
2. Space Complexity: Examines how memory usage scales with input size.
Why Analyze Complexity?
Imagine searching through a stack of papers for a specific document. Some approaches, like checking each page individually, are
slow, while others, like using tabs or indexing, are much faster. Complexity analysis helps us choose the best method for efficient
programming.
Big O Notation
Big O notation provides a mathematical way to describe algorithm efficiency based on input growth. Key notations include:
O(1) - Constant Time Complexity: Always executes in the same time, regardless of input size. (Example: retrieving the first item in a
list.)
O(n) - Linear Time Complexity: Execution time grows linearly with input size. (Example: printing each item in a list.)
O(log n) - Logarithmic Time Complexity: Execution time grows slower than input size, often by eliminating half the possibilities each
time. (Example: binary search.)
O(n²) - Quadratic Time Complexity: Time grows quickly with input size, often due to nested loops. (Example: comparing all pairs in a
list.)
def get_first_item(lst):
return lst[0]
Explanation: This function retrieves the first item, taking the same amount of time, whether the list has 1 or 1,000,000 items.
def print_all_elements(lst):
for item in lst:
print(item)
Explanation: For a list of 10 items, it runs 10 times; for 100 items, it runs 100 times.
Explanation: Binary search narrows down by halves, like finding a word in the dictionary by starting in the middle.
def print_all_pairs(lst):
for i in lst:
for j in lst:
print(i, j)
Explanation: For 5 items, this runs 25 times (5x5). For 10 items, it runs 100 times (10x10), growing exponentially.
Identify one task in your daily life that has constant time complexity (O(1)).
Identify one task where time grows with workload (O(n)).
Types of Complexity
2. Space Complexity
Measures how much memory a program uses as it runs.
# Example of O(1)
def get_first_item(lst):
return lst[0] # Accessing the first item takes constant time
# Example of O(n)
def print_all_items(lst):
for item in lst:
print(item) # Goes through each item once
# Example of O(n^2)
def print_all_pairs(lst):
for i in range(len(lst)):
for j in range(len(lst)):
print(lst[i], lst[j]) # Checks every possible pair
# Example of O(log n)
def binary_search(lst, target):
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
2. Question: If you have two nested loops, each going through n items, what’s the time complexity?
Answer: O(n²) – Each loop runs n times, multiplying their effect.
Space Complexity: How Much Memory Does Your Code Use?
# Example of O(1)
def add_two_numbers(a, b):
return a + b # Only needs space for 'a' and 'b'
# Example of O(n)
def create_list_of_zeros(n):
return [0] * n # Uses memory for 'n' zeros
# Example of O(n^2)
def create_matrix(n):
return [[0] * n for _ in range(n)] # Creates an n x n matrix
O(1) return lst[0] Grabbing the first item on a shelf Accessing array elements by index
O(n) for item in lst: print(item) Reading every page in a book Searching or modifying each list item
O(n²) for i in range(n): for j in range(n) Comparing all pairs of socks Nested loops, brute-force combinations
For example, using a cache can speed up operations by storing data but uses more memory.
Practice Exercise
Write a function that takes a list of numbers and prints only the even numbers. What is the time complexity?
def print_even_numbers(lst):
for num in lst:
if num % 2 == 0:
print(num)
Python** and make programs more interactive. This is crucial for building responsive and user-friendly applications.
Pre-Class Reading: Let's Dive into Python Input and Functions
Together!
Input The data your user gives you while your program is running.
input() function Python's way of getting info from your user—think of it as starting a conversation!
Type Conversion Changing data from one type to another, like turning a string into a number.
Try-Except A way to handle errors gracefully, so your program doesn't crash if something unexpected happens.
Function A reusable piece of code that does something specific—your program's building blocks!
Concept What's It All About?
Return Value What your function hands back after it's done its job.
3. A Real-World Scenario
Imagine you're creating a registration system for a coding bootcamp. You need to ask users for their:
Depending on what they tell you, you can recommend beginner resources or advanced sessions. Pretty cool, right?
Why Convert?
Breaking It Down:
The split() method divides the input string into a list where each word is a separate item.
We assign those items to first_name and city .
Tip: Make sure to instruct your user to separate their inputs properly!
We're using a try-except block to catch any errors if the user doesn't enter a valid number.
If an error occurs, we gently prompt them to try again.
def greet_user(name):
"""Greets the user with their name."""
return f"Hello, {name}! Welcome aboard."
Function Fun:
5. Give It a Try!
Why not try these exercises yourself?
2. Calculating Age
Prompt the user to enter their first and last name in one line.
Use split() to separate them.
Greet them using both names.
4. Area Calculator
Misusing split()
Problem: If the user enters more or fewer names, you'll get an error.
Fix It: You can use split() without assigning all parts, or handle variable numbers of inputs.
full_name = input("Enter your full name: ")
name_parts = full_name.split()
print(f"Hello, {' '.join(name_parts)}!")
Feel free to play around with these examples and see what you can create. Don't hesitate to experiment—that's one of the best ways to
learn. See you in class, and happy coding!
Input Taking in Python - Student Notes
Purpose: Pauses the program and waits for the user to enter text.
Syntax: input("Enter your text here")
Return Value: Always gives back a string.
Example:
name = input("Enter your name: ") # Prompt user for their name
print("Hello, " + name + "!") # Greets the user
In this example, input() takes the user’s response and treats it as a string, even if it’s a number! This means every input is initially stored as text.
Example:
Imagine asking for someone’s age. Without converting it, age = input("Enter age: ") would treat "25" as text, not a number. Type conversion
makes it easy to handle different data types in calculations and comparisons!
Example:
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except ValueError:
print("Oops! That's not a valid number!")
If someone enters "abc" for age, the program catches the error and displays “Oops! That’s not a valid number!” instead of crashing. Try-except
makes programs user-friendly and resilient against unexpected input!
Example:
name, age = input("Enter your name and age: ").split() # Splits input by space
age = int(age) # Convert age to integer
If the user enters Alice 25 , name will be "Alice" and age will be 25 . Simple and efficient!
input() Takes a single line of user input input("Enter name") Basic user input
int(input()) /
Converts input to integer/float int(input("Enter age: ")) Numerical input (age, height, etc.)
float()
Trick Questions
1. Question: What happens if you try to convert "hello" to an integer?
Answer: You’ll get a ValueError because "hello" isn’t a number. Using try-except will prevent the program from crashing.
2. Question: Why does input("Enter number: ") + input("Enter another: ") give unexpected results?
Answer: The inputs are strings, so they concatenate instead of adding! For example, "4" + "5" gives "45" , not 9 . Convert to integers for
numerical addition.
try:
num1, num2 = map(float, input("Enter two numbers separated by space: ").split())
operator = input("Enter an operation (+, -, *, /): ")
if operator == '+':
print("Result:", num1 + num2)
elif operator == '-':
print("Result:", num1 - num2)
elif operator == '*':
print("Result:", num1 * num2)
elif operator == '/':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Cannot divide by zero!")
else:
print("Invalid operator!")
except ValueError:
print("Please enter valid numbers!")
Solution Notes: This program uses map() for type conversion, try-except for error handling, and if-elif statements for choosing operations.
Fun and practical!