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

CSE101 Lecture Notes for Mid Term Exams

The document outlines the introductory concepts of programming, focusing on Python, including the definition of programming, the role of algorithms, and essential programming elements like variables and data types. It provides practical examples, basic syntax, and common programming mistakes, along with exercises to reinforce learning. Additionally, it previews upcoming topics on mathematical and comparison operators.

Uploaded by

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

CSE101 Lecture Notes for Mid Term Exams

The document outlines the introductory concepts of programming, focusing on Python, including the definition of programming, the role of algorithms, and essential programming elements like variables and data types. It provides practical examples, basic syntax, and common programming mistakes, along with exercises to reinforce learning. Additionally, it previews upcoming topics on mathematical and comparison operators.

Uploaded by

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

Pre-Class Reading for Lecture 1: Introduction to Programming

Learning Objectives:

In the upcoming lecture, you will:

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.

Key Concepts or Vocabulary:


Programming: Writing instructions for a computer to execute. Think of programming like writing a
list of instructions for a friend. Instead of saying "turn left at the next street," you're telling the
computer to do things like "display this message" or "calculate this value." You write these
instructions in a programming language such as Python.
Algorithm: A structured series of steps to solve a specific problem. An algorithm can be thought
of as a recipe in cooking. For example, if you want to bake a cake, your algorithm would be the list
of steps you follow (e.g., mix ingredients, bake for 30 minutes).
Source Code: The text of a program written by the programmer. This is the raw code that you
write and edit. For example, writing print("Hello, World!") in Python is a simple piece of source
code. The source code is the human-readable version of your program before it gets translated
into machine language.
Compiler/Interpreter: Tools that convert source code into machine code that the computer can
understand. In Python, we use an interpreter, which reads and executes code line-by-line,
translating it into actions the computer can perform.
Variables: Containers in which we store data that can be changed and used later. Imagine a
variable as a storage box. You can put a piece of information inside, like a number or a word, and
then retrieve it whenever you need it.
Data Types: The types of data that can be stored in variables, such as:
Integers (int): Whole numbers like 5 or -10.
Floating-point numbers (float): Numbers with decimals, such as 3.14.
Strings (str): Sequences of characters, like "Hello, World!"
Booleans (bool): True or False values.
Text Editor or IDE: A software application where you write and edit your source code. An IDE
(Integrated Development Environment) like VSCode or PyCharm offers additional tools like syntax
highlighting and auto-completion to make programming easier.
Type Casting: Converting data from one type to another, such as converting a string "21" into
an integer 21 .

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?

For example, you could write a program that:

Reminds you to drink water every hour.


Automatically sends emails.
Tracks your expenses and generates a weekly report.

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:

1. Your First Program: Hello, World!

# This prints "Hello, World!" to the screen


print("Hello, World!")

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.

2. Working with Variables:

# Storing a name in a variable and printing a greeting


name = "Alice"
print("Hello, " + name + "!")

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!" .

3. User Input and Data Conversion:

# Taking input from the user and converting it to an integer


age = input("Enter your age: ") # This takes the user's input as a string
age = int(age) # Convert the string to an integer
print("You are " + str(age) + " years old!")

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.

Pre-Reading Questions or Simple Exercises:


To prepare for the upcoming class, try the following:

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?

Common Mistakes or Misconceptions:


Indentation in Python: One of the unique things about Python is that it uses indentation (spaces)
to define code blocks. Forgetting to indent properly or using inconsistent indentation is one of the
most common mistakes beginners make.
Example of correct indentation:

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!

To fix this, you must convert the integer to a string first:

print("You are " + str(age) + " years old!")

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") .

Teaser for the Lecture:


In the next class, we’ll dive deeper into Conditional Statements, explore the Mathematical and
Comparison Operators, and learn how to implement logic to make decisions within your Python
programs.
Notes for CSE101 - Programming Fundamentals (Lecture 1)

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.

Why Learn Programming?


Programming is everywhere today, from the apps on your phone
to the websites you visit. Learning how to program enables you to
build applications, automate tasks, solve problems, and much
more! Plus, with technology growing at such a fast pace, it’s a
skill that's in high demand.

Basic Concepts of Programming

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.

Setting Up the Environment


To start programming, you need a suitable environment. For this course, we'll use Python. Here’s
what you need to set up:

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:

print() is a function in Python used to display messages.


"Hello, World!" is the message inside the parentheses, and the output will be shown on your

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.

Basic Syntax in Python


Python’s syntax is designed to be easy to read and write. Here are some key rules:

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.

# This is a comment and will be ignored by the Python interpreter


print("This is code!")

Problem Statement:
Write a Python program to print your name.

Hint: Use the print() function.

2. Introduction to Python: Variables and Data Types


What are Variables?
Variables are like storage containers in programming. They hold information that you can use and
manipulate later. For example, think of variables as a box where you can store your favorite snack.
You can open the box (the variable) whenever you want to eat the snack (access the data).

Example:

name = "Alice"
age = 21

Here, name is a variable storing the string "Alice" , and age is a variable storing the number 21 .

Primitive Data Types in Python

1. Integers ( int ) : Whole numbers, like 5 , 100 , -25 .


2. Floating-point numbers ( float ): Numbers with decimals, like 3.14 , -9.8 .

3. Strings ( str ) : Text, like "Hello" , "Python" .


4. Booleans ( bool ) : Either True or False .

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.

Variables and Constants

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.

In Python, constants are typically written in uppercase to distinguish them. Example:

PI = 3.14159 # This value shouldn't change


Problem Statement:
Create a Python program that calculates and displays the total price of two products in a store. For
each product, define variables to store the product name, its price, and the quantity available. The
program should:
1. Use variables for each product's name, price (as a floating-point number), and quantity (as an
integer).
2. Calculate the total cost for each product by multiplying the quantity by the price.
3. Add the total costs of both products to get the overall total.
4. Display the name of each product, its total cost, and the overall total using f-strings.

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

# Defining product 2 details


product2_name = "Milk"
product2_price = 2.00
product2_quantity = 2
product2_total = product2_price * product2_quantity # Calculating total cost for product 2

# Calculating overall total


overall_total = product1_total + product2_total

# Displaying results using f-strings


print(f"Product 1: {product1_name}, Quantity: {product1_quantity}, Price per unit: ${product1_price}")
print(f"Product 1 Total: ${product1_total:.2f}\n")

print(f"Product 2: {product2_name}, Quantity: {product2_quantity}, Price per unit: ${product2_price}")


print(f"Product 2 Total: ${product2_total:.2f}\n")

print(f"Overall Total: ${overall_total:.2f}")

Output
Product 1: Apples, Quantity: 3, Price per unit: $1.5
Product 1 Total: $4.50

Product 2: Milk, Quantity: 2, Price per unit: $2.0


Product 2 Total: $4.00

Overall Total: $8.50


Type Casting
Sometimes, you need to convert one data type into another. This is called type casting.

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'

Problem Statement (Topic might not be covered in lecture):


- Create a Python program that does the following:
1. Takes a user’s name (string) as input.
2. Converts the name to uppercase.
3. Prints the message: "HELLO, [UPPERCASE_NAME]!" .

Step-by-Step Solution:

1. Step 1: Use the input() function to get the user’s name.


2. Step 2: Use the .upper() method to convert the name.
3. Step 3: Use print() to display the final message.

Solution:

name = input("Enter your name: ")


name_upper = name.upper()
print(f"HELLO, {name_upper}!")
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.

Fun Facts about Python Programming


