Phython Becomes Easier .
Phython Becomes Easier .
1. What is Python?
Python is a high-level, interpreted programming language known for its
simplicity and readability. It allows developers to write clear programs for both
small and large-scale projects. Python is used for:
• Web development (e.g., Django, Flask)
• Data Science and Machine Learning (e.g., Pandas, TensorFlow)
• Automation (e.g., scripting tasks)
• Software development and more.
4. Arithmetic Operators
Python supports basic arithmetic operations like addition, subtraction,
multiplication, division, and more.
Common Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• // (Floor Division)
• % (Modulus)
• ** (Exponentiation)
Examples:
a = 10
b=3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333...
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a ** b) # Output: 1000 (Exponentiation)
6. Variable Reassignment
You can change the value of a variable at any point in your program.
Example:
x=5
print(x) # Output: 5
x = 10
print(x) # Output: 10
Input and Output in Python
1.1 Input from the User:
In Python, we use the input() function to take input from the user. The data
entered by the user is always received as a string, so if you want to use it as a
different data type (e.g., integer or float), you'll need to convert it using type
conversion functions like int() or float().
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert input to integer
1.2 Output to the Console:
The print() function is used to display output to the console. You can use it to
display text, variables, or results of expressions.
print("Hello, " + name + "! You are " + str(age) + " years old.")
You can also use f-strings (formatted string literals) for more readable code:
print(f"Hello, {name}! You are {age} years old.")
2. String Manipulation
Strings are sequences of characters. Python provides many useful methods to
manipulate strings.
2.1 Common String Operations:
• Concatenation: Joining two or more strings together using the + operator.
• first_name = "John"
• last_name = "Doe"
• full_name = first_name + " " + last_name
print(full_name) # Output: "John Doe"
• Repetition: Repeating a string multiple times using the * operator.
• greeting = "Hello! " * 3
print(greeting) # Output: "Hello! Hello! Hello! "
2.2 String Methods:
• upper(): Converts a string to uppercase.
• lower(): Converts a string to lowercase.
• strip(): Removes leading and trailing spaces from a string.
• replace(old, new): Replaces a substring with another string.
message = " Hello, World! "
print(message.strip()) # Output: "Hello, World!"
print(message.upper()) # Output: "HELLO, WORLD!"
print(message.replace("World", "Python")) # Output: "Hello, Python!"
4. Escape Sequences
Escape sequences are special characters in strings that start with a backslash
(\). They are used to represent certain special characters.
Some commonly used escape sequences:
• \n: New line
• \t: Tab space
• \\: Backslash
Example:
print("Hello\nWorld") # Output:
# Hello
# World
print("Hello\tPython") # Output: Hello Python
Homework
1. Simple Greeting Program: Write a Python program that asks the user for
their name and age, then prints a personalized greeting message. Use both
the + operator and f-strings for output.
Example:
Enter your name: Alice
Enter your age: 25
Output: Hello, Alice! You are 25 years old.
2. String Manipulation Exercise: Write a Python program that:
o Takes a sentence as input from the user.
o Prints the sentence in all uppercase and lowercase.
o Replaces all spaces with underscores.
o Removes leading and trailing whitespace.
Example:
Input: " Python is awesome! "
Output:
Uppercase: "PYTHON IS AWESOME!"
Lowercase: "python is awesome!"
Replaced: "___Python_is_awesome!___"
Stripped: "Python is awesome!"
3. Character Counter: Write a Python program that:
o Asks the user for a string.
o Prints how many characters are in the string, excluding spaces.
Example:
Input: "Hello World"
Output: "Number of characters (excluding spaces): 10"
4. Escape Sequence Practice: Write a Python program that uses escape
sequences to print the following output:
Example:
Hello
World
This is a backslash: \
Assignment Operators
Assignment operators are used to assign values to variables. The simplest one
is = which assigns the value on the right to the variable on the left. There are also
compound assignment operators that combine arithmetic operations with
assignment.
Common Assignment Operators:
• =: Assigns value on the right to the variable on the left.
• +=: Adds right operand to the left operand and assigns the result to the
left operand.
• -=: Subtracts the right operand from the left operand and assigns the result
to the left operand.
• *=: Multiplies the left operand by the right operand and assigns the result
to the left operand.
• /=: Divides the left operand by the right operand and assigns the result to
the left operand.
• %=: Takes modulus of left operand by right operand and assigns the result
to the left operand.
Examples:
x = 5 # Assigns 5 to x
x += 3 # Equivalent to x = x + 3, now x is 8
x -= 2 # Equivalent to x = x - 2, now x is 6
x *= 4 # Equivalent to x = x * 4, now x is 24
x /= 6 # Equivalent to x = x / 6, now x is 4.0
2. Comparison Operators
Comparison operators are used to compare two values. They return
either True or False depending on the condition.
Common Comparison Operators:
• ==: Checks if two values are equal.
• !=: Checks if two values are not equal.
• >: Checks if the left operand is greater than the right operand.
• <: Checks if the left operand is less than the right operand.
• >=: Checks if the left operand is greater than or equal to the right operand.
• <=: Checks if the left operand is less than or equal to the right operand.
Examples:
a = 10
b = 20
3. Logical Operators
Logical operators are used to combine conditional statements. They evaluate
expressions and return either True or False.
Common Logical Operators:
• and: Returns True if both conditions are true.
• or: Returns True if at least one condition is true.
• not: Reverses the logical state of its operand (True becomes False, and vice
versa).
Examples:
x=5
y = 10
z = 15
# and operator
print(x > 0 and y > 5) # Output: True (both conditions are True)
# or operator
print(x > 10 or z > 10) # Output: True (one of the conditions is True)
# not operator
print(not(x > 10)) # Output: True (reverses False to True)
4. Membership Operators
Membership operators test for membership within a sequence, such as a list,
string, or tuple. They return True or False based on whether the value is found in
the sequence.
Membership Operators:
• in: Returns True if the specified value is found in the sequence.
• not in: Returns True if the specified value is not found in the sequence.
Examples:
my_list = [1, 2, 3, 4, 5]
my_string = "Python"
5. Bitwise Operators
Bitwise operators perform operations on binary representations of integers.
These operators are useful for low-level programming tasks like working with bits
and bytes.
Common Bitwise Operators:
• &: Bitwise AND (sets each bit to 1 if both bits are 1).
• |: Bitwise OR (sets each bit to 1 if one of the bits is 1).
• ^: Bitwise XOR (sets each bit to 1 if only one of the bits is 1).
• ~: Bitwise NOT (inverts all the bits).
• <<: Left shift (shifts bits to the left by a specified number of positions).
• >>: Right shift (shifts bits to the right by a specified number of positions).
Examples:
a = 5 # In binary: 101
b = 3 # In binary: 011
# Bitwise AND
print(a & b) # Output: 1 (binary: 001)
# Bitwise OR
print(a | b) # Output: 7 (binary: 111)
# Bitwise XOR
print(a ^ b) # Output: 6 (binary: 110)
# Bitwise NOT
print(~a) # Output: -6 (inverts all bits)
# Left shift
print(a << 1) # Output: 10 (binary: 1010)
# Right shift
print(a >> 1) # Output: 2 (binary: 010)
6. Arithmetic Operators
Python supports basic arithmetic operations like addition, subtraction,
multiplication, division, and more.
Common Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• // (Floor Division)
• % (Modulus)
• ** (Exponentiation)
Examples:
a = 10
b=3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333...
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a ** b) # Output: 1000 (Exponentiation)
Homework
1. Logical Operator Practice: Write a Python program that takes two
numbers as input from the user and checks if:
o Both numbers are greater than 10 (using and).
o At least one of the numbers is less than 5 (using or).
o The first number is not greater than the second (using not).
2. Comparison Operator Challenge: Create a Python program that asks the
user for their age and prints:
o "You are an adult" if the age is greater than or equal to 18.
o "You are a minor" if the age is less than 18.
o Use >= and < comparison operators.
3. Membership Operator Exercise: Write a Python program that:
o Takes a string as input from the user.
o Checks if the letter 'a' is in the string (using in).
o Checks if the string doesn't contain the word "Python" (using not
in).
4. Bitwise Operator Task: Given two integers, write a Python program that:
o Prints the result of a & b, a | b, and a ^ b.
o Shifts the bits of a two positions to the left (a << 2).
o Shifts the bits of b one position to the right (b >> 1).
1. What is a List?
A list is a collection of items that are ordered, mutable (changeable), and allow
duplicate elements. Lists can hold items of different data types, such as integers,
strings, or even other lists.
Syntax:
my_list = [element1, element2, element3, ...]
Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["apple", 3, True]
3. Modifying Lists
Lists are mutable, which means you can change the value of items in a list.
Changing a specific element:
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
Adding elements:
• append(): Adds an element to the end of the list.
• fruits.append("grape")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape']
• insert(): Inserts an element at a specific index.
• fruits.insert(1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry']
Removing elements:
• remove(): Removes the first occurrence of an element.
• fruits.remove("orange")
print(fruits) # Output: ['apple', 'kiwi', 'cherry']
• pop(): Removes the element at a specific index (or the last item if no index
is provided).
• fruits.pop() # Removes the last item
• print(fruits) # Output: ['apple', 'kiwi']
•
4. Slicing Lists
You can extract a portion of a list using slicing.
Syntax:
list_name[start:stop:step]
• start: The index to start the slice (inclusive).
• stop: The index to stop the slice (exclusive).
• step: The number of steps to skip elements (default is 1).
Examples:
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # Output: [1, 2, 3] (from index 1 to 3)
print(numbers[:4]) # Output: [0, 1, 2, 3] (from start to index 3)
print(numbers[2:]) # Output: [2, 3, 4, 5, 6] (from index 2 to end)
print(numbers[::2]) # Output: [0, 2, 4, 6] (every 2nd element)
6. Nested Lists
Lists can contain other lists, allowing you to create nested lists. This can be
useful for storing matrix-like data structures.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Homework
1. List Manipulation Exercise:
o Create a list of 5 items (strings or numbers).
o Add a new item to the end of the list and another at the second
position.
o Remove the third item from the list.
o Print the list after each operation.
2. Reverse and Sort a List: Create a list of numbers and:
o Sort it in descending order.
o Reverse the sorted list and print it.
1. Tuples in Python
A tuple is a collection of items that is ordered and immutable (unchangeable).
Tuples are similar to lists, but once a tuple is created, you cannot modify it. They
are often used to group related data together.
Syntax:
my_tuple = (element1, element2, element3, ...)
Example:
my_tuple = ("apple", "banana", "cherry")
numbers_tuple = (1, 2, 3, 4)
Creating a Tuple with One Element:
To create a tuple with only one element, include a trailing comma:
single_element_tuple = ("apple",)
3. Tuple Operations
Although tuples are immutable, you can perform various operations with them.
Tuple Concatenation:
You can combine two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
Tuple Repetition:
You can repeat a tuple multiple times using the * operator.
repeated_tuple = (1, 2) * 3
print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2)
Checking Membership:
You can check if an item exists in a tuple using the in operator.
print("apple" in fruits) # Output: True
4. Tuple Methods
Though tuples are immutable, Python provides some built-in methods for working
with tuples.
• count(): Returns the number of times an element appears in the tuple.
• my_tuple = (1, 2, 3, 1, 1)
print(my_tuple.count(1)) # Output: 3
• index(): Returns the index of the first occurrence of an element.
• my_tuple = ("apple", "banana", "cherry")
print(my_tuple.index("banana")) # Output: 1
6. Sets in Python
A set is a collection of unique items that is unordered and unindexed. Sets do
not allow duplicate values. Sets are useful for performing operations like union,
intersection, and difference.
Syntax:
my_set = {element1, element2, element3, ...}
Example:
fruits_set = {"apple", "banana", "cherry"}
numbers_set = {1, 2, 3, 4, 5}
Empty Set:
To create an empty set, use the set() function (not {}, which creates an empty
dictionary).
empty_set = set()
7. Set Operations
Sets support mathematical operations like union, intersection, and difference.
Union:
The union of two sets combines all elements from both sets, removing duplicates.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # Output: {1, 2, 3, 4, 5}
Intersection:
The intersection of two sets returns elements that are common to both sets.
intersection_set = set1 & set2 # Output: {3}
Difference:
The difference between two sets returns elements that are in the first set but not
in the second.
difference_set = set1 - set2 # Output: {1, 2}
Symmetric Difference:
The symmetric difference returns elements that are in either of the sets but not
in both.
sym_diff_set = set1 ^ set2 # Output: {1, 2, 4, 5}
8. Set Methods
Sets come with several useful methods for performing common tasks.
• add(): Adds an element to the set.
• fruits_set.add("orange")
print(fruits_set) # Output: {'apple', 'banana', 'cherry', 'orange'}
• remove(): Removes a specified element from the set. Raises an error if the
element does not exist.
• fruits_set.remove("banana")
print(fruits_set) # Output: {'apple', 'cherry'}
• discard(): Removes a specified element without raising an error if it does
not exist.
fruits_set.discard("banana") # No error if "banana" is not in the set
• pop(): Removes a random element from the set.
fruits_set.pop()
• clear(): Removes all elements from the set.
fruits_set.clear()
9. Differences Between Lists, Tuples, and Sets
Feature List Tuple Set
Ordering Ordered Ordered Unordered
Mutability Mutable Immutable Mutable
Duplicates Allows duplicates Allows duplicates No duplicates
Indexing Supports indexing Supports indexing No indexing
Operations List operations Tuple operations Set operations
Common Uses General collection Fixed data Unique items
Homework
1. Tuple Operations:
o Create a tuple with 5 elements.
o Try to modify one of the elements. What happens?
o Perform slicing on the tuple to extract the second and third
elements.
o Concatenate the tuple with another tuple.
2. Set Operations:
o Create two sets: one with your favorite fruits and another with your
friend’s favorite fruits.
o Find the union, intersection, and difference between the two sets.
o Add a new fruit to your set.
o Remove a fruit from your set using both remove() and discard().
What happens when the fruit doesn’t exist?
3. Tuple and Set Comparison:
o Create a list of elements and convert it into both a tuple and a set.
o Print both the tuple and the set.
o Try to add new elements to the tuple and set. What differences do
you observe?
Dictionaries in Python
A dictionary in Python is a collection of key-value pairs. Each key in a dictionary
is associated with a value, and you can retrieve or manipulate data using the
key. Unlike lists and tuples, dictionaries
are unordered and mutable (changeable).
1. Creating a Dictionary
You can create a dictionary using curly braces {} or the dict() function.
Syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Example:
Let's create a dictionary of famous cities in Karnataka and their popular dishes.
karnataka_food = {
"Bengaluru": "Bisi Bele Bath",
"Mysuru": "Mysore Pak",
"Mangaluru": "Neer Dosa"
}
2. Accessing Dictionary Elements
To access the values stored in a dictionary, you use the key.
Example:
print(karnataka_food["Mysuru"]) # Output: Mysore Pak
You can also use the get() method to access values, which is safer because it
doesn’t throw an error if the key doesn’t exist.
print(karnataka_food.get("Mangaluru")) # Output: Neer Dosa
print(karnataka_food.get("Shivamogga", "Not Found")) # Output: Not Found
6. Dictionary Characteristics
• Unordered: Dictionary keys are not stored in any particular order.
• Mutable: You can change, add, or remove items.
• Keys Must Be Immutable: Keys in a dictionary must be of a data type
that is immutable, such as a string, number, or tuple.
• Unique Keys: A dictionary cannot have duplicate keys. If you try to add a
duplicate key, the latest value will overwrite the previous one.
7. Differences Between Lists, Tuples, Sets, and Dictionaries
Feature List Tuple Set Dictionary
Ordering Ordered Ordered Unordered Unordered
Mutability Mutable Immutable Mutable Mutable
Duplicates Allows Allows No duplicates Keys: No
duplicates duplicates duplicates
Indexing Supports Supports No indexing Uses keys
indexing indexing
Structure Indexed Indexed Unordered Key-value
collection collection collection pairs
Homework
1. Basic Dictionary Operations:
o Create a dictionary to store information about 5 cities in Karnataka
and their famous dishes.
o Add a new city and its dish to the dictionary.
o Update the dish for Bengaluru.
o Remove one city from the dictionary.
o Use the keys() method to print all city names in the dictionary.
o Use the values() method to print all dishes in the dictionary.
2. Nested Dictionary Practice (Simple for now):
o Create a dictionary to store details of two of your friends, including
their names, favorite subject, and favorite food.
o Access and print the favorite food of one friend.
Conditional Statements in Python: if, elif, and else
In programming, conditional statements are used to perform different actions
based on different conditions. Python uses if, elif, and else statements to allow
your program to make decisions.
1. The if Statement
The if statement is used to test a condition. If the condition is True, the block of
code under the if statement is executed.
Syntax:
if condition:
# Code block to execute if the condition is True
Example:
Let's say you want to check if it's time for dinner (assuming dinner time is 8
PM).
time = 20 # 20 represents 8 PM in 24-hour format
if time == 20:
print("It's time for dinner!")
Here, the program checks if the variable time is equal to 20 (8 PM). If it's 20, the
message "It's time for dinner!" is printed.
if time == 8:
print("It's breakfast time!")
elif time == 13:
print("It's lunch time!")
elif time == 20:
print("It's dinner time!")
else:
print("It's not a meal time.")
Here, the program checks multiple conditions:
• If the time is 8 AM, it prints "It's breakfast time!".
• If the time is 1 PM, it prints "It's lunch time!".
• If the time is 8 PM, it prints "It's dinner time!".
• If none of these conditions are true, it prints "It's not a meal time."
4. Comparison Operators in if Statements
You can use comparison operators to compare values in if statements:
• ==: Equal to
• !=: Not equal to
• <: Less than
• >: Greater than
• <=: Less than or equal to
• >=: Greater than or equal to
Example:
Let’s check if someone is eligible to vote in Karnataka (minimum age for voting
is 18).
age = 19
if age < 5:
print("Ticket is free.")
elif age <= 12:
print("You get a child discount.")
elif age >= 60:
print("You get a senior citizen discount.")
else:
print("You pay the full fare.")
In this example:
• If the passenger is younger than 5 years, the output is "Ticket is free."
• If they are 5 to 12 years old, it prints "You get a child discount."
• If they are 60 or older, it prints "You get a senior citizen discount."
• For all other ages, it prints "You pay the full fare."
7. Nested if Statements
You can also use if statements inside other if statements. This is called nesting.
Example:
Let’s say you’re planning to visit Mysuru. You want to decide whether to go based
on the day of the week and the weather.
day = "Saturday"
is_raining = False
8. Indentation in Python
Python uses indentation (spaces at the beginning of a line) to define blocks of
code. The indented code after an if, elif, or else statement belongs to that
condition. Make sure to use consistent indentation to avoid errors.
Example:
age = 19
Output:
Sheep 1
Sheep 2
Sheep 3
Sheep 4
Sheep 5
That's enough counting!
if booking == "yes":
available_seats -= 1
print("Seat booked!")
else:
print("No booking made.")
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
...
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Here, the outer loop controls the first number (i), and the inner loop controls the
second number (j). Together, they generate the multiplication table.
Homework
1. Multiples of 3:
o Write a for loop that prints all multiples of 3 between 1 and 30.
2. Sum of First 10 Numbers:
o Write a program using a for loop that calculates the sum of numbers
from 1 to 10.
3. Print Your Name Letter by Letter:
o Write a program that takes your name as input and prints each
letter of your name using a for loop.
4. Count Vowels in a String:
o Write a program that counts how many vowels are in a given string
using a for loop.
Lists and Dictionaries with For Loops, List Comprehension, and Dictionary
Comprehension
In this video, we will learn how to use for loops with Lists and Dictionaries,
followed by advanced techniques using List Comprehension and Dictionary
Comprehension. These tools are essential for writing concise and efficient Python
code.
student_marks = {}
for i in range(len(students)):
student_marks[students[i]] = marks[i]
print(student_marks)
Output:
{'Anand': 85, 'Geetha': 90, 'Kumar': 78}
4. List Comprehension
List comprehension provides a more concise way to create lists by applying an
expression to each element in an existing list.
Syntax:
new_list = [expression for item in iterable if condition]
Example 1: Squaring numbers in a list
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Example 2: Filtering even numbers
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
Example 3: Uppercasing Kannada city names
cities = ["Bengaluru", "Mysuru", "Hubballi", "Mangaluru"]
uppercased_cities = [city.upper() for city in cities]
print(uppercased_cities)
Output:
['BENGALURU', 'MYSURU', 'HUBBALLI', 'MANGALURU']
5. Dictionary Comprehension
Similar to list comprehension, dictionary comprehension provides a concise way
to create dictionaries.
Syntax:
new_dict = {key_expression: value_expression for item in iterable if condition}
Example 1: Creating a dictionary of squares
numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num ** 2 for num in numbers}
print(squares_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2: Converting a list of names to a dictionary of name lengths
names = ["Anand", "Geetha", "Kumar"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
Output:
{'Anand': 5, 'Geetha': 6, 'Kumar': 5}
Example 3: Filtering cities with population above 10 lakhs (Localized
Example)
city_population = {
"Bengaluru": 84,
"Mysuru": 11,
"Hubballi": 9,
"Mangaluru": 5
}
large_cities = {city: population for city, population in city_population.items() if
population > 10}
print(large_cities)
Output:
{'Bengaluru': 84, 'Mysuru': 11}
Practical Application
You can use the split() method when reading data from a text file or processing
input from a user where the data is separated by spaces, commas, or any other
delimiters. Once you split the data, you can work with it as a list, applying any
list manipulation techniques you've learned.
Homework
1. List Manipulation:
o Create a list of Kannada foods. Use list comprehension to create a
new list where each food name is in uppercase.
2. Sum of Prices:
o Create a dictionary of 5 items with their prices. Write a program
that calculates the total price of all items using a for loop.
3. List of Squares:
o Create a list of numbers from 1 to 10. Use list comprehension to
generate a list of their squares.
4. Student Data Task:
o Create a list of 3 dictionaries, where each dictionary contains the
name, age, and marks of a student. Loop through the list and print
each student's information.
5. Dictionary Comprehension:
o Create a dictionary where the keys are Kannada cities, and the
values are their populations. Use dictionary comprehension to filter
out cities with populations below 10 lakhs.
6. Nested List Challenge: Write a Python program that takes a list of lists
(a 2D list) as input and:
o Prints the entire matrix row by row.
o Prints the sum of each row in the matrix.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
FUNCTIONS
1. Basics of Functions
A function is a reusable block of code that performs a specific task when called.
Functions are useful to organize code, make it reusable, and reduce redundancy.
2. Defining a Function
You define a function using the def keyword followed by the function name,
parentheses, and a colon :.
Syntax:
def function_name(parameters):
# Block of code
Example: Basic function to greet a user
def greet():
print("Hello! Welcome to the Python course.")
greet()
Output:
Hello! Welcome to the Python course.
3. Function Parameters
Parameters are variables used to pass data into a function.
Example: Function with a parameter
def greet_user(name):
print(f"Hello, {name}! Welcome to the Python course.")
greet_user("Anand")
Output:
Hello, Anand! Welcome to the Python course.
def greet():
name = "Local Name"
print(name)
Homework:
1. Greet Function: Write a function greet() that takes no arguments and
prints a greeting message.
2. Parameterized Greet: Write a function greet_user() that takes a name as
input and prints a custom greeting.
3. Sum Function: Write a function add_numbers(a, b) that returns the sum
of two numbers. Call this function with different values.
Functions - Advanced Concepts
In this part, we'll explore more advanced function concepts, including recursion,
lambda functions, and variable-length arguments.
1. Keyword Arguments
With keyword arguments, you can pass values to a function by specifying the
parameter names.
Example:
def display_info(name, age):
print(f"Name: {name}, Age: {age}")
display_info(age=25, name="Kumar")
Output:
Name: Kumar, Age: 25
2. Variable-Length Arguments
You can use *args and **kwargs to accept a variable number of arguments in a
function.
Example: Using *args
def total_sum(*numbers):
result = 0
for num in numbers:
result += num
return result
print(total_sum(1, 2, 3, 4))
Output:
10
Example: Using **kwargs
def student_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
3. Lambda Functions
A lambda function is a small anonymous function that can take any number of
arguments but has only one expression.
Syntax:
lambda arguments: expression
Example: Lambda function to double a number
double = lambda x: x * 2
print(double(5))
Output:
10
4. Recursion
Recursion occurs when a function calls itself. It's used to solve problems that can
be broken down into smaller, similar problems.
Example: Recursive function to calculate factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Here are the sections for Nested Functions and Local/Global Variables:
5. Nested Functions
A nested function is a function defined inside another function. The inner
function is only accessible within the outer function, allowing for more modular
and controlled code execution.
Example: Nested function in Python
def outer_function(name):
def inner_function():
print(f"Hello, {name}!")
inner_function()
outer_function("Anand")
Output:
Hello, Anand!
In this example, the inner_function() is called within outer_function() and uses
the name parameter of the outer function.
Homework:
1. Lambda Function: Write a lambda function that multiplies two numbers.
2. Recursive Function: Write a recursive function that calculates the sum of
the first n numbers.
3. Variable-Length Arguments: Write a function that accepts any number
of arguments and returns their average.
# Method
def display_info(self):
print(f"Car Brand: {self.brand}, Model: {self.model}")
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating objects
person1 = Person("Arjun", 30)
person2 = Person("Megha", 25)
person1.greet()
person2.greet()
Output:
Hello, my name is Arjun and I am 30 years old.
Hello, my name is Megha and I am 25 years old.
In this example:
• The Person class defines two attributes: name and age.
• The method greet() prints a greeting message using these attributes.
def bark(self):
print(f"{self.name} is barking!")
dog1.bark()
dog2.bark()
Output:
Rex is barking!
Bolt is barking!
Here:
• dog1 and dog2 are different objects of the Dog class, each with its
own name and breed.
5. Homework
1. Create a Class:
o Write a class Mobile with attributes brand and price.
o Create two objects of the class and display their attributes using a
method.
2. Method Definition:
o Define a class Student with attributes name and marks.
o Write a method display_info() that prints the student's name and
marks.
o Create multiple objects of the Student class and call the method on
each.
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
# Creating an object
person1 = Person("Arjun", 22)
person1.introduce()
Output:
My name is Arjun and I am 22 years old.
Here:
• self.name and self.age are instance variables.
• introduce() is a method that accesses the instance variables using self.
def show_info(self):
print(f"Laptop Brand: {self.brand}, Price: ₹{self.price}")
laptop1.show_info()
laptop2.show_info()
Output:
Laptop Brand: Dell, Price: ₹45000
Laptop Brand: HP, Price: ₹55000
• Each Laptop object has its own values for brand and price, demonstrating
unique attribute assignment through __init__().
def show_book(self):
print(f"Title: {self.title}, Author: {self.author}")
book1.show_book()
book2.show_book()
Output:
Title: Python Programming, Author: Unknown
Title: Machine Learning, Author: Andrew Ng
In this example:
• If an author is not provided, it defaults to "Unknown".
5. Homework
1. Create a Class with a Constructor:
o Write a class Movie with attributes title and rating using
the __init__() constructor.
o Define a method to display the movie’s title and rating.
2. Add Default Parameters:
o Create a class Employee with attributes name, designation,
and salary (default value of salary is 30,000).
o Write a method that displays the details of each employee.
o Create multiple Employee objects with different values
for name and designation, and test the default salary behavior.
1. Encapsulation
• Definition: Encapsulation involves wrapping data and methods that
operate on that data within one unit, such as a class. This protects the
data from external interference and misuse, improving security and
maintainability.
• Real-World Example: Imagine an ATM machine—you interact with a
limited interface (e.g., withdraw, deposit, check balance) but do not have
access to the inner mechanics or backend functions.
atm = ATM(1000)
atm.deposit(500)
atm.withdraw(300)
Here, __balance is a private attribute, ensuring only
the deposit() and withdraw() methods can modify it.
def get_username(self):
return self.username
2. Abstraction
• Definition: Abstraction hides the complex inner workings of an object,
exposing only the essential parts for interaction.
• Real-World Example: Think about driving a car. You use the steering
wheel and pedals to control the car, without needing to know the engine
mechanics or braking systems.
def accelerate(self):
print("Car accelerating")
def brake(self):
print("Car stopping")
car = Car()
car.start_engine() # Abstracts complex internal workings
car.accelerate()
car.brake()
Here, Car abstracts internal functions like ignition and fuel management,
presenting only basic methods for interaction.
db = Database()
db.save_data("user_101", {"name": "Raj", "age": 30})
print(db.get_data("user_101"))
The user can store and retrieve data without needing to know the storage details.
3. Inheritance
• Definition: Inheritance allows a class to inherit attributes and methods
from another class, facilitating reuse.
• Real-World Example: Consider human families. Characteristics like
surname, traditions, or physical features can be passed down from parents
to children.
Real-World Example in Code:
class Family:
def __init__(self, surname):
self.surname = surname
class Child(Family):
def __init__(self, surname, name):
super().__init__(surname)
self.name = name
class Admin(User):
def delete_user(self, user):
print(f"Admin {self.username} deleted user {user}")
admin = Admin("karnataka_admin")
admin.login() # Inherited from User
admin.delete_user("user_102") # Admin-specific method
Here, Admin inherits from User and gains additional functionality.
4. Polymorphism
• Definition: Polymorphism allows objects of different classes to be treated
as objects of a common superclass, but they can behave differently
depending on the object type.
• Real-World Example: Think of animals making sounds—both dogs and
cats make sounds, but each produces a distinct sound. They share a
common method make_sound(), but the output varies.
Real-World Example in Code:
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Bark")
class Cat(Animal):
def make_sound(self):
print("Meow")
class EmailNotification(Notification):
def send(self):
print("Sending Email")
class SMSNotification(Notification):
def send(self):
print("Sending SMS")
Homework
1. Encapsulation:
o Create a BankAccount class with private attributes
for account_number and balance.
o Add methods to check balance, deposit, and withdraw funds.
o Try accessing the balance directly and observe the result.
2. Abstraction:
o Design a Phone class with methods
to call_contact and take_picture. Abstract away any internal
processing details and focus on creating a user-friendly interface.
3. Inheritance:
o Create a base class Vehicle with a start method. Then create a
subclass Bike with an additional ride() method.
o Demonstrate how the Bike can use both start and ride.
4. Polymorphism:
o Implement a Shape class and derive Circle and Rectangle classes
with a method calculate_area. Each class should calculate area
differently based on its shape.
o Create a loop to calculate areas for
both Circle and Rectangle objects.
# Usage
student = Student("Anita", 20)
print("Age:", student.get_age()) # Accessing age with getter
student.set_age(21) # Modifying age with setter
print("Updated Age:", student.get_age())
Output:
Age: 20
Updated Age: 21
Here:
• get_age() provides read-only access to __age, while set_age() enables
controlled modification.
2. Method Overloading
• Definition: Method overloading is the ability to define multiple methods
with the same name but different parameters.
• Note: Python doesn’t support method overloading directly, but we can
achieve it by using default parameters or by handling varying numbers of
arguments with *args or **kwargs.
Example:
class MathOperations:
def add(self, a, b, c=0):
return a + b + c # Handles both 2 and 3 parameter cases
# Usage
math = MathOperations()
print(math.add(5, 10)) # Two arguments
print(math.add(5, 10, 15)) # Three arguments
Output:
15
30
Here:
• The method add can accept either two or three arguments, handling both
cases within the same method.
3. Method Overriding
• Definition: Method overriding allows a child class to provide a specific
implementation for a method that is already defined in its parent class.
• Purpose: It enables a child class to alter or extend the behavior of a parent
class method.
Example:
class Animal:
def sound(self):
print("This animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks") # Overrides the parent class method
# Usage
animal = Animal()
animal.sound()
dog = Dog()
dog.sound() # Calls the overridden method in Dog class
Output:
This animal makes a sound
Dog barks
Here:
• sound() in Dog overrides the sound() method in Animal, providing
specific behavior for Dog.
4. super() Function
• Definition: The super() function is used in child classes to call a method
from the parent class, enabling access to inherited methods or attributes.
• Purpose: It ensures that the parent class's method is executed alongside
any additional functionality added in the child class, useful when
overriding methods but still needing to incorporate the parent’s behavior.
Example:
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the parent class's __init__ method
self.breed = breed
def sound(self):
super().sound() # Calling the parent class's sound method
print(f"{self.name} barks")
# Usage
dog = Dog("Buddy", "Labrador")
dog.sound()
Output:
Buddy makes a sound
Buddy barks
Here:
• super().__init__(name) in the Dog class calls the __init__ method from
the Animal class, initializing the name attribute.
• Similarly, super().sound() calls the sound method in Animal, followed by
the additional behavior in Dog.
5. Abstract Classes
• Definition: An abstract class in Python is a class that cannot be
instantiated directly. It can have abstract methods, which must be
implemented by subclasses.
• Purpose: Abstract classes provide a blueprint for other classes, enforcing
a structure where subclasses must implement certain methods.
• Implementation: Use the ABC (Abstract Base Class) module to create
abstract classes in Python.
Example:
from abc import ABC, abstractmethod
class Car(Vehicle):
def start_engine(self):
print("Car engine started")
# Usage
car = Car()
car.start_engine()
Output:
Car engine started
Here:
• Vehicle is an abstract class that defines an abstract
method start_engine().
• Car inherits from Vehicle and provides an implementation
of start_engine(), enabling us to create an object of Car.
6. Homework
1. Getters and Setters:
o Create a class BankAccount with a private attribute balance.
o Write a getter method to retrieve the balance and a setter method
to update it, ensuring the balance never goes below zero.
2. Method Overloading:
o Write a class Calculator with a method multiply(). Allow it to take
either two or three arguments to multiply two or three numbers.
3. Method Overriding:
o Create a parent class Shape with a method draw() that prints
"Drawing shape".
o Create a child class Circle that overrides draw() to print "Drawing
circle".
4. Abstract Classes:
o Define an abstract class Employee with an abstract
method calculate_salary().
o Create a subclass Manager that
implements calculate_salary() based on working hours and rate per
hour.
while True:
menu()
choice = input("Enter your choice (1-4): ")
if choice == '1':
print("You selected Option 1.")
elif choice == '2':
print("You selected Option 2.")
elif choice == '3':
print("You selected Option 3.")
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
Detailed Example
Scenario: Simple Calculator
A menu-driven program to perform basic arithmetic operations.
def menu():
print("\nSimple Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
while True:
menu()
choice = input("Enter your choice (1-5): ")
if choice == '1':
print(f"Result: {num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"Result: {num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"Result: {num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"Result: {num1} / {num2} = {num1 / num2}")
elif choice == '5':
print("Exiting the calculator. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")
Key Points to Note
1. Input Validation:
o Ensure user input is valid to prevent runtime errors.
o Example: Check if the user enters a number when required.
2. Exit Condition:
o Use a specific option (e.g., 4 or 5) to allow users to exit the program
gracefully.
3. Error Handling:
o Handle cases like division by zero or invalid inputs
using try and except.
4. Reusability:
o Define a separate function for the menu to avoid repeating code.
Homework
1. Banking System: Write a menu-driven program to simulate a basic
banking system with options like:
o Check Balance
o Deposit Money
o Withdraw Money
o Exit
2. Grocery Store Menu:
o Create a program where users can:
§ Add items to their cart.
§ Remove items.
§ View the total price.
§ Exit.
3. Educational System:
o Write a program with options to:
§ Add student details.
§ Display student details.
§ Exit.
OOP Challenges
5. Traffic Simulation
Design a simulation of a traffic system in a city, including vehicles, roads, and
traffic lights.
• Vehicles (e.g., cars, buses, bikes) have different speeds and behaviors.
• Roads have capacities, and traffic lights regulate the flow.
• Add features like handling traffic jams and prioritizing emergency vehicles.
These challenges progressively test the understanding of core OOP principles like
inheritance, polymorphism, abstraction, and encapsulation, while also
encouraging real-world problem-solving.
SUPPORTED BY
UNIQFIN BUSINESS SCHOOL MARATHAHALLI .