2. Exercise Week 1
1.Write a Python program that takes two numbers as
input and prints their sum.
2.Create a calculator that takes two numbers and
an operator (+, -, *, /) as input and performs the
operation.
3. Take three numbers as input and print the largest
one.
4. Conditional statements
if Statement
Executes a block of code
if the condition is True.
example
x = 10
if x > 5:
print("x is greater than
5")
if-else Statement
Executes one block if the
condition is True, otherwise
executes another block.
example
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
5. if-elif-else Statement
Checks multiple conditions in
sequence.
example
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is between 6 and 10")
else:
print("x is 5 or less")
Nested if Statements
An if statement inside another if
statement.
example
x = 15
if x > 10:
print("x is greater than 10")
if x > 20:
print("x is also greater than
20")
7. Looping statements
Python allow you to execute a block of code multiple times. Here
are the main types of loops
for Loop
Used to iterate over a
sequence (like a list, tuple,
string, or range).
example
for i in range(5): # Loops
from 0 to 4
print(i)
while Loop
Repeats as long as a
condition is True.
example
x = 0
while x < 5:
print(x)
x += 1 # Increment x
8. for Loop with break
example
for i in range(10):
if i == 5:
break # Exits loop
when i is 5
print(i)
for Loop with continue
Skips the current iteration and
moves to the next one.
example
for i in range(5):
if i == 2:
continue # Skips 2
print(i)
9. while Loop with break
example
x = 0
while x < 5:
if x == 3:
break # Exits when x is 3
print(x)
x += 1
while Loop with continue
example
x = 0
while x < 5:
x += 1
if x == 3:
continue # Skips 3
print(x)
10. Nested Loops
A loop inside another loop.
example
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
11. Week 2 Assignment
1.Python programs to Stop the Loop at 5 using a for Loop with
break
2.Skip Even Numbers using a while Loop with continue
3.Python programs to Multiplication Table from 1 to 3 using
Nested for Loop
4.Python programs to Pattern Printing using Nested while Loop
5.Number Guessing Game (Use a while loop to let the user guess
a number until they get it right.
13. Tuple
A tuple in Python is an ordered, immutable
sequence of items.
Tuples can have elements of different data
types.
Tuples are created using parentheses ()
Example
mytuple = ("apple", "banana", "cherry")
14. List
A list in Python is an ordered, mutable
sequence of items.
Lists are created using square brackets []
can hold elements of different data types
within the same list.
Example:my_list = [10, "hello", 3.14, True,
[1, 2, 3], (4, 5)]
15. NumPy
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra,
matrices.
In Python we have lists that serve the purpose of arrays, but they
are slow to process.
NumPy aims to provide an array object that is up to 50x faster
than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of
supporting functions that make working with ndarray very easy.
16. import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: n",arr)
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("Array with Rank 2: n", arr)
# Creating an array from tuple
arr = np.array((1, 3, 2))
print("nArray created using "
"passed tuple:n", arr)
19. import numpy as np
# Create a sample NumPy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Basic slicing: [start:stop:step]
# Get elements from index 2 to 5 (exclusive)
slice1 = arr[2:5] # Output: [3 4 5]
# Get elements from the beginning to index 4 (exclusive)
slice2 = arr[:4] # Output: [1 2 3 4]
# Get elements from index 5 to the end
slice3 = arr[5:] # Output: [ 6 7 8 9 10]
# Get every other element
slice4 = arr[::2] # Output: [ 1 3 5 7 9]
# Reverse the array
slice5 = arr[::-1] # Output: [10 9 8 7 6 5 4 3 2 1]
# Slicing in multi-dimensional arrays
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Get the first row
row1 = arr2d[0, :] # Output: [1 2 3]
# Get the second column
col2 = arr2d[:, 1] # Output: [2 5 8]
20. NumPy as np
NumPy is usually
imported under the np
alias.
alias: In Python alias
are an alternate name
for referring to the
same thing.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
21. Python Functions
A function is a block of code which only runs when it is
called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
my_function()
22. Week 3 Assignment
1)Write a program that takes a list of integers as input and returns
a new list containing only the unique elements (remove
duplicates). Maintain the original order of elements.
2)Write a function that takes a tuple of numbers as input and
returns the product of all the numbers in the tuple.
3)Write a NumPy program to extract all even numbers from a
given NumPy array.
4)Write a function that takes a string as input and returns the
number of vowels in the string (a, e, i, o, u). Consider both
uppercase and lowercase vowels.
25. Types of Functions
Basic Function
A function is created using the def keyword.
It performs a task when called.
Example:
def greet():
print("Hello, world!")
greet() # Output: Hello, world!
Function with Parameters
Functions can take inputs (called parameters) to
perform tasks.
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8
# The add_numbers() function takes two
numbers (a and b) and returns their sum.
26. Function with Default Parameters
You can provide default values for parameters.
If no argument is passed, the default value is
used.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
#The greet() function uses "Guest" as the
default name if no argument is provided.
Function with Variable-length Arguments
Use *args to accept any number of arguments.
Example:
def sum_all(*args):
return sum(args)
result = sum_all(1, 2, 3, 4, 5)
print(result) # Output: 15
#The sum_all() function takes any number of
arguments and returns their sum.
27. Function with Keyword Arguments
Use key=value pairs to pass arguments.
Example:
def print_info(name, age):
print(f"Name: {name}, Age: {age}")
print_info(age=30, name="John") # Output:
Name: John, Age: 30
#The print_info() function accepts arguments by
name, making the order irrelevant.
Lambda Function (Anonymous Function)
A short, one-line function defined using
the lambda keyword.
Example
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
#The lambda function adds two numbers
(x and y) and returns the result
28. Dictionaries
Dictionary is a built-in Python Data Structure and are used to store data
values in key:value pairs. Each key is
Dictionaries are not indexed by a sequence of numbers but indexed based on keys
separated from its value by a colon ( : ).
29. Creating a Dictionary
The syntax for defining a dictionary is:
dictionary_name = {key_1: value_1, key_2: value2, key_3: value_3}
(Or)
dictionary_name = {
key_1: value_1,
key_2: value_2,
key_3: value_3,
}
31. # Creating a dictionary
student = {
"name": "Alice",
"age": 22,
"course": "Computer Science"
}
# 1. Accessing a value using get()
print(student.get("name")) # Output: Alice
# 2. Adding a new key-value pair
student["grade"] = "A"
print(student) # {'name': 'Alice', 'age': 22, 'course': 'Computer Science', 'grade': 'A'}
# 3. Updating an existing value
student.update({"age": 23})
print(student) # {'name': 'Alice', 'age': 23, 'course': 'Computer Science', 'grade': 'A'}
# 4. Removing a key-value pair using pop()
removed_value = student.pop("course")
print(removed_value) # Output: Computer Science
print(student) # {'name': 'Alice', 'age': 23, 'grade': 'A'}
32. # 5. Getting all keys
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age', 'grade'])
# 6. Getting all values
values = student.values()
print(values) # Output: dict_values(['Alice', 23, 'A'])
# 7. Getting all key-value pairs
items = student.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 23), ('grade', 'A')])
# 8. Removing all elements using clear()
student.clear()
print(student) # Output: {}
# 9. Creating a copy of a dictionary
new_student = student.copy()
print(new_student) # Output: {}
# 10. Using setdefault() to get or set a default value
student.setdefault("age", 20)
print(student) # Output: {'age': 20}
36. Exception
●
An exception is an error that occurs during the
execution of a program, causing it to stop
unexpectedly unless handled properly.
●
Exceptions interrupt the normal flow of a
program.
37. Exception Handling
●
The try block lets you test a block of code for errors.
●
The except block lets you handle the error.
●
The else block lets you execute code when there is no error.
●
The finally block lets you execute code, regardless of the result of the try-
and except blocks.
39. Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
40. Example
try:
num = int(input("Enter a number: ")) # User input
result = 10 / num # May raise ZeroDivisionError
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
41. 1.Write a Python program to accept a 3*3 matrix as input from the user find the
transpose of the matrix. Print both the original and transposed matrices.
Exception Handling
●
Write a Python program that takes a list of numbers as input asks the user for an
index position and prints the number at that index.
●
Uses try-except to handle:
●
IndexError (if an invalid index is entered).
●
ValueError (if the user enters a non-integer index).
42. WEEK-5 Assignment Question
1. Write a Python program to accept a 3X3 matrix as input from the user, find the
transpose of the matrix and Print both the original and transposed matrices.
2. Create a program that reads a number from user input. Handle the ValueError if the
input is not a valid integer.
3. Write a program that takes two numbers as input and divides the first by the
second. Handle the following exceptions
a)ZeroDivisionError (if the denominator is zero).
b)ValueError (if either input is not a number).
1. Write a Python program that repeatedly prompts the user to enter a positive
number, handling invalid inputs appropriately with a maximum of 3 attempts.
44. Python Inheritance
Inheritance allows us to define a class that
inherits all the methods and properties from
another class.
Parent class is the class being inherited from,
also called base class.
Child class is the class that inherits from another
class, also called derived class.
45. Syntax for Inheritance
class ParentClass:
# Parent class code here pass
class ChildClass(ParentClass):
# Child class code here pass
●
47. Basic Inheritance Syntax
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
48. Single Inheritance
A child class inherits from only one parent class.
Example
class Parent:
def show(self):
print("This is the Parent class.")
class Child(Parent): # Single Inheritance
pass # Inherits all methods from Parent
obj = Child()
obj.show() # Output: This is the Parent class.
49. Multiple Inheritance
A child class inherits from more than one parent class.
class Parent1:
def show1(self):
print("This is Parent1 class.")
class Parent2:
def show2(self):
print("This is Parent2 class.")
class Child(Parent1, Parent2): # Multiple Inheritance
pass
obj = Child()
obj.show1() # Output: This is Parent1 class.
obj.show2() # Output: This is Parent2 class.
52. Tkinter layout managers
To make widgets visible, you must position them using one of these
methods:
.pack() - Simple vertical/horizontal stacking
label.pack(side="top", padx=5, pady=5)
.grid() - Row/column layout (like a spreadsheet)
button.grid(row=0, column=1, sticky="ew")
.place() - Precise pixel positioning
canvas.place(x=50, y=100)