Did you know? Python is named after the British comedy group Monty Python , not after the
snake!
Where is Python used? From web development (like Instagram) to AI research and scientific
computing, Python is everywhere! It’s even used by NASA.

Extra Challenge (Might not covered in the class):


Write a Python program that asks for two numbers, adds them together, and prints the result.

Hint: Use input() to take input and int() to convert strings to integers.
Pre-Class Reading: Mathematical Operator and Comparison
Operator
Learning Objectives:

In the upcoming session, you'll learn:

How to use arithmetic operators to perform basic mathematical operations.


The role of relational (comparison) operators in making decisions based on conditions.
How to combine multiple conditions using logical operators.
How assignment operators help modify and store values in variables.

Key Concepts or Vocabulary:

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

if price_A > price_B:


print("Item A is more expensive.")
Similarly, arithmetic operators help us in daily activities like calculating the total cost of items in a cart:

item_1 = 50
item_2 = 30
total = item_1 + item_2

print("Total cost:", total)

Mini Code Snippets:

1. Using Arithmetic Operators:

num1 = 10
num2 = 5

print(num1 + num2) # Addition: 15


print(num1 - num2) # Subtraction: 5
print(num1 * num2) # Multiplication: 50
print(num1 / num2) # Division: 2.0

2. Using Relational Operators:

a = 10
b = 20

print(a > b) # False


print(a < b) # True
print(a == b) # False

3. Using Logical Operators:

score1 = 60
score2 = 45

if score1 > 50 and score2 > 50:


print("Both scores are above 50.")
else:
print("At least one score is below 50.")

Pre-Reading Questions or Simple Exercises:

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.

Common Mistakes or Misconceptions:

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.

Teaser for the Next Lecture:

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)

Mathematical Operator and


Comparison Operator

In programming, operators are symbols that perform operations on


variables and values. These operations range from basic arithmetic
to logical comparisons. Think of operators as the "verbs" in
programming—they perform the action! Let's dive into the various
types of operators and how they are
used.

1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction,
multiplication, and more.

Basic Arithmetic Operators in Python:

1. + (Addition) – Adds two values.


Example: 3 + 2 equals 5
2. - (Subtraction) – Subtracts one value from another.
Example: 5 - 2 equals 3
3. * (Multiplication) – Multiplies two values.
Example: 4 * 2 equals 8
4. / (Division) – Divides one value by another.
Example: 10 / 2 equals 5.0 (Note: The result is always a float in Python.)
5. % (Modulus) – Returns the remainder of a division.
Example: 10 % 3 equals 1 (because 10 divided by 3 leaves a remainder of 1)
6. ** (Exponentiation) – Raises one number to the power of another.
Example: 2 ** 3 equals 8 (2 raised to the power of 3)
7. // (Floor Division) – Divides and returns the integer part (removes the decimal).
Example: 10 // 3 equals 3

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.

Relational Operators in Python:

1. == (Equal to) – Checks if two values are equal.


Example: 5 == 5 returns True
2. != (Not equal to) – Checks if two values are not equal.
Example: 5 != 4 returns True
3. > (Greater than) – Checks if the left value is greater than the right.
Example: 6 > 3 returns True
4. < (Less than) – Checks if the left value is less than the right.
Example: 4 < 6 returns True
5. >= (Greater than or equal to) – Checks if the left value is greater than or equal to the right.
Example: 5 >= 5 returns True
6. <= (Less than or equal to) – Checks if the left value is less than or equal to the right.
Example: 3 <= 4 returns True

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.

Logical Operators in Python:

1. and – Returns True if both conditions are True .


Example: (5 > 3) and (4 == 4) returns True because both conditions are true.
2. or – Returns True if at least one condition is True .
Example: (5 < 3) or (4 == 4) returns True because the second condition is true.
3. not – Reverses the result; returns False if the condition is True , and vice versa.
Example: not (5 > 3) returns False because 5 > 3 is True , and not flips it to False .
Real-Life Example:
Imagine you're deciding whether to go out for a walk. You might check two conditions:

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.

Assignment Operators in Python:

1. = (Assignment) – Assigns a value to a variable.


Example: x = 5 assigns the value 5 to the variable x .
2. += (Add and Assign) – Adds the right value to the left value and assigns the result.
Example: x += 3 is the same as x = x + 3 .
3. -= (Subtract and Assign) – Subtracts the right value from the left value and assigns the result.
Example: x -= 2 is the same as x = x - 2 .
4. *= (Multiply and Assign) – Multiplies the right value by the left value and assigns the result.
Example: x *= 4 is the same as x = x * 4 .
5. /= (Divide and Assign) – Divides the left value by the right value and assigns the result.
Example: x /= 2 is the same as x = x / 2 .
6. %= (Modulus and Assign) – Takes the modulus of the two values and assigns the result.
Example: x %= 3 is the same as x = x % 3 .

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: "))

# Comparison using relational operators


if age1 > age2:
print("The first person is older.")
elif age1 < age2:
print("The first person is younger.")
else:
print("Both persons are of the same age.")

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:

Gain a deep understanding of how conditional logic works in Python.


Learn to write programs that make decisions based on user input or other conditions.
Explore how the if , elif , and else statements allow for more flexible control over your
program's flow.
Practice using loops to execute code repeatedly, either for a set number of times (for loops) or
until a condition is met (while loops).
Discover how nested conditions and loops handle complex scenarios where multiple criteria or
repetitions must be met.
Understand the importance of breaking down complex logic using loops for more efficient and
readable code.
Apply your knowledge through real-world examples and exercises to reinforce your
understanding.

Key Concepts and Vocabulary


1. If Statement:
A control structure that allows your program to execute a block of code if a certain condition is true. If
the condition is false, the code inside the if block is skipped.
Example:

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:

for item in sequence:


# code that runs for each item in the sequence

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:

value = "Yes" if condition else "No"

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.

Real-World Examples of Conditional Logic and Loops


Example 1: Traffic Lights
Traffic signals work using conditional logic. If a pedestrian presses the button to cross, the light
changes after a brief delay. The conditional check is: "Has the button been pressed?" If yes, change
the light; if no, continue with the regular cycle.

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 = ""

while password != correct_password:


password = input("Enter password: ")

print("Access granted!")

Example 3: Looping Over a List with a For Loop


Consider a situation where you want to send a welcome message to a list of new users.

Code Analogy:

new_users = ["Alice", "Bob", "Charlie"]

for user in new_users:


print(f"Welcome, {user}!")

Mini Code Snippets: Understanding Python’s Conditional


Statements and Loops
1. Simple If-Else Statement:

age = 20

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
2. Using Elif for Multiple Conditions:

temperature = 22

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.")

3. While Loop for Repeated Input:

attempts = 0
while attempts < 3:
password = input("Enter password: ")
if password == "secret":
print("Access granted")
break
attempts += 1

4. For Loop Iterating Over a Range:

for i in range(5):
print(f"This is loop iteration {i}")

Pre-Reading Questions or Simple Exercises


1. Simple Condition:
Write a Python program that checks if a number entered by the user is positive, negative, or zero.
2. Voting Age Check:
Modify the voting eligibility program to check if the person is eligible to vote based on both age
and country. Use nested conditions for this.
3. While Loop Practice:
Write a program that repeatedly asks the user to guess a number between 1 and 10. The loop
should stop when they guess correctly.
4. For Loop Practice:
Write a program that prints the squares of numbers from 1 to 10 using a for loop.

Common Mistakes or Misconceptions


