SlideShare a Scribd company logo
2025pylab engineering 2025pylab engineering
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.
WEEK 2
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")
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")
Ternary Conditional (if-else in one line)
example
x = 8
print("Even") if x % 2 == 0 else print("Odd")
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
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)
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)
Nested Loops
A loop inside another loop.
example
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
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.
WEEK 3
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")
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)]
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.
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)
a1_zeros = np.zeros((3, 3))
a2_ones = np.ones((2, 2))
a3_range = np.arange(0, 10, 2)
print(a1_zeros)
print(a2_ones)
print(a3_range)
output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
[0 2 4 6 8]
Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
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]
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)
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()
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.
WEEK 4
Creating and calling functions in Python
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.
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.
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
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 ( : ).
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,
}
2025pylab engineering 2025pylab engineering
# 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'}
# 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}
STRING
list functions
Tuple Functions
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.
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.
2025pylab engineering 2025pylab engineering
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
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.")
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).
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.
WEEK -6
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.
Syntax for Inheritance
class ParentClass:
# Parent class code here pass
class ChildClass(ParentClass):
# Child class code here pass
●
2025pylab engineering 2025pylab engineering
Basic Inheritance Syntax
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
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.
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.
2025pylab engineering 2025pylab engineering
root = tk.Tk() #root object represents the application's primary window
# 1. Create widget
btn = tk.Button(root,
text="Click Me",
command=button_click,
bg="blue",
fg="white")
# 2. Position widget
btn.pack(pady=10) # Adds vertical padding
root.mainloop()
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)

More Related Content

PDF
III MCS python lab (1).pdf
PDF
Python-Cheat-Sheet.pdf
PDF
C++ Course - Lesson 2
PPTX
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
PDF
Python basic
PPTX
Python Workshop - Learn Python the Hard Way
PDF
The Ring programming language version 1.5.2 book - Part 21 of 181
PPTX
C# introduzione per cibo e altri usi vati
III MCS python lab (1).pdf
Python-Cheat-Sheet.pdf
C++ Course - Lesson 2
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
Python basic
Python Workshop - Learn Python the Hard Way
The Ring programming language version 1.5.2 book - Part 21 of 181
C# introduzione per cibo e altri usi vati

Similar to 2025pylab engineering 2025pylab engineering (20)

PPTX
NUMPY [Autosaved] .pptx
PPTX
Working with functions.pptx. Hb.
PPTX
Python functions PYTHON FUNCTIONS1234567
PPTX
made it easy: python quick reference for beginners
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DOCX
Write a NumPy program to find the most frequent value in an array. Take two...
PPTX
Python programming workshop
PPTX
Python1_Extracted_PDF_20250404_1054.pptx
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
PDF
The Ring programming language version 1.8 book - Part 94 of 202
PDF
Unit-5-Part1 Array in Python programming.pdf
PPTX
Introduction to python programming ( part-3 )
DOCX
Basic python laboratoty_ PSPP Manual .docx
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
NUMPY [Autosaved] .pptx
Working with functions.pptx. Hb.
Python functions PYTHON FUNCTIONS1234567
made it easy: python quick reference for beginners
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Write a NumPy program to find the most frequent value in an array. Take two...
Python programming workshop
Python1_Extracted_PDF_20250404_1054.pptx
Raspberry Pi - Lecture 5 Python for Raspberry Pi
The Ring programming language version 1.8 book - Part 94 of 202
Unit-5-Part1 Array in Python programming.pdf
Introduction to python programming ( part-3 )
Basic python laboratoty_ PSPP Manual .docx
Python basics
Python basics
Python basics
Python basics
Python basics
Python basics
Ad

Recently uploaded (20)

PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
DOCX
573137875-Attendance-Management-System-original
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Welding lecture in detail for understanding
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
web development for engineering and engineering
PPTX
OOP with Java - Java Introduction (Basics)
R24 SURVEYING LAB MANUAL for civil enggi
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Geodesy 1.pptx...............................................
UNIT-1 - COAL BASED THERMAL POWER PLANTS
573137875-Attendance-Management-System-original
UNIT 4 Total Quality Management .pptx
Lecture Notes Electrical Wiring System Components
Welding lecture in detail for understanding
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Internet of Things (IOT) - A guide to understanding
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
additive manufacturing of ss316l using mig welding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
web development for engineering and engineering
OOP with Java - Java Introduction (Basics)
Ad

2025pylab engineering 2025pylab engineering

  • 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")
  • 6. Ternary Conditional (if-else in one line) example x = 8 print("Even") if x % 2 == 0 else print("Odd")
  • 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)
  • 17. a1_zeros = np.zeros((3, 3)) a2_ones = np.ones((2, 2)) a3_range = np.arange(0, 10, 2) print(a1_zeros) print(a2_ones) print(a3_range) output: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[1. 1.] [1. 1.]] [0 2 4 6 8]
  • 18. Example import numpy arr = numpy.array([1, 2, 3, 4, 5]) print(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.
  • 24. Creating and calling functions in Python
  • 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.
  • 51. root = tk.Tk() #root object represents the application's primary window # 1. Create widget btn = tk.Button(root, text="Click Me", command=button_click, bg="blue", fg="white") # 2. Position widget btn.pack(pady=10) # Adds vertical padding root.mainloop()
  • 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)