1. Forgetting Indentation:
Python uses indentation to define blocks of code. A common beginner mistake is to forget to
indent code properly under if , elif , else , while , and for blocks.
2. Incorrect Use of Elif and If:
Remember that elif is only checked if all preceding if or elif conditions are false.
Sometimes beginners place if when they mean to use elif .
3. Overusing Nested Loops and Conditions:
Nested loops and conditions are useful but can make code hard to read. Simplify where possible
by breaking down logic or using boolean operators like and or or .

A Teaser for the Lecture


Here’s something to think about before class: What happens when you combine loops within loops,
and how does Python manage these nested structures? We’ll dive into nested loops and explore how
they can interact with lists to solve more complex problems.

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.

1.1 If-Else Statement


The if statement checks if a condition is true. If it’s true, the code inside the if block is executed.
Otherwise, the else block is executed.

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:

If the store is open, you can buy groceries.


Otherwise, you have to wait until it opens.
1.2 Elif Statement
What if you have more than two conditions? This is where the elif statement comes in. It allows for
multiple conditions to be checked sequentially.

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:

number = int(input("Enter a number: "))


if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

1.3 Nested If Statements


You can put an if statement inside another if statement to make more complex decisions.
Example:

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.

2.1 For Loop


A for loop lets you iterate over a sequence (like a list, tuple, or string) and repeat the same block of
code for each item.

Syntax:

for item in sequence:


# Instructions

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.

2.2 For Loop with range()


The range() function generates a sequence of numbers. It's commonly used with for loops.

Syntax:

for i in range(start, stop, step):


# Instructions

Example:

for i in range(1, 6):


print(i)

Problem 2:
What will the following code output?

for i in range(1, 10, 2):


print(i)

Solution:
The code prints the numbers: 1, 3, 5, 7, 9.

2.3 While Loop


A while loop repeats as long as a condition is true.

Syntax:

while condition:
# Instructions
Example:

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

Real-Life Example:

Keep watering a plant while it is still thirsty.

Trick Question:
What will happen if you forget to update the count variable in the previous example?

3. Loop Control Statements


3.1 Break
The break statement exits a loop before it has finished.

Example:

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

Output: 0, 1, 2 (The loop stops when i is 3.)

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.

Trick Questions for Practice:


1. What will this code output?

for i in range(10, 1, -2):


print(i)

2. Write a Python program to print all even numbers between 1 and 20 using a for loop.

Preview for Next Lecture:


In the next class, we’ll dive deeper into Nested Loops and Lists in Python. Nested loops allow us to
handle more complex repetition scenarios, and lists are a powerful data structure in Python that helps
us organize and manipulate data efficiently.
Pre-Class Reading: Nested Loops and Lists in Python
1. Learning Objectives
In this session, you will:

Understand what nested loops are and how to use them.


Learn how lists in Python can be used with loops, including nested loops.
Explore practical uses for nested loops and lists in solving problems.
Gain confidence in writing and reading code that involves multiple layers of loops.

2. Key Concepts or Vocabulary


Loop: A sequence of instructions that repeats until a certain condition is met.
Nested Loop: A loop inside another loop. The inner loop runs completely for every iteration of the
outer loop.
List: A collection in Python that holds multiple items, such as numbers or strings, in a specific
order.
Iteration: The process of repeating actions (or looping) for each item in a collection or sequence.
Index: The position of an item in a list. Python uses zero-based indexing, meaning the first item is
at index 0.

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).

4. Mini Code Snippets


Here’s a simple example of a nested loop that prints out the multiplication table from 1 to 3:
# Outer loop for the numbers 1 to 3
for i in range(1, 4):
# Inner loop for the numbers 1 to 3
for j in range(1, 4):
# Print multiplication of i and j
print(f"{i} * {j} = {i * j}")
# Blank line to separate each table
print()

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.

Here’s an example with a list of student names for different classes:

# List of classes, each class contains a list of students


classes = [
["John", "Alice", "Bob"],
["Sara", "Tom", "Linda"],
["Mike", "Jane", "Anna"]
]

# Outer loop to go through each class


for class_group in classes:
# Inner loop to go through each student in the class
for student in class_group:
print(student)
# Blank line to separate each class's list of students
print()

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.

5. Pre-Reading Questions or Simple Exercises


Try these questions to prepare for class:
1. What will be the output of the following code snippet?

for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")

2. Can you write a nested loop to print the following pattern?

* * *
* * *
* * *

3. Create a list of three of your favorite foods, and use a nested loop to print each character in each
food's name.

6. Common Mistakes or Misconceptions


Forgetting to fully understand the flow of loops: Sometimes beginners get confused about
how the inner loop completes all its iterations before the outer loop moves to the next step.
Confusing inner and outer loop variables: It’s easy to accidentally mix up the loop variables
(e.g., using the same name for both loops).
Misunderstanding list indexing: Python lists start at index 0, so the first item is list[0] , not
list[1] .
Overcomplicating loops: You might find yourself overthinking loop logic. Start simple and walk
through each iteration manually if necessary.

7. A Teaser for the Lecture


Imagine you’re designing a basic game where the player can move on a grid (like chess or checkers).
How can we use nested loops to check each possible position on the board and determine if a move is
valid? In our lecture, we’ll explore how nested loops can be the key to solving problems like this in
gaming, data analysis, and more!

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

What is a Nested Loop?


A nested loop is a loop inside another loop. The outer loop runs first, and for each iteration of the
outer loop, the inner loop runs completely. Nested loops allow us to perform complex iterations,
making them useful for tasks like processing multi-dimensional data or creating patterns.

Example: Printing Patterns


Imagine you are tasked with printing a triangular pattern like this:

*
* *
* * *
* * * *

To achieve this, you can use a nested loop:

for i in range(1, 5):


for j in range(1, i+1):
print("*", end=" ")
print()

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.

Trick Question #1:


What will be the output of this code?

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.

Example: Creating and Using Lists


You can create a list by enclosing items in square brackets:

my_list = [1, 2, 3, 4, 5]
print(my_list)

You can access elements in a list by using their index:

print(my_list[0]) # Output: 1
List Operations:
Appending: Adds an item to the end of the list.

my_list.append(6)

Removing: Removes the specified item.

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.

Trick Question #2:


What is the output of this code?

my_list = [1, 2, 3, 4]
my_list[1] = 10
print(my_list)

Think: What happens when you modify an element at a specific index?

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:

squares = [x**2 for x in range(5)]


print(squares)

This creates a list of squares for the numbers 0 to 4.


Trick Question #3:
What will be the output of this list comprehension?

my_list = [x for x in range(6) if x % 2 == 0]


print(my_list)

Think: How does the list comprehension filter the values?

4. Using Nested Loops with Lists


You can combine nested loops with lists to iterate over complex data structures like 2D lists (lists of
lists).

Example:

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix:


for element in row:
print(element, end=" ")
print()

In this example, the outer loop iterates over each row, and the inner loop iterates over each element in
that row.

Summary of Key Concepts


Nested Loops: Loops within loops, used for multi-dimensional operations or repeated tasks.
Lists: Ordered collections of items, allowing you to store, access, and modify data efficiently.
List Comprehensions: A concise way to create and manipulate lists.
Combining Nested Loops with Lists: Useful for working with multi-dimensional data like
matrices.

Trick Question #4:


What happens if you try to access an index that doesn’t exist in a list?

Hint: Think about error handling in Python.

Preview of Next Lecture: Strings in Python


In the next class, we’ll explore strings in Python — how to work with text, perform operations like
slicing, and manipulate strings efficiently. Here’s a sneak peek:

Example:

my_string = "Hello, World!"


print(my_string[0:5]) # Output: Hello

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:

Understand what a string is and how to create one in Python.


Use common string methods to manipulate and analyze text data.
Learn how to format and combine strings for various tasks.
Avoid common mistakes when working with strings.

2. Key Concepts or Vocabulary


Here are some important terms that will come up in the lesson:

String: A sequence of characters enclosed in quotes. Example: "Hello, World!"


Concatenation: The process of joining two or more strings together using the + operator.
Indexing: Accessing a specific character in a string using its position (index).
Slicing: Extracting a portion of a string using a range of indices.
String Methods: Built-in functions that perform operations on strings (e.g., .lower() ,
.replace() , .split() ).

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.

4. Mini Code Snippets


Let's look at a few basic Python string operations with some comments to explain what's happening.

Creating and printing a string:

my_string = "Python is fun!"


print(my_string) # Output: Python is fun!

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

Using a string method:

greeting = "Hello, World!"


print(greeting.lower()) # Output: hello, world!
5. Pre-Reading Questions or Simple Exercises
Before the class, try to think about or experiment with the following:

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?

6. Common Mistakes or Misconceptions


Mixing Data Types: One common mistake beginners make is trying to combine strings with
numbers without converting the number to a string first. For example:

age = 25
print("I am " + age + " years old.") # This will cause an error!

You must convert the number to a string:

print("I am " + str(age) + " years old.") # This will work!

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.

7. A Teaser for the Lecture


Think about this: How would you extract just the domain name from an email address like
"student@example.com" ?

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!

1. What are Strings?


In Python, a string is simply a sequence of characters enclosed within quotes. You can use either
single ( ' ' ) or double ( " " ) quotes to define a string.

Example:

my_string = "Namaste, Python!"


print(my_string) # Output: Namaste, Python!

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.

2. Basic String Operations


We can perform several simple yet powerful operations with strings, such as concatenation, repetition,
and accessing characters.

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

Repetition: Repeating a string multiple times using the * operator.

slogan = "India! "


print(slogan * 3) # Output: India! India! 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:

my_string = "Incredible India"


print(my_string[0:10]) # Output: Incredible

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?

text = "Welcome to India"


print(text[4:10])

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.

print("DELHI".lower()) # Output: delhi

.replace(): Replaces a part of the string with another string. For instance, changing “Ganga” to
“Yamuna.”

river = "Ganga is clean"


print(river.replace("Ganga", "Yamuna")) # Output: Yamuna is clean

.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.

sentence = "Learn Python Programming"


print(sentence.split()) # Output: ['Learn', 'Python', 'Programming']

Trick Question #2
What will be the result of this code?

phrase = "India Shining"


print(phrase.upper().replace("I", "A"))

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.

new_word = "D" + word[1:]


print(new_word) # Output: Dumbai

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.

print("Name: {}, Age: {}".format(name, age)) # Output: Name: Raj, Age: 20

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 {} .

print(f"Name: {name}, Age: {age}") # Output: Name: Raj, Age: 20

Preview of Next Lecture: Multidimensional Lists and Functions


Next time, we will be exploring Multidimensional Lists and Functions in Python. Imagine managing
student marks in multiple subjects or organizing a cricket score table. Multidimensional lists (like 2D
lists) help us handle such tasks efficiently.

Here’s a small teaser:

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).

2. Key Concepts or Vocabulary


Function: A block of code that performs a specific task and can be reused whenever needed.
Functions help keep your code organized and efficient.
Defining a Function: In Python, we define a function using the def keyword, followed by the
function name and parentheses. Example: def greet():
Calling a Function: Once a function is defined, you can "call" it by using its name followed by
parentheses. Example: greet()
Multidimensional List: A list that contains other lists as its elements, allowing you to organize
data in a structure similar to rows and columns.

3. Real-World Example: Why Use Functions?


Imagine you’re planning a birthday party and need to send out 50 personalized invitation messages. If
you write a message 50 times, that’s repetitive and takes a lot of time. Instead, you could create a
function to print your message just once and call it as many times as you need. Functions save time,
reduce errors, and make it easy to reuse code.
4. Mini Code Snippets

A. Basic Function: Saying Hello


Let’s look at a simple function that prints "Hello!" each time it’s called.

# Defining the function


def say_hello():
print("Hello!")

# Calling the function


say_hello() # Output: Hello!
say_hello() # Output: Hello!

In this example, say_hello() is our function. Every time we call it, it prints "Hello!".

B. Functions with Parameters


Functions can also take inputs, known as parameters. Let’s make say_hello() more flexible by
allowing it to greet by name.

# Defining a function with a parameter


def say_hello(name):
print("Hello, " + name + "!")

# Calling the function with different names


say_hello("Alice") # Output: Hello, Alice!
say_hello("Bob") # Output: Hello, Bob!

Now, say_hello(name) takes a name as input and prints a personalized greeting.

5. Introducing Multidimensional Lists


A multidimensional list (often a 2D list) is like a list of lists. This structure is useful when you want to
organize data in a grid or table format.
For example, here’s a 2D list that stores student grades for three subjects:

# A 2D list of grades for three students in three subjects


grades = [
[85, 90, 78], # Grades for student 1
[88, 76, 92], # Grades for student 2
[90, 88, 84] # Grades for student 3
]

# Accessing data in a 2D list


print(grades[0]) # Output: [85, 90, 78] (all grades for student 1)
print(grades[1][2]) # Output: 92 (third subject grade for student 2)

6. Pre-Reading Questions or Simple Exercises


Try these to get familiar with functions and multidimensional lists:

1. Function Practice: Write a function called introduce() that prints


"Hello, I'm learning Python!" . Call the function to see the output.
2. Adding Parameters: Modify the introduce() function to accept a parameter for a name, so it
prints "Hello, [name]! I'm learning Python!" .
3. Working with Lists: Create a 2D list representing a 3x3 grid of numbers, like a tic-tac-toe board.

7. Common Mistakes or Misconceptions


Forgetting to Call Functions: Defining a function does not mean it will run. You need to call it
using its name, like introduce() .
Mixing Parameters: If a function has parameters, remember to provide values for them when
calling it.
Accessing Elements in 2D Lists: Remember to use two indices for 2D lists. For example,
grades[1][2] refers to the second list’s third item.
8. A Teaser for the Lecture
What if you wanted to calculate the average grade of each student in a 2D list of grades? Could we
write a function to do that? Today’s class will show you how!

Looking forward to seeing you in class!


Multidimensional Lists and Functions
Overview
Today’s lecture focused on understanding multidimensional lists and functions in Python, both of which
are fundamental to handling complex data structures and performing repetitive tasks efficiently. This
knowledge is foundational for creating sophisticated applications and streamlining our code.

Section 1: Multidimensional Lists


1.1 What are Multidimensional Lists?
Definition: A multidimensional list is essentially a list where each element is also a list. This
creates layers, or "dimensions," within the main list.
Examples in Daily Life: Think of a spreadsheet. Each row of the spreadsheet could be
represented as a list, and the entire spreadsheet itself as a 2D list. Similarly, a Rubik's Cube can
be thought of as a 3D list, with each side containing smaller units.

1.2 Types of Multidimensional Lists


2D Lists (Grids/Tables):
Structured like a grid, with rows and columns.
Example: A list representing a Tic-Tac-Toe board:

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:

print(board[1][2]) # Outputs 'O'

3D Lists: Access using three indices.


Example:

print(cube[0][1][1]) # Outputs '4'

1.4 Iterating through Multidimensional Lists


Nested Loops: Use a loop for each dimension.
Example for 2D list:

for row in board:


for cell in row:
print(cell, end=" ")

1.5 List Manipulation


Adding Elements:
2D Example: list.append(["new", "row"])
Removing Elements:
2D Example: del list[1][2]

1.6 Applications of Multidimensional Lists


Matrices for Mathematical Operations: Useful in data analysis and scientific computing.
Image Processing: A grayscale image can be represented as a 2D list of pixel values; a colored
image as a 3D list (width, height, color channels).
Game Boards: Structuring board games like chess or Sudoku as a multidimensional list.

Quick Trick Questions


1. Trick Question: What will be the output of the following code?

board = [[1, 2, 3], [4, 5, 6]]


print(board[0][3])

Answer: An IndexError because there’s no fourth element in the first list.


2. Trick Question: How can you replace the value 5 with 9 in the board example from section
1.2?
Solution:

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

2.2 Defining Functions


Function Declaration: Use the def keyword, name the function, add any necessary parameters,
and then the function body.
Example:

def greet(name):
return f"Hello, {name}!"

2.3 Function Parameters


Positional Parameters: Passed in order of declaration.
Keyword Parameters: Specified by name, allowing flexibility.
Example:

def display_info(name, age=18):


print(f"Name: {name}, Age: {age}")

2.4 Return Values


Single Return Value: return statement allows us to send data back from the function.
Multiple Return Values: A function can return multiple values as a tuple.
Example:

def divide(a, b):


return a // b, a % b

2.5 Lambda Functions


Definition: Anonymous (nameless) functions, often used for short, single-expression functions.
Example:

square = lambda x: x ** 2

Quick Trick Questions


1. Trick Question: What is the difference between return x and print(x) in a function?
Answer: return sends the value back to the caller, allowing further use, while print just
displays it on the screen.
2. Trick Question: What will this code output?

def add(a, b):


return a + b
print(add(3, add(2, 1)))

Solution: add(2, 1) returns 3 , so add(3, 3) outputs 6 .

Preview of Next Lecture: Classes and Inbuilt Functions


In the next lecture, we will dive into Classes, which are the foundation of Object-Oriented
Programming (OOP). We will explore how to create objects, use attributes, and define methods within
classes. Additionally, we’ll discuss Inbuilt Functions in Python that make our code more efficient,
helping us avoid reinventing the wheel.

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.

Let’s dive in to get a strong foundation before class!

1. Learning Objectives
By the end of the session, you will be able to:

Explain what a class is and how it allows us to create objects in Python.


Create and use your own classes, with methods (functions inside classes) and attributes
(variables inside classes).
Recognize and use Python's inbuilt functions to perform various tasks and simplify your code.
See how classes and inbuilt functions work together to make Python code both efficient and
organized.

2. Key Concepts or Vocabulary


Here are some key terms to keep in mind as we explore classes and functions:

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.

3. Real-World Example: Library Books


Imagine a library needs a system to keep track of its books. Each book has a title, author, and status
(whether it’s available or borrowed). Using classes, we can create a Book class that has attributes
(title, author, availability) and methods to manage the book’s status.

For example:

The Book class will act as a template for all books.


Each specific book (like "Harry Potter and the Sorcerer's Stone" by J.K. Rowling) will be an
object created from this template.
We can add methods to borrow or return the book, making the system more functional.

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.

4. Mini Code Snippets


Here’s a simple code example to show you how classes work and how inbuilt functions can be used
with them.

Creating a Simple Class


In this example, we’ll create a Book class that keeps track of the book’s title, author, and availability
status.
# Defining a Book class
class Book:
def __init__(self, title, author):
self.title = title # Sets the title of the book
self.author = author # Sets the author of the book
self.available = True # Sets availability status as True (available to borrow)

# Method to borrow the book


def borrow(self):
if self.available: # Checks if the book is available
self.available = False # Sets status to borrowed
print(f"You borrowed '{self.title}' by {self.author}")
else:
print(f"Sorry, '{self.title}' is already borrowed.")

# Method to return the book


def return_book(self):
self.available = True # Sets status back to available
print(f"You returned '{self.title}'.")

# Creating a book object (an instance of Book class)


my_book = Book("Python 101", "John Doe")
my_book.borrow() # Borrow the book
my_book.return_book() # Return the book

Using Inbuilt Functions with a Class


Now let’s use some inbuilt functions to interact with our Book object:

# Checking the type of the object we created


print(type(my_book)) # Output: <class '__main__.Book'>

# Checking if my_book is an instance of the Book class


print(isinstance(my_book, Book)) # Output: True

# Checking if my_book has an attribute 'title'


print(hasattr(my_book, 'title')) # Output: True

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.

6. Common Mistakes or Misconceptions


Here are a few common areas where beginners often make mistakes:

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.

7. A Teaser for the Lecture


Ever wonder how you could efficiently manage hundreds or even thousands of items, like books in a
library or cars in a showroom? In the lecture, we’ll explore how classes make this possible and
introduce more powerful inbuilt functions that make coding in Python even easier and more effective!

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

1. Introduction to Object-Oriented Programming


(OOP)
OOP is a programming paradigm that uses "objects" to represent data and functionality. Each
object can contain:
Attributes (data specific to the object)
Methods (functions that perform actions on the object)
Key Benefits of OOP:
Modularity: Code is organized into classes and objects, making it easier to manage.
Reusability: Classes can be reused across different parts of the program.
Maintenance: The structure of OOP makes updating or changing code more manageable.

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

Here, Car is a class with attributes make and 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."

3. Objects and Constructors


Objects: An instance of a class, representing individual "real-world" entities created based on the
class blueprint.
Constructor: A special method __init__ that initializes attributes when an object is created.
self: Refers to the current instance and allows accessing attributes and methods.

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:

Q: Will the following code create an error?

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

def __init__(self, make, model):


self.make = make
self.model = model # Instance attribute

@classmethod
def change_wheels(cls, new_count):
cls.wheels = new_count # Modifies class attribute

@staticmethod
def car_type():
return "Vehicle"

Trick Question:

Q: What will be the output of print(Car.wheels) and Car.change_wheels(6); print(Car.wheels) ?


Solution: Initially, Car.wheels is 4. After calling Car.change_wheels(6) , Car.wheels will become
6.

5. Built-in Functions in Python


Python has several inbuilt functions for performing common tasks, organized into categories:

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:

Q: What will pow(2, 3) output?


Solution: The output will be 8 , as 2^3 is 8.

String Functions
len() : Returns length.
upper() : Converts to uppercase.
replace() : Replaces part of the string.

Trick Question:

Q: What will "hello".replace("l", "p") output?


Solution: heppo , as every occurrence of l is replaced with p .

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.

Preview of the Next Lecture: Primitive & Abstract Data


Structures
In the next lecture, we’ll discuss:

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:

The differences between primitive and abstract data structures.


How data structures help organize and manage data in programming.
How to use Python’s basic data types and structures effectively.
An introduction to the concept of abstract data structures and their importance.

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.

2. Key Concepts or Vocabulary


Primitive Data Structures: Basic data types provided by Python, like integers, floats, strings, and
booleans.
Abstract Data Structures (ADS): More complex data structures built on top of primitive types,
like lists, stacks, queues, dictionaries, and trees.
Mutable vs. Immutable: Mutable objects can be changed after creation (like lists), while
immutable objects cannot be modified (like strings and tuples).
Array: A data structure that stores elements in a contiguous block of memory (Python’s list is a
type of array).
Stack: A Last In, First Out (LIFO) data structure; think of a stack of books where you can only
access the top book.
Queue: A First In, First Out (FIFO) data structure, like a line of people waiting in a queue.
Dictionary: A data structure that holds key-value pairs, enabling efficient data retrieval based on
keys.
3. Real-World Examples
1. Primitive Data Structures: Think of primitive data types as the foundation of a building.
Numbers, characters, and booleans are like the bricks and beams used to construct everything
else.
2. Abstract Data Structures:
Lists: Consider a grocery list. You add items to it, and you may remove items as you buy
them. Python lists work similarly, allowing us to add, remove, or update elements.
Stacks: Imagine stacking plates in a cupboard. The last plate you place on the stack is the
first one you take off—a stack is exactly like this.
Queues: Picture standing in line at a coffee shop. The first person to enter the line is the first
to be served, just like how a queue functions.
Dictionaries: Think of a phone book where you look up a person’s phone number by their
name. Dictionaries work the same way; they allow us to retrieve values (like phone numbers)
by using keys (like names).

4. Mini Code Snippets

Primitive Data Types

# Integer (whole number)


age = 25 # Age of a person

# Float (decimal number)


height = 5.9 # Height in feet

# String (text)
name = "Alice" # Person's name

# Boolean (True/False)
is_student = True # Indicates if the person is a student
Abstract Data Structures
List

# A list of favorite fruits


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

# Adding an item to the list


fruits.append("orange") # fruits becomes ["apple", "banana", "cherry", "orange"]

# Accessing an item
print(fruits[1]) # Outputs "banana"

Stack (using a list)

# A simple stack of books


stack = []

# Adding books to the stack


stack.append("Book 1")
stack.append("Book 2")

# Removing the top book


top_book = stack.pop() # "Book 2" is removed

Queue (using a list with collections.deque for efficiency)

from collections import deque

# A queue of people
queue = deque(["Alice", "Bob", "Charlie"])

# Adding a person to the end of the queue


queue.append("David")

# Removing the person at the front of the queue


first_person = queue.popleft() # "Alice" is removed
Dictionary

# A dictionary of items with their prices


prices = {"apple": 0.5, "banana": 0.3, "cherry": 0.7}

# Accessing a price by item


print(prices["apple"]) # Outputs 0.5

5. Pre-Reading Questions or Simple Exercises


1. Identify Data Types: Look around your room and identify three objects. Try to classify these as
different data types. For example, “chair” could be a string, and the number of chairs could be an
integer.
2. Mini Coding Task: Write a list of three favorite movies and add a fourth movie to it. Print out the
updated list.
3. Explore Dictionaries: Think of two things you can categorize by a unique attribute, like “people
and their favorite colors.” Try creating a dictionary in Python where you assign each person a
favorite color.

6. Common Mistakes or Misconceptions


Confusing Lists and Arrays: In many programming languages, lists and arrays are distinct, but
in Python, the list type behaves similarly to arrays in other languages.
Misusing Mutable vs. Immutable Types: Beginners often try to modify immutable types, like
strings or tuples. Remember, you cannot change the contents of these objects directly—Python
will throw an error.
Using Wrong Data Structures: Sometimes students try to use a list as a stack or queue but
forget to follow LIFO/FIFO rules. Remember, stacks are LIFO, and queues are FIFO.
7. A Teaser for the Lecture
Why do some data structures let you access elements faster than others? And why is that speed
crucial for real-world applications? Tomorrow, we’ll dive deeper into how different data structures affect
the speed and efficiency of programs, and how to pick the right one for any coding task.

Looking forward to helping you build a solid foundation in Python data structures!
Lecture Notes: Primitive & Abstract Data Structures in
Python

1. Introduction to Data Structures


Definition: Data structures are methods used to store and organize data to facilitate efficient access
and modifications. Think of them as different types of "containers" for data, each suited for specific
tasks.

In Python, data structures are categorized into:

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.

2. Primitive Data Structures


Primitive data types in Python serve as the building blocks for more complex structures.

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?

Answer: Since True is treated as 1 , the output will be 101 .

3. Abstract Data Structures


Abstract data structures allow us to group multiple pieces of information together and manage them
effectively.

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"]

# Accessing elements by index


print(inventory[0]) # Output: apple

# Adding an item to the list


inventory.append("date")
print(inventory) # Output: ['apple', 'banana', 'cherry', 'date']

# 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)

# Accessing elements by index


print(coordinates[0]) # Output: 40.7128

# Attempting to modify a tuple will raise an error


# coordinates[0] = 50.0 # This line would raise an error as tuples are immutable
Trick Question 3
Question: Can you modify the first element of a tuple?

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"
}

# Accessing values by key


print(user_profile["name"]) # Output: Alice

# Adding a new key-value pair


user_profile["email"] = "alice@example.com"
print(user_profile)

# Removing a key-value pair


del user_profile["age"]
print(user_profile)

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

# Trying to add a duplicate element


unique_items.add("apple")
print(unique_items) # 'apple' will not be added again

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.

4. Choosing the Right Data Structure


Each data structure has its ideal use cases:

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).

Summary and Key Takeaways


Primitive Types: Simple data types - int , float , str , and bool .
Abstract Types: Complex data structures - list , tuple , dictionary , and set .
Selection Criteria: Choosing the right data structure depends on the nature of the data and what
you want to achieve.

Preview for Next Lecture: Lists & Strings, and Brute Force
Approach
In our next class, we’ll go into more detail about Lists & Strings:

List Manipulation: Sorting, slicing, and more.


String Manipulation: Using methods like .upper() , .replace() , etc.
Common Algorithms: Techniques for efficient data manipulation.
Complexity Analysis: Why efficiency matters.

We’ll also introduce the Brute Force Approach:

Definition: Trying all possible solutions to solve a problem.


Examples: Simple search algorithms and pattern matching.
Comparison with Optimized Approaches: When brute force works and when it’s better to avoid
it.
Pre-Class Reading: Advanced Lists & Strings Manipulation and
the Brute Force Approach in Python

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.

2. Key Concepts or Vocabulary


Indexing: The process of accessing an element in a list or string by its position (or index).
Indexing starts at 0 in Python.
Slicing: A technique to retrieve a portion of a list or string by specifying a range of indices. Slicing
can use a start, stop, and step to create subsets.
List Comprehensions: A Pythonic way to create lists quickly and concisely by specifying
expressions and conditions.
Brute Force Approach: A straightforward method for solving problems by exhaustively checking
all possibilities, often used when problem size is manageable.
Complexity Analysis: A way to measure the efficiency of algorithms, particularly how runtime or
memory requirements grow with input size.

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.

4. Mini Code Snippets


To help you understand these concepts, here are a few code snippets with explanations.

a. List Indexing and Slicing

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.

# List of exam scores


scores = [88, 92, 79, 93, 85]

# Access the second score


second_score = scores[1] # Output: 92

# Get a slice from the second to the fourth score


middle_scores = scores[1:4] # Output: [92, 79, 93]

# Negative indexing (get the last element)


last_score = scores[-1] # Output: 85

# Slice with a step (every other score)


alternate_scores = scores[::2] # Output: [88, 79, 85]

b. String Manipulation with Methods

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!"

# Find the starting index of 'coding'


coding_index = sentence.find("coding") # Output: 13

# Replace 'fun' with 'amazing'


new_sentence = sentence.replace("fun", "amazing") # Output: "Python makes coding amazing!"

# Split sentence into a list of words


words = sentence.split() # Output: ['Python', 'makes', 'coding', 'fun!']

c. List Comprehensions with Conditions

List comprehensions are a concise way to create lists. They’re powerful, especially when combined
with conditions.

# List of numbers from 1 to 10


numbers = list(range(1, 11))

# Create a list of squares of even numbers


even_squares = [x**2 for x in numbers if x % 2 == 0] # Output: [4, 16, 36, 64, 100]

d. Simple Brute Force Example

In this example, we use brute force to find a target number in a list by checking each element.

# List of random numbers


numbers = [12, 45, 23, 67, 34]
target = 67

# Brute force search for the target


for num in numbers:
if num == target:
print("Target found:", num) # Output: Target found: 67
break

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?

6. Common Mistakes or Misconceptions


Confusing Indices in Slicing: Beginners often confuse the start and end indices in slicing.
Remember that the end index is exclusive, so list[1:3] retrieves elements at positions 1 and 2,
not 3.
Misusing List Comprehensions: A common error in list comprehensions is forgetting the
condition or applying it incorrectly. For example, in [x for x in list if condition] , ensure the
condition is logical and relates to the variable x .
Brute Force Overuse: It’s tempting to use brute force due to its simplicity, but it’s rarely efficient
for large problems. Consider other algorithmic options, especially when dealing with vast data
sets.

7. A Deeper Dive into Brute Force Efficiency


To understand why the Brute Force approach can be problematic, let’s examine time complexity
briefly. If you’re using brute force on a problem with n elements, it might require checking each
element individually, resulting in a time complexity of O(n) or worse, depending on the operations
involved. For instance, searching for a combination lock code with three digits has a manageable
complexity, O(1000), but as the lock digits increase, the number of possibilities (10,000, 100,000,
etc.) makes brute force quickly impractical.
8. A Teaser for the Lecture
Imagine you’re faced with a list of millions of records, and you need to search for specific information.
How can you avoid the lengthy process of brute-force checking each record? Are there ways to
organize or search data that make this task faster? In today’s lecture, we’ll explore efficient methods
and strategies, introducing a few smart algorithms to speed up searching and other data-handling
tasks!

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:

Understand what complexity analysis is and its importance in coding.


Identify types of complexity—time and space—and understand their impact.
Use Big O notation to evaluate and compare algorithm efficiency.
Recognize common Big O notations: O(1), O(n), O(log n), and O(n²).
Balance time and space considerations for improved performance.

Key Concepts and Vocabulary


Understanding Complexity Analysis starts with the basics.

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.)

Real-World Examples of Complexity Types


O(1): Checking the latest email in your inbox.
O(n): Reading a book, page by page.
O(log n): Guessing a number by halving options each time (e.g., 1 to 100).
O(n²): Comparing each person to everyone else in a room to find a match.

Step-by-Step Explanation of Key Complexity Types

Constant Time Complexity (O(1))


Concept: Execution time remains constant, irrespective of input size.
Example:

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.

Linear Time Complexity (O(n))


Concept: Execution time grows proportionally with input size.
Example:

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.

Logarithmic Time Complexity (O(log n))


Concept: Execution time grows slower relative to input, commonly halving possible solutions each step.
Example:

def binary_search(sorted_lst, target):


low, high = 0, len(sorted_lst) - 1
while low <= high:
mid = (low + high) // 2
if sorted_lst[mid] == target:
return mid
elif sorted_lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

Explanation: Binary search narrows down by halves, like finding a word in the dictionary by starting in the middle.

Quadratic Time Complexity (O(n²))


Concept: Execution time grows rapidly due to nested loops.
Example:

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.

Pre-Reading Questions and Exercises


1. Identify Complexity
Analyze the following code for its time complexity:

def check_for_item(lst, item):


for i in lst:
if i == item:
return True
return False

Hint: Does it go through each item once or multiple times?


2. Predict Complexity in Real Life

Identify one task in your daily life that has constant time complexity (O(1)).
Identify one task where time grows with workload (O(n)).

3. Practice Writing a Linear Complexity Function


Write a function to sum all elements in a list. What is its time complexity?

Common Mistakes and Misconceptions


1. Big O Does Not Equal Runtime: Big O notation indicates growth rate, not exact time.
2. Confusing Constant and Linear Complexity: Fast doesn’t mean constant (O(1)). A quick loop is still linear (O(n)).
3. Assuming More Code Equals Higher Complexity: A single nested loop causes quadratic complexity (O(n²)), while extensive single-
step code may remain constant (O(1)).
Time and Space Complexity Analysis: How Fast or Slow Can
Code Be?

Introduction to Complexity Analysis


Complexity analysis is like a "fitness test" for your code. It tells you how efficiently your program performs as the size of its input grows.
This helps ensure that your code can handle large datasets effectively.

Why Complexity Analysis Matters


Imagine planning tasks for a large group. If everything is organized, tasks get done faster, with fewer mistakes. But if there’s no plan, time
is wasted, tasks overlap, and errors multiply. Complexity analysis brings order and predictability to code performance, especially for large
data.

Types of Complexity

Complexity Type Notation Example Scenario

Constant O(1) Accessing an element in an array

Linear O(n) Looping through a list

Quadratic O(n²) Nested loops comparing all pairs

Logarithmic O(log n) Binary search on a sorted list


1. Time Complexity
Measures how long it takes for a program to finish based on input size.

2. Space Complexity
Measures how much memory a program uses as it runs.

Big O Notation: A Special Language for Complexity


Big O notation describes the worst-case scenario of time and space complexity, giving a high-level overview of your program’s efficiency.
Think of it as emojis for speed:

O(1) - Constant Time: Always takes the same time


O(n) - Linear Time: Takes longer with more data
O(n²) - Quadratic Time: Takes even longer as data grows

Common Big O Notations with Examples

1. Constant Time - O(1)


No matter the size of the data, the program always takes the same amount of time.

# Example of O(1)
def get_first_item(lst):
return lst[0] # Accessing the first item takes constant time

Real-life Analogy: Grabbing the first book on a shelf.


2. Linear Time - O(n)
Time taken grows linearly with the amount of data.

# Example of O(n)
def print_all_items(lst):
for item in lst:
print(item) # Goes through each item once

Real-life Analogy: Reading each page in a book one by one.

3. Quadratic Time - O(n²)


The time taken grows significantly as the data size increases, often due to nested loops.

# 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

Real-life Analogy: Comparing every sock in a drawer to find matching pairs.

4. Logarithmic Time - O(log n)


The time taken grows slowly, usually by halving the data each step.

# 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

Real-life Analogy: Guessing a number by halving the range each time.

Key Points to Remember


Time Complexity measures how long code takes to run.
Space Complexity measures how much memory code uses.
Big O Notation represents the worst-case scenario.
Constant complexity (O(1)) is the most efficient.

Trick Questions on Big O Notation


1. Question: What’s the time complexity of accessing an element by index in a list?
Answer: O(1) – Accessing an index in a list is constant time.

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?

1. Constant Space - O(1)


Memory usage doesn’t change with more data.

# Example of O(1)
def add_two_numbers(a, b):
return a + b # Only needs space for 'a' and 'b'

2. Linear Space - O(n)


Memory usage grows with the input size.

# Example of O(n)
def create_list_of_zeros(n):
return [0] * n # Uses memory for 'n' zeros

3. Quadratic Space - O(n²)


Memory grows significantly as data size increases.

# Example of O(n^2)
def create_matrix(n):
return [[0] * n for _ in range(n)] # Creates an n x n matrix

At a Glance: Complexity Types


Notation Example Code Real-Life Analogy Typical Use Cases

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

Trick Questions on Space Complexity


1. Question: If a function only uses a single variable, what is its space complexity?
Answer: O(1) – Space is constant as it doesn’t depend on input size.

2. Question: What’s the space complexity of creating a new list of n elements?


Answer: O(n) – The list grows with each additional item.

Time vs. Space Trade-Offs


Balancing time and space is essential in coding:

Faster code may need more memory.


Code that saves memory might run slower.

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)

Answer: O(n) because it checks each element once.

Real-World Relevance of Complexity Analysis


In real-world applications, complexity analysis helps ensure that a program designed for a small dataset can still perform efficiently with
large datasets, like handling millions of users on social media or performing fast searches on a search engine.

Preview for the Next Lecture: Input Handling in Python


In the next session, we’ll explore **how to take user input in

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!

1. Hey There! Ready to Learn?


By the end of our session, you'll be able to:

Use the input() function in Python to chat with your users.


Convert those inputs into numbers or other data types you need.
Handle multiple inputs smoothly and catch any input hiccups.
Refresh your memory on functions—parameters, return values, and all that good stuff.

2. Key Concepts We're Going to Explore


Let's get familiar with some key ideas:

Concept What's It All About?

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?

Parameter Variables that you define in a function to receive data.

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:

Name: So you can greet them personally.


Age: To check if they're eligible.
Programming Experience: To suggest the right courses.

Depending on what they tell you, you can recommend beginner resources or advanced sessions. Pretty cool, right?

4. Let's Look at Some Code Together

Getting to Know Your User

# Let's ask for the user's name


name = input("What's your name? ")
print(f"Hello, {name}! Great to meet you.")

What's Happening Here?

We're using input() to ask the user for their name.


Then, we're greeting them using an f-string for easy formatting.
Turning Strings into Numbers

# Asking for age and converting it


age = int(input("How old are you? "))
print(f"Wow, you're {age} years young!")

Why Convert?

The input() function always gives us a string.


We use int() to turn that string into an integer so we can do math with it later if we want.

Handling Multiple Pieces of Info

# Getting multiple inputs at once


first_name, city = input("Enter your first name and your city, separated by a space: ").split()
print(f"Nice to meet you, {first_name} from {city}!")

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!

Being Prepared for Surprises

# Safely asking for a number


try:
age = int(input("Enter your age: "))
print(f"Next year, you'll be {age + 1}!")
except ValueError:
print("Hmm, that doesn't look like a number. Please try again.")

What's Going On?

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.

Creating Useful Functions

def greet_user(name):
"""Greets the user with their name."""
return f"Hello, {name}! Welcome aboard."

# Using our function


user_name = input("What's your name? ")
print(greet_user(user_name))

Function Fun:

We define a function called greet_user that takes a name parameter.


The function returns a greeting string.
We then call the function with the user's input.

5. Give It a Try!
Why not try these exercises yourself?

1. What's Your Favorite Color?


Use input() to ask the user for their favorite color.
Print a message that includes their color.

2. Calculating Age

Ask the user what year they were born.


Convert that input to an integer.
Calculate their age assuming the current year is 2023.
Tell them how old they are.

3. Full Name Greeting

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

Think of a function that calculates the area of a rectangle.


What information do you need? (Hint: Length and width)
Write the function and use it to calculate an area based on user input.

Sample Solution for Exercise 4:

def calculate_area(length, width):


"""Calculates the area of a rectangle."""
return length * width

# Get user input


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

# Calculate and display the area


area = calculate_area(length, width)
print(f"The area of your rectangle is {area} square units.")

6. Watch Out for These Common Mistakes


Even the best of us run into these hiccups. Here's how to avoid them:

Forgetting to Convert Types

The Issue: Trying to do math with strings.


Example:

age = input("Enter your age: ")


print(age + 5) # This will cause an error!

Fix It: Convert age to an integer first.

age = int(input("Enter your age: "))


print(age + 5)

Misusing split()

The Issue: Not getting the number of inputs you expect.


Example:

first_name, last_name = input("Enter your full name: ").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)}!")

Ignoring Potential Errors

The Issue: Program crashes when unexpected input is given.


Example: Not using try-except when converting inputs.
Fix It: Always use exception handling when you're dealing with user input.

7. Can't Wait to Show You More!


Imagine building a program that not only takes in user data but responds intelligently, perhaps even learning from the inputs! In our
upcoming class, we'll dive deeper into making our programs interactive and robust. You'll be crafting code that feels almost conversational.
Excited? I know I am!

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

Introduction to Input Taking


Hey there! Ever wanted a program to actually listen to you? That’s where input handling comes in. Input taking allows Python programs to
gather information from users, making them interactive and responsive. Imagine logging into your favorite app, setting up a reminder, or even
playing a game—all these involve input from you. Let’s dive into how Python makes it easy to gather and handle user input!

1. The input() Function


The input() function is the simplest way to ask for user input in Python. It’s like saying, “Hey, what’s your name?” and waiting for a response.

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.

2. Type Conversion for Input Values


What if you need numbers instead of text? That’s where type conversion comes in! Input is always a string, but we can convert it to a number
(like an integer or float) if needed.

Common Type Conversions:


int() converts input to an integer (whole number).
float() converts input to a decimal number.
bool() converts input to a boolean (True/False).

Example:

age = int(input("Enter your age: ")) # Converts input to integer


height = float(input("Enter your height in meters: ")) # Converts to float

print(f"Age: {age}, Height: {height}")

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!

3. Handling Invalid Input with Try-Except


What happens if a user enters letters instead of numbers? That’s where try-except blocks come to the rescue! With try-except , Python can
handle errors gracefully, preventing crashes and giving helpful messages.

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!

Why Use Try-Except?

Avoids Crashes – Keeps the program running smoothly.


Friendly Error Messages – Gives users feedback when something goes wrong.

4. Taking Multiple Inputs in One Line


Sometimes, you want multiple pieces of information in one go, like a name and age. You can use input().split() to take multiple inputs in a single
line, separated by spaces.

Syntax: input("Prompt here").split()


Returns: A list of strings that can be converted if needed.

Example:

name, age = input("Enter your name and age: ").split() # Splits input by space
age = int(age) # Convert age to integer

print(f"Name: {name}, Age: {age}")

If the user enters Alice 25 , name will be "Alice" and age will be 25 . Simple and efficient!

Input Handling Methods Comparison


Concept Description Example Use Cases

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()

Takes multiple inputs in one Collecting multiple inputs (name, age,


input().split() name, age = input().split()
line etc.)

try: age = int(input())


try-except for input Handles invalid input errors User-friendly input validation
except:

Key Points to Remember


input() always returns a string.

Use int() , float() , or bool() to convert types as needed.


try-except blocks help handle invalid input gracefully.

input().split() is perfect for multiple inputs in one line.

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.

At a Glance - Quick Reference


input() Basics: Pauses and waits for user input, always returns a string.

Type Conversion: int() , float() , and bool() for non-string values.


Error Handling: try-except to handle invalid input gracefully.
Multiple Inputs: Use input().split() to gather more than one input in a single line.

Practice Exercise: Simple Calculator


Let’s apply what you’ve learned! Create a calculator that takes two numbers and an operator ( + , - , * , / ) and performs the calculation.

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!

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