SlideShare a Scribd company logo
Python
Master it
Outlines
• Topic 1: Introduction to Python
• Topic 2: Python Operators
• Topic 3: Variables
• Topic 4: Conditional Statements
• Topic 5: Iteration
• Topic 6: Python Lists
• Topic 7: Python Tuples
• Topic 8: Advanced Control Flow
Outlines
• Topic 9: Functions and Modules
• Topic 10: Object-Oriented Programming
• Topic 11: Data Structures and Algorithms
• Topic 12: File Handling and Data Serialization
• Topic 13: Final Project
Let’s GO
• Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.
Python Getting Started
• Pycharm: https://www.jetbrains.com/pycharm/download/other.html
• Google Colab https://colab.google/
• print("Hello, World!")
Execute Python Syntax
• Python Indentation: Indentation refers to the spaces at the beginning of a
code line.
Python Variables
• In python, variables are created when you assign a value to it.
• x = 5
y = "Hello, World!"
• Python has commenting capability for the purpose of in-code documentation.
• Comments start with a #, and Python will render the rest of the line as a
comment:
• #This is a comment.
print("Hello, World!")
Python Variables
• Python has no command for declaring a variable.
• Variables do not need to be declared with any particular type, and can even
change type after they have been set.
• x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
• If you want to specify the data type of a variable, this can be done with
casting.
• x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
• You can get the data type of a variable with the type() function.
• x = 5
y = "John"
print(type(x))
print(type(y))
• Single or Double Quotes?
• x = "John"
# is the same as
x = 'John'
Case-Sensitive
• Variable names are case-sensitive.
• a = 4
A = "Sally"
#A will not overwrite a
Variable Names
• Rules for Python variables: A variable name must start with a letter or the
underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Python keywords
Variable Names
• Camel Case: Each word, except the first, starts with a capital letter:
• myVariableName = "John"
• Pascal Case: Each word starts with a capital letter:
• MyVariableName = "John"
• Snake Case: Each word is separated by an underscore character:
• my_variable_name = "John"
Python Variables - Assign Multiple Values
• Many Values to Multiple Variables: Python allows you to assign values to multiple variables in one
line:
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• One Value to Multiple Variables: And you can assign the same value to multiple variables in one line:
• x = y = z = "Orange"
print(x)
print(y)
print(z)
Python Variables - Assign Multiple Values
• Unpack a Collection: If you have a collection of values in a list, tuple etc.
Python allows you to extract the values into variables. This is called unpacking.
• fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables
• The Python print() function is often used to output variables.
• x = "Python is awesome"
print(x)
• x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Python - Output Variables
• The Python print() function is often used to output variables.
• x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
• x = 5
y = 10
print(x + y)
Python - Output Variables
Python - Global Variables
Python - Global Variables
The global Keyword
The global Keyword
Test your knowledge
• https://
www.w3schools.com/python/exercise.asp?filename=exercise_variables1
Exercises
• Create variables with valid names for a person's first name, last name, age,
and whether they are a student. Assign appropriate values to these variables
and print them.
• Assign the values 10, 20, and 30 to the variables x, y, and z respectively in a
single line. Print the values of these variables.
• Define a global variable named counter. Create a function that increments
this counter by 1 each time it is called. Call this function twice and print the
value of the counter after each call.
Exercises
• Create variables with valid names for a person's first name, last name, age,
and whether they are a student. Assign appropriate values to these variables
and print them.
• Assign the values 10, 20, and 30 to the variables x, y, and z respectively in a
single line. Print the values of these variables.
• Define a global variable named counter. Create a function that increments
this counter by 1 each time it is called. Call this function twice and print the
value of the counter after each call.
User-input variables
• User input variables are variables that store data provided by the user during
the execution of a program.
• In Python, the input() function is used to get input from the user. The data
entered by the user is typically stored in a variable for further use in the
program.
Example
age = int(input("Enter your age: "))
Python Operators
• Python Numbers
• Python supports several types of numeric data:
• Integers (int): Whole numbers, positive or negative, without a decimal
point.
• Floats (float): Numbers that contain a decimal point.
• Complex numbers (complex): Numbers with a real and imaginary part.
Python Arithmetic Operators
• Arithmetic operators are used to perform mathematical operations.
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulus)
• ** (Exponentiation)
• // (Floor Division)
Python Comparison Operators
• Comparison operators are used to compare two values and return a Boolean
result (True or False).
• == (Equal to)
• != (Not equal to)
• > (Greater than)
• < (Less than)
• >= (Greater than or equal to)
• <= (Less than or equal to)
Python Logical Operators
• Logical operators are used to combine conditional statements.
• and (Logical AND)
• or (Logical OR)
• not (Logical NOT)
Exercise
• Given the following values:
• a = 7
• b = 4
• c = 9
• Calculate the sum of a and b.
• Calculate the product of b and c.
• Check if a is equal to b.
• Check if c is greater than a.
• Use a logical AND operator to check if a is greater than b and c is greater than a.
• Use a logical OR operator to check if a is greater than b or c is less than b.
Conditional Statements in Python
• Types of Conditional Statements
• if statement
• if-else statement
• elif statement
• Nested conditional statements
if statement
• The if statement is used to test a specific condition. If the condition is true,
the block of code inside the if statement is executed.
• age = 18
• if age >= 18:
• print("You are an adult.")
if-else statement
• The if-else statement adds an alternative path of execution when the
condition is false.
• age = 16
• if age >= 18:
• print("You are an adult.")
• else:
• print("You are not an adult.")
elif statement
• The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the
conditions is true.
• score = 85
• if score >= 90:
• print("Grade: A")
• elif score >= 80:
• print("Grade: B")
• elif score >= 70:
• print("Grade: C")
• else:
• print("Grade: F")
Nested conditional statements
• You can use one if or else if statement inside another if or else if statement(s).
• num = 10
• if num > 0:
• if num % 2 == 0:
• print("Positive and Even")
• else:
• print("Positive but Odd")
• else:
• print("Negative")
Exercises
• Write a program that asks the user to input their age. If they are 18 or older,
print "You are eligible to vote.“
• Write a program that asks the user to input a number. Print whether the number
is positive or negative.
• Write a program that asks the user for their exam score, and print the
corresponding grade (A, B, C, F).
• Write a program that checks whether a given year is a leap year. A year is a leap
year if it is divisible by 4 but not 100, except if it is also divisible by 400.
Solution-1
• age = int(input("Enter your age: "))
• if age >= 18:
• print("You are eligible to vote.")
Solution-2
• number = float(input("Enter a number: "))
• if number >= 0:
• print("The number is positive.")
• else:
• print("The number is negative.")
Solution-3
• score = int(input("Enter your score: "))
• if score >= 90:
• print("Grade: A")
• elif score >= 80:
• print("Grade: B")
• elif score >= 70:
• print("Grade: C")
• else:
• print("Grade: F")
Solution-4
• year = int(input("Enter a year: "))
• if year % 4 == 0:
• if year % 100 == 0:
• if year % 400 == 0:
• print(f"{year} is a leap year.")
• else:
• print(f"{year} is not a leap year.")
• else:
• print(f"{year} is a leap year.")
• else:
• print(f"{year} is not a leap year.")
Iteration
• Iteration is a fundamental concept in programming where a sequence of
instructions is repeated until a certain condition is met.
• Python supports several constructs to implement iteration, such as loops.
• Types of Iteration
• for loop
• while loop
• Nested loops
For loop
• The for loop in Python is used for iterating over a sequence (such as a list,
tuple, dictionary, set, or string).
• fruits = ["apple", "banana", "cherry"]
• for fruit in fruits:
• print(fruit)
While loop
• The while loop in Python repeatedly executes a block of code as long as the
condition is true.
• count = 0
• while count < 5:
• print(count)
• count += 1
Nested loop
• Nested loops are loops within loops. The inner loop runs to completion each
time the outer loop runs once.
• for i in range(3):
• for j in range(2):
• print(f"i = {i}, j = {j}")
Loop Control Statements
• Break: Exits the loop prematurely.
• Continue: Skips the current iteration and moves to the next iteration.
Examples
• for i in range(10):
• if i == 5:
• break
• print(i)
• --------------------------------------------------------------------------------------------------
• for i in range(10):
• if i % 2 == 0:
• continue
• print(i)
Exercises
• Write a program to iterate over a list of numbers and print only the even
numbers.
• Write a program that calculates the factorial of a given number n.
• Write a program to print a multiplication table for numbers from 1 to 5.
• Write a program that iterates over numbers from 1 to 10, but skips the
number 5 using continue, and stops the loop if the number is 8 using break.
Python Lists
• A list is a collection which is ordered and changeable. In Python, lists are
written with square brackets.
• # Creating a list
• fruits = ["apple", "banana", "cherry"]
• print(fruits)
• Create a list named colors that contains at least 5 different color names.
Python Lists
• You can access list items by referring to the index number, inside square
brackets. Note that list indices start at 0.
• # Accessing an item
• fruits = ["apple", "banana", "cherry"]
• print(fruits[1]) # Output: banana
• Access the third item in the colors list you created.
Python Lists
• You can change the value of a specific item by referring to its index.
• # Changing item value
• fruits = ["apple", "banana", "cherry"]
• fruits[1] = "blueberry"
• print(fruits) # Output: ['apple', 'blueberry', 'cherry']
• Change the second color in your colors list to "magenta".
Python Lists
• You can loop through the list items by using a for loop.
• # Looping through a list
• fruits = ["apple", "banana", "cherry"]
• for f in fruits:
• print(f)
• Write a loop that prints each color in your colors list.
Python Lists
• To determine if a specified item is present in a list use the in keyword.
• # Checking if item exists
• fruits = ["apple", "banana", "cherry"]
• if "banana" in fruits:
• print("Banana is in the list")
• Check if the color "blue" is in your colors list and print an appropriate
message.
Python Lists
• To determine how many items a list has, use the len() function.
• # Getting the length of a list
• fruits = ["apple", "banana", "cherry"]
• print(len(fruits)) # Output: 3
• Print the length of your colors list.
Python Lists
• To add an item to the end of the list, use the append() method.
• # Adding an item
• fruits = ["apple", "banana", "cherry"]
• fruits.append("orange")
• print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
• Add a new color to your colors list.
Python Lists
• There are several methods to remove items from a list:
• remove(): Removes the first item with the specified value.
• pop(): Removes the item at the specified position.
• del: Removes the item at the specified index or the entire list.
• clear(): Empties the list.
Python Lists
• # Removing an item using remove()
• fruits = ["apple", "banana", "cherry"]
• fruits.remove("banana")
• print(fruits) # Output: ['apple', 'cherry']
• # Removing an item using pop()
• fruits.pop(1)
• print(fruits) # Output: ['apple']
Python Lists
• # Removing an item using del
• del fruits[0]
• print(fruits) # Output: []
• # Clearing the list
• fruits = ["apple", "banana", "cherry"]
• fruits.clear()
• print(fruits) # Output: []
• Remove the first color from your colors list.
Python Lists
• You can copy a list using the copy() method or by using list slicing.
• # Copying a list using copy()
• fruits = ["apple", "banana", "cherry"]
• fruits_copy = fruits.copy()
• print(fruits_copy) # Output: ['apple', 'banana', 'cherry']
• # Copying a list using slicing
• fruits_copy = fruits[:]
• print(fruits_copy) # Output: ['apple', 'banana', 'cherry']
Python Lists
• You can join two lists using the + operator or the extend() method.
• # Joining two lists using +
• list1 = ["a", "b", "c"]
• list2 = [1, 2, 3]
• joined_list = list1 + list2
• print(joined_list) # Output: ['a', 'b', 'c', 1, 2, 3]
• # Joining two lists using extend()
• list1.extend(list2)
• print(list1) # Output: ['a', 'b', 'c', 1, 2, 3]
Python Lists
• Create a copy of your colors list.
• Join your colors list with a new list more_colors containing at least 3
different colors.
Arrays
• An array is a data structure that can hold multiple values at once.
• Unlike lists, arrays are designed to store only one type of data.
• Arrays are useful for numerical operations and scientific computing.
Creating Arrays
• Import the array module.
• Define the type code (e.g., 'i' for integers, 'f' for floats).
• Provide initial values.
• import array as arr
• # Creating an array of floats
• floats = arr.array('f', [1.1, 2.2, 3.3])
• print(floats)
Accessing Array Elements
• Access elements using their index.
• Indexing starts at 0.
• import array as arr
• numbers = arr.array('i', [1, 2, 3, 4, 5])
• print(numbers[0]) # Output: 1
• print(numbers[2]) # Output: 3
Modifying Arrays
• Change the value of an array element by accessing its index.
• import array as arr
• numbers = arr.array('i', [1, 2, 3, 4, 5])
• numbers[1] = 10
• print(numbers) # Output: array('i', [1, 10, 3, 4, 5])
Array Operations
• You can perform various operations like adding, removing, and slicing elements.
• import array as arr
• numbers = arr.array('i', [1, 2, 3, 4, 5])
• # Adding elements
• numbers.append(6)
• print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6])
• # Removing elements
• numbers.pop(2)
• print(numbers) # Output: array('i', [1, 2, 4, 5, 6])
Array Slicing
• Access a range of elements using slicing.
• import array as arr
• numbers = arr.array('i', [1, 2, 3, 4, 5])
• print(numbers[1:4]) # Output: array('i', [2, 3, 4])
Looping Through Arrays
• Use loops to iterate over array elements.
• import array as arr
• numbers = arr.array('i', [1, 2, 3, 4, 5])
• for num in numbers:
• print(num)
Exercises
• Exercise 1:
• Create an array of integers from 1 to 10.
• Replace the value at index 5 with 50.
• Print the updated array.
• Exercise 2:
• Create an array of floats: [1.5, 2.5, 3.5, 4.5].
• Append the value 5.5 to the array.
• Remove the value at index 2.
• Print the final array.
Solutions
• # Exercise 1
• import numpy as np
• # Create an array of integers from 1 to 10
• array1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
• print("Original array:", array1)
• # Replace the value at index 5 with 50
• array1[5] = 50
• print("Updated array:", array1)
Solutions
• # Exercise 2
• # Create an array of floats: [1.5, 2.5, 3.5, 4.5]
• array2 = np.array([1.5, 2.5, 3.5, 4.5])
• print("Original array:", array2)
• # Append the value 5.5 to the array
• array2 = np.append(array2, 5.5)
• print("Array after appending 5.5:", array2)
• # Remove the value at index 2
• array2 = np.delete(array2, 2)
• print("Final array:", array2)
Difference between range and arange
• range is a built-in Python function that generates a sequence of numbers.
• arange is a function in the NumPy library that generates arrays.
• Using Range:
• range(start, stop, step) generates a sequence of numbers from start to stop -
1 with a step size of step.
• range returns a range object, not an array or list.
range
• # Using range in Python
• numbers = range(1, 10, 2)
• print(numbers) # Output: range(1, 10, 2)
• print(list(numbers)) # Output: [1, 3, 5, 7, 9]
Arange
• arange(start, stop, step) generates an array of numbers from start to stop with a step size
of step.
• arange returns a NumPy array.
• import numpy as np
• # Using arange in NumPy
• numbers = np.arange(1, 10, 2)
• print(numbers) # Output: [1 3 5 7 9]
Conclusion
• range is built-in and returns a range object, which can be converted to a list.
• arange is part of NumPy and returns a NumPy array, which is more flexible for numerical operations.
• # range example
• numbers_range = range(1, 10, 2)
• print(list(numbers_range)) # Output: [1, 3, 5, 7, 9]
• # arange example
• import numpy as np
• numbers_arange = np.arange(1, 10, 2)
• print(numbers_arange) # Output: [1 3 5 7 9]
Exercises
• Exercise 1:
• Use range to generate a sequence of numbers from 0 to 20 with a step of
3.Convert the range object to a list and print it.
• Exercise 2:
• Use arange to generate an array of numbers from 0 to 20 with a step of
3.Print the resulting array.
Solution
• # Exercise 1
• # Use range to generate a sequence of numbers from 0 to 20 with a step of 3
• sequence = range(0, 21, 3)
• # Convert the range object to a list and print it
• sequence_list = list(sequence)
• print("List from range object:", sequence_list)
Solution
• # Exercise 2
• import numpy as np
• # Use arange to generate an array of numbers from 0 to 20 with a step of 3
• array = np.arange(0, 21, 3)
• # Print the resulting array
• print("Array from arange:", array)
Python Tuples
• Creating Tuples
• Tuples are similar to lists but are immutable, meaning their values cannot be
changed once defined.
• # Creating a tuple
• my_tuple = (1, 2, 3)
• print(my_tuple) # Output: (1, 2, 3)
Python Tuples
• Exercise
• Create a tuple named fruits with the values "apple", "banana", and "cherry“.
• # Your code here
• fruits = ("apple", "banana", "cherry")
• print(fruits)
Python Tuples
• Access Tuple Items
• You can access tuple items using indexing.
• # Accessing tuple items
• my_tuple = (1, 2, 3)
• print(my_tuple[0]) # Output: 1
• print(my_tuple[1]) # Output: 2
Python Tuples
• Access and print the second item in the fruits tuple.
• # Your code here
• print(fruits[1]) # Output: banana
Python Tuples
• Change Tuple Values:
• Tuples are immutable, but you can convert them to a list, change the value, and convert them back to
a tuple.
• # Changing tuple values
• my_tuple = (1, 2, 3)
• temp_list = list(my_tuple)
• temp_list[0] = 4
• my_tuple = tuple(temp_list)
• print(my_tuple) # Output: (4, 2, 3)
Python Tuples
• Exercise:Convert the fruits tuple to a list, change "banana" to "orange", and
convert it back to a tuple.
• # Your code here
• temp_list = list(fruits)
• temp_list[1] = "orange"
• fruits = tuple(temp_list)
• print(fruits) # Output: ('apple', 'orange', 'cherry')
Python Tuples
• Loop Through a TupleYou can loop through the items in a tuple using a for
loop.
• # Looping through a tuple
• my_tuple = (1, 2, 3)
• for item in my_tuple:
• print(item)
Python Tuples
• Check if Item Exists: You can check if an item exists in a tuple using the in
keyword.
• # Check if item exists
• my_tuple = (1, 2, 3)
• print(2 in my_tuple) # Output: True
• print(4 in my_tuple) # Output: False
Python Tuples
• Tuple Length: You can find the length of a tuple using the len() function.
• # Finding tuple length
• my_tuple = (1, 2, 3)
• print(len(my_tuple)) # Output: 3
Python Tuples
• Add Items
• Since tuples are immutable, you cannot add items to an existing tuple. Instead,
you can concatenate tuples.
• # Adding items to a tuple
• my_tuple = (1, 2, 3)
• my_tuple += (4,)
• print(my_tuple) # Output: (1, 2, 3, 4)
Python Tuples
• Remove Items
• Tuples are immutable, so you cannot directly remove items. You can convert the tuple to a list,
remove the item, and convert it back to a tuple.
• # Removing items from a tuple
• my_tuple = (1, 2, 3)
• temp_list = list(my_tuple)
• temp_list.remove(2)
• my_tuple = tuple(temp_list)
• print(my_tuple) # Output: (1, 3)
Python Tuples
• Join Two TuplesYou can join two tuples using the + operator.
• # Joining two tuples
• tuple1 = (1, 2, 3)
• tuple2 = (4, 5, 6)
• result = tuple1 + tuple2
• print(result) # Output: (1, 2, 3, 4, 5, 6)
Exercise
• Add the item "grape" to the fruits tuple.
• Remove "orange" from the fruits tuple.
• Join the fruits tuple with another tuple containing "pear" and "mango".
Dictionary
• Definition: A dictionary is a collection of key-value pairs. Each key is unique and is used
to access its corresponding value.
• student = {
• "name": "Alice",
• "age": 21,
• "major": "Computer Science"
• }
• print(student) # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
Accessing Dictionary Elements
• student = {
• "name": "Alice",
• "age": 21,
• "major": "Computer Science"
• }
• print(student["name"]) # Output: Alice
Using get() Method
• Syntax: dictionary.get(key, default)
• print(student.get("age")) # Output: 21
• print(student.get("GPA", "Not Available")) # Output: Not Available
Modifying Dictionaries
• Syntax: dictionary[key] = value
• student["GPA"] = 3.8 # Adding a new key-value pair
• student["age"] = 22 # Updating an existing key-value pair
• print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer
Science', 'GPA': 3.8}
Removing Elements
• Using del
• del student["GPA"]
• print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science'}
• Using pop()
• age = student.pop("age")
• print(age) # Output: 22
• print(student) # Output: {'name': 'Alice', 'major': 'Computer Science'}
Dictionary Methods
• keys(): Returns a view object containing the dictionary's keys.
• values(): Returns a view object containing the dictionary's values.
• items(): Returns a view object containing the dictionary's key-value pairs.
• update(): Updates the dictionary with the key-value pairs from another
dictionary.
Examples
• keys = student.keys()
• print(keys) # Output: dict_keys(['name', 'major'])
• values = student.values()
• print(values) # Output: dict_values(['Alice', 'Computer Science'])
• items = student.items()
• print(items) # Output: dict_items([('name', 'Alice'), ('major', 'Computer Science')])
• student.update({"age": 22, "GPA": 3.8})
• print(student) # Output: {'name': 'Alice', 'major': 'Computer Science', 'age': 22, 'GPA': 3.8}
Looping Through Dictionaries
• Looping Through Keys
• for key in student:
• print(key, student[key])
• Looping Through Key-Value Pairs
• for key, value in student.items():
• print(key, value)
Exercise-1
• Create a dictionary representing a grocery store inventory with items and their
prices, perform the following operations:
• Add a new item with its price.
• Update the price of an existing item.
• Remove an item from the inventory.
• Print the final inventory.
• N.B. inventory={“apples”:2.99,”bananas:1.99,”orange”:3.24}
Solution-1
• # Initial inventory dictionary
• inventory = {
• "apples": 2.99,
• "bananas": 1.99,
• "oranges": 3.49
• }
• inventory["grapes"] = 4.99
• inventory["bananas"] = 2.49
• del inventory["oranges"]
• for item, price in inventory.items():
• print(f"{item}: ${price:.2f}")
Exercise-2
• Create a dictionary to store information about three students. Each student
should have a dictionary containing their name, age, and grade. Print the
details of each student in a readable format
Solution-2
• # Creating the nested dictionary
• students = {
• "student1": {"name": "John", "age": 20, "grade": "A"},
• "student2": {"name": "Alice", "age": 22, "grade": "B"},
• "student3": {"name": "Bob", "age": 21, "grade": "A-"}
• }
• # Printing the details of each student
• for student_id, student_info in students.items():
• print(f"Details of {student_id}:")
• for key, value in student_info.items():
• print(f" {key}: {value}")
Lambda()
• Definition: lambda functions are small anonymous functions defined using the lambda keyword. They can have
any number of arguments but only one expression. The expression is evaluated and returned.
• Examples:
• # Lambda function to add two numbers
• add = lambda x, y: x + y
• print(add(2, 3)) # Output: 5
• # Lambda function to square a number
• square = lambda x: x**2
• print(square(4)) # Output: 16
Map()
• Definition: The map() function applies a given function to all items in an input list (or any iterable) and returns an iterator
(which can be converted to a list).
• # Using map to double the numbers in a list
• numbers = [1, 2, 3, 4, 5]
• doubled = list(map(lambda x: x * 2, numbers))
• print(doubled) # Output: [2, 4, 6, 8, 10]
• # Using map to convert a list of temperatures from Celsius to Fahrenheit
• celsius = [0, 10, 20, 30]
• fahrenheit = list(map(lambda x: (x * 9/5) + 32, celsius))
• print(fahrenheit) # Output: [32.0, 50.0, 68.0, 86.0]
Filter()
• Definition: The filter() function constructs an iterator from elements of an iterable for which a function returns true.
• # Using filter to get even numbers from a list
• numbers = [1, 2, 3, 4, 5, 6]
• evens = list(filter(lambda x: x % 2 == 0, numbers))
• print(evens) # Output: [2, 4, 6]
• # Using filter to get words longer than 3 characters from a list
• words = ["apple", "it", "banana", "cat"]
• long_words = list(filter(lambda word: len(word) > 3, words))
• print(long_words) # Output: ['apple', 'banana']
Exercises
• Exercise 1: Use map() with lambda: Given a list of numbers, use map() and a
lambda function to create a new list with the square of each number.
• Exercise 2: Use filter() with lambda: Given a list of strings, use filter() and a lambda
function to create a new list with only the strings that contain the letter 'a'.
• Exercise 3: Combine map() and filter(): Given a list of numbers, first use filter() and
a lambda function to create a new list of only the even numbers. Then use map()
and a lambda function to create a new list with the squares of those even numbers.
Solution
• numbers = [1, 2, 3, 4, 5]
• squares = list(map(lambda x: x**2, numbers))
• print(squares) # Output: [1, 4, 9, 16, 25]
• words = ["apple", "banana", "cherry", "date", "fig"]
• words_with_a = list(filter(lambda word: 'a' in word, words))
• print(words_with_a) # Output: ['apple', 'banana', 'date']
Solution
• numbers = [1, 2, 3, 4, 5, 6, 7, 8]
• evens = list(filter(lambda x: x % 2 == 0, numbers))
• squared_evens = list(map(lambda x: x**2, evens))
• print(squared_evens) # Output: [4, 16, 36, 64]
Practical Application
• Task: Given a list of dictionaries representing employees, each with a name
and salary, use map() and a lambda function to give each employee a 10%
raise. Then use filter() and a lambda function to filter out employees with
salaries less than $50,000 after the raise.
Solution
• employees = [
• {"name": "Alice", "salary": 45000},
• {"name": "Bob", "salary": 50000},
• {"name": "Charlie", "salary": 60000}
• ]
• # Giving a 10% raise
• raised_salaries = list(map(lambda e: {"name": e["name"], "salary": e["salary"] * 1.1}, employees))
• print(raised_salaries)
• # Output: [{'name': 'Alice', 'salary': 49500.0}, {'name': 'Bob', 'salary': 55000.0}, {'name': 'Charlie', 'salary': 66000.0}]
• # Filtering out employees with salaries less than $50,000
• high_salaries = list(filter(lambda e: e["salary"] >= 50000, raised_salaries))
• print(high_salaries)
• # Output: [{'name': 'Bob', 'salary': 55000.0}, {'name': 'Charlie', 'salary': 66000.0}]
Error Handling with try, except, and finally
• Error handling is a crucial part of writing robust and error-free code. Python provides a way to handle errors
gracefully using the try, except, and finally blocks.
• try:
• number = int(input("Enter a number: "))
• result = 10 / number
• print(f"The result is {result}")
• except ZeroDivisionError:
• print("Error: Division by zero is not allowed.")
• except ValueError:
• print("Error: Invalid input. Please enter a valid number.")
Using finally
• try:
• file = open('example.txt', 'r')
• content = file.read()
• print(content)
• except FileNotFoundError:
• print("Error: The file does not exist.")
• finally:
• file.close()
• print("The file has been closed.")
Catching Multiple Exceptions
• try:
• data = [1, 2, 3]
• print(data[3]) # This will raise an IndexError
• number = int("abc") # This will raise a ValueError
• except IndexError:
• print("Error: Index out of range.")
• except ValueError:
• print("Error: Invalid value.")
Exercises
• Exercise 1: Write a program that takes two numbers as input from the user
and divides them. Use try and except blocks to handle the
ZeroDivisionError and ValueError exceptions.
• Exercise 2: Write a program that reads a number from the user, converts it to
an integer, and divides 100 by this number. Use nested try and except blocks
to handle ValueError and ZeroDivisionError.
Solution-1
• try:
• num1 = float(input("Enter the first number: "))
• num2 = float(input("Enter the second number: "))
• result = num1 / num2
• print(f"The result is {result}")
• except ZeroDivisionError:
• print("Error: Division by zero is not allowed.")
• except ValueError:
• print("Error: Invalid input. Please enter valid numbers.")
Solution -2
• try:
• num_str = input("Enter a number: ")
• try:
• num = int(num_str)
• result = 100 / num
• print(f"The result is {result}")
• except ZeroDivisionError:
• print("Error: Division by zero is not allowed.")
• except ValueError:
• print("Error: Invalid input. Please enter a valid number.")
Functions and Modules
• Definition: A function is a block of organized, reusable code that is used to
perform a single, related action.
• def function_name(parameters):
• """docstring"""
• statement(s)
• return expression
Example
• def greet(name):
• """This function greets the person whose name is passed as a parameter"""
• return f"Hello, {name}!"
• # Calling the function
• print(greet("Alice")) # Output: Hello, Alice!
Working with Modules and Packages
• A module is a file containing Python definitions and statements. The file
name is the module name with the suffix .py added.
# Save this as my_module.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# Importing and using the module
import my_module
print(my_module.add(5, 3)) #
Output: 8
print(my_module.subtract(5, 3)) #
Output: 2
Packages
• A package is a way of collecting related modules together within a single tree-
like hierarchy. They are just directories containing a special __init__.py file.
• # Importing and using the package
• from my_package import module1, module2
• print(module1.function_in_module1())
• print(module2.function_in_module2())
Importing and Using Third-Party Libraries
• These are external modules and packages that are not included in the Python
Standard Library but can be installed using a package manager like pip.
Exercises
• Write a function factorial that takes a positive integer and returns its factorial
• Create a module math_operations.py with functions to add, subtract,
multiply, and divide two numbers. Import this module in another script and
use these functions.
• Install and use the numpy library to create an array and perform basic
arithmetic operations.
Solution-1
• def factorial(n):
• """This function returns the factorial of a given number."""
• if n == 0:
• return 1
• else:
• return n * factorial(n-1)
• print(factorial(5)) # Output: 120
Solution-2
• # math_operations.py
• def add(a, b):
• return a + b
• def subtract(a, b):
• return a - b
• def multiply(a, b):
• return a * b
• def divide(a, b):
• if b != 0:
• return a / b
• else:
• return "Division by zero is not allowed"
Solution-2
• # main.py
• import math_operations as mo
• print(mo.add(10, 5)) # Output: 15
• print(mo.subtract(10, 5)) # Output: 5
• print(mo.multiply(10, 5)) # Output: 50
• print(mo.divide(10, 5)) # Output: 2.0
• print(mo.divide(10, 0)) # Output: Division by zero is not allowed
Soluiotn-3
• import numpy as np
• # Creating a numpy array
• arr = np.array([1, 2, 3, 4, 5])
• # Performing arithmetic operations
• print(arr + 5) # Output: [ 6 7 8 9 10]
• print(arr * 2) # Output: [ 2 4 6 8 10]
Object-Oriented Programming
• Definition:
• Class: A blueprint for creating objects. It defines a set of attributes and
methods that the created objects will have.
• Object: An instance of a class.
Example
Inheritance and Polymorphism
• Inheritance allows a class (called the child class) to inherit attributes and
methods from another class (called the parent class).
• class ParentClass:
• # parent class implementation
• class ChildClass(ParentClass):
• # child class implementation
Example
Inheritance and Polymorphism
• Polymorphism allows methods to do different things based on the object it is
acting upon. In the example above, the speak method is polymorphic,
behaving differently depending on whether the object is an instance of Dog
or Cat.
Advanced Class Features
• Class Methods:
• Class methods are methods that are bound to the class and not the instance. They can modify the class state that applies
across all instances of the class.
• class Dog:
• species = "Canis familiaris"
• @classmethod
• def get_species(cls):
• return cls.species
• print(Dog.get_species()) # Output: Canis familiaris
Static Methods:
• Static methods are methods that do not operate on an instance or the class. They are
utility-type methods that can be called on the class itself.
• class Math:
• @staticmethod
• def add(a, b):
• return a + b
• print(Math.add(5, 3)) # Output: 8
Properties
• Properties are a way of customizing access to instance attributes. They can be used to add logic to getting and
setting a value.
• class ClassName:
• @property
• def property_name(self):
• # getter method
• @property_name.setter
• def property_name(self, value):
• # setter method
Properties
Exercises
• Exercise 1: Create a class Car with attributes make, model, and year. Add a
method description that returns a formatted string describing the car.
• Exercise 2: Create a base class Person with attributes name and age. Create a
derived class Employee that inherits from Person and adds an attribute
employee_id. Add a method to the Employee class that returns the employee's
details.
Exercises
• Exercise 3: Create a class Temperature with a class attribute unit set to
"Celsius". Add a class method change_unit to change the unit to
"Fahrenheit". Add a static method convert_to_fahrenheit that converts a
temperature from Celsius to Fahrenheit.
• Exercise 4: Create a class Rectangle with attributes width and height. Add a
property area that calculates and returns the area of the rectangle. Add a
property perimeter that calculates and returns the perimeter.
Soluiton-1
Solution-2
Solution-3
Solution-4
Advanced Data Structures (Sets, Queues,
Stacks)
• Sets
• A set is a collection of unique elements. Sets are useful for membership tests,
removing duplicates, and performing mathematical set operations like union,
intersection, and difference.
• Examples
• Go pycharm
Example
Queues
• A queue is a collection where elements are added from one end and removed from the other (FIFO: First In, First Out).
• from collections import deque
• # Creating a queue
• queue = deque()
• # Enqueuing elements
• queue.append(1)
• queue.append(2)
• queue.append(3)
• print(queue) # Output: deque([1, 2, 3])
• # Dequeuing elements
• queue.popleft()
• print(queue) # Output: deque([2, 3])
Stacks
• A stack is a collection where elements are added and removed from the same end (LIFO: Last In, First Out).
• # Creating a stack
• stack = []
• # Pushing elements onto the stack
• stack.append(1)
• stack.append(2)
• stack.append(3)
• print(stack) # Output: [1, 2, 3]
• # Popping elements from the stack
• stack.pop()
• print(stack) # Output: [1, 2]
Exercises
• Write a function that takes two lists and returns a set containing the common
elements (intersection) and another set containing all unique elements from both lists
(union).
• Implement a stack using a list. The stack should support the following operations:
push (add an element to the top), pop (remove and return the top element), and peek
(return the top element without removing it).
• Implement a queue using a list (or deque). The queue should support the following
operations: enqueue (add an element to the end), dequeue (remove and return the
element from the front), and front (return the front element without removing it).
Solution-1
• def set_operations(list1, list2):
• set1 = set(list1)
• set2 = set(list2)
• intersection = set1.intersection(set2)
• union = set1.union(set2)
• return intersection, union
• # Example usage
• list1 = [1, 2, 3, 4, 5]
• list2 = [4, 5, 6, 7, 8]
• intersection, union = set_operations(list1, list2)
• print("Intersection:", intersection) # Output: {4, 5}
• print("Union:", union) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
Solution-2
• class Stack:
• def __init__(self):
• self.stack = []
• def push(self, item):
• self.stack.append(item)
• def pop(self):
• if len(self.stack) == 0:
• return "Stack is empty"
• return self.stack.pop()
• def peek(self):
• if len(self.stack) == 0:
• return "Stack is empty"
• return self.stack[-1]
• def is_empty(self):
• return len(self.stack) == 0
• # Example usage
• stack = Stack()
• stack.push(1)
• stack.push(2)
• stack.push(3)
• print(stack.peek()) # Output: 3
• print(stack.pop()) # Output: 3
• print(stack.peek()) # Output: 2
Solution-3
• from collections import deque
• class Queue:
• def __init__(self):
• self.queue = deque()
• def enqueue(self, item):
• self.queue.append(item)
• def dequeue(self):
• if len(self.queue) == 0:
• return "Queue is empty"
• return self.queue.popleft()
• def front(self):
• if len(self.queue) == 0:
• return "Queue is empty"
• return self.queue[0]
• def is_empty(self):
• return len(self.queue) == 0
• # Example usage
• queue = Queue()
• queue.enqueue(1)
• queue.enqueue(2)
• queue.enqueue(3)
• print(queue.front()) # Output: 1
• print(queue.dequeue()) # Output: 1
• print(queue.front()) # Output: 2
File Handling
• Text files are the most common types of files used to store data. Python
provides built-in functions to read from and write to text files.
File Handling and Data Serialization
Exercise
• Create a text file named myfile.txt and write a few lines of text into it.
• Read the content of myfile.txt and print it to the console.
• Append a new line to myfile.txt and print the updated content.
Solution
• with open('myfile.txt', 'w') as file:
• file.write("Line 1: Hello, world!n")
• file.write("Line 2: Welcome to file
handling in Python.n")
• with open('myfile.txt', 'r') as file:
• content = file.read()
• print("Content of myfile.txt:")
• print(content)
• with open('myfile.txt', 'a') as file:
• file.write("Line 3: Appending a new
line.n")
• with open('myfile.txt', 'r') as file:
• updated_content = file.read()
• print("Updated content of myfile.txt:")
• print(updated_content)
CSV manipulation
• CSV (Comma-Separated Values) files are used to store tabular data. The
pandas library provides powerful functionality to read from and write to CSV
files using DataFrames.
CSV manipulation
CSV manipulation
Exercise
• Create a CSV file named students.csv with columns Name, Age, and Grade
using a pandas DataFrame.
• Write at least three rows of data into students.csv.
• Read the content of students.csv into a pandas DataFrame and print it to the
console.
• Add a new row to the students.csv file and print the updated DataFrame.
Solution
• import pandas as pd
• data = {
• 'Name': ['Alice', 'Bob', 'Charlie'],
• 'Age': [20, 21, 22],
• 'Grade': ['A', 'B', 'C']
• }
• df = pd.DataFrame(data)
• df.to_csv('students.csv', index=False)
• df = pd.read_csv('students.csv')
• print(df)
• new_data = pd.DataFrame({'Name': ['David'],
'Age': [23], 'Grade': ['B']})
• df = pd.concat([df, new_data],
ignore_index=True)
• df.to_csv('students.csv', index=False)
• print("Updated content of students.csv:")
• print(df)
Pandas dataframe
• One of the most powerful and commonly used data structures in pandas.
• Creating DataFrames
• From a Dictionary
• From a List of Dictionaries
• From a CSV File
From a dictionary
• import pandas as pd
• data = {
• 'Name': ['Alice', 'Bob', 'Charlie'],
• 'Age': [25, 30, 35],
• 'City': ['New York', 'Los Angeles', 'Chicago']
• }
• df = pd.DataFrame(data)
• print(df)
From a list of dictionaries
• data = [
• {'Name': 'Alice', 'Age': 25, 'City': 'New York'},
• {'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'},
• {'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
• ]
• df = pd.DataFrame(data)
• print(df)
Exercise
• Create a DataFrame from a dictionary with the columns Product, Price, and
Quantity.
• Create a DataFrame from a list of dictionaries with the columns Student,
Grade, and Subject.
• Read a CSV file named sales.csv into a DataFrame and print the first 5 rows.
Solution
• import pandas as pd
• data = {
• 'Product': ['Apples', 'Bananas', 'Cherries'],
• 'Price': [1.2, 0.5, 3.0],
• 'Quantity': [10, 20, 15]
• }
• df1 = pd.DataFrame(data)
• print("DataFrame from dictionary:")
• print(df1)
• data = [
• {'Student': 'Alice', 'Grade': 'A', 'Subject': 'Math'},
• {'Student': 'Bob', 'Grade': 'B', 'Subject': 'Science'},
• {'Student': 'Charlie', 'Grade': 'C', 'Subject': 'History'}
• ]
• df2 = pd.DataFrame(data)
• print("nDataFrame from list of dictionaries:")
• print(df2)
• df3 = pd.read_csv('sales.csv')
• print("nFirst 5 rows of sales.csv:")
• print(df3.head())
Viewing Data
Exercise
• Print the first 3 rows of a DataFrame.
• Select and print the Product column from a DataFrame.
• Select and print rows where the Price is greater than 50.
Solution
• import pandas as pd
• # Sample DataFrame for demonstration
• data = {
• 'Product': ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries'],
• 'Price': [1.2, 0.5, 3.0, 10.0, 50.5],
• 'Quantity': [10, 20, 15, 5, 2]
• }
• df = pd.DataFrame(data)
• # Solution 1: Printing the first 3 rows
• print("First 3 rows of DataFrame:")
• print(df.head(3))
• # Solution 2: Selecting and printing the 'Product' column
• print("n'Product' column of DataFrame:")
• print(df['Product'])
• # Solution 3: Selecting and printing rows where the 'Price'
is greater than 50
• print("nRows where 'Price' is greater than 50:")
• print(df[df['Price'] > 50])
Data manipulation
• Add a new column Total to a DataFrame, which is the product of Price and
Quantity.
• Rename the Product column to Item in a DataFrame.
• Fill missing values in a DataFrame with the mean of the column.
Exercise
• import pandas as pd
• # Sample DataFrame for demonstration
• data = {
• 'Product': ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries'],
• 'Price': [1.2, 0.5, 3.0, 10.0, 50.5],
• 'Quantity': [10, 20, 15, 5, 2]
• }
• df = pd.DataFrame(data)
• df['Total'] = df['Price'] * df['Quantity']
• print("DataFrame with 'Total' column added:")
• print(df)
• df = df.rename(columns={'Product': 'Item'})
• print("nDataFrame with 'Product' column renamed to 'Item':")
• print(df)
• # Creating a sample DataFrame with missing values for Solution 3
• data_with_na = {
• 'Product': ['Apples', 'Bananas', 'Cherries'],
• 'Price': [1.2, None, 3.0],
• 'Quantity': [10, 20, None]
• }
• df_na = pd.DataFrame(data_with_na)
• # Solution 3: Filling missing values with the mean of the column
• df_na['Price'] = df_na['Price'].fillna(df_na['Price'].mean())
• df_na['Quantity'] = df_na['Quantity'].fillna(df_na['Quantity'].mean())
• print("nDataFrame with missing values filled with column mean:")
• print(df_na)
Python with DB
• Connecting to a MySQL Database with Python.
• Basic Operations:
• Connecting to the Database
• Creating a Table
• Inserting Data
• Querying Data
• Updating Data
• Deleting Data
Connecting to the Database
• import mysql.connector
• # Establish the connection
• conn = mysql.connector.connect(
• host="localhost",
• user="yourusername",
• password="yourpassword",
• database="yourdatabase"
• )
• # Create a cursor object
• cursor = conn.cursor()
Creating a Table
• create_table_query = """
• CREATE TABLE employees (
• id INT AUTO_INCREMENT PRIMARY KEY,
• name VARCHAR(255),
• position VARCHAR(255),
• salary DECIMAL(10, 2)
• )
• """
• cursor.execute(create_table_query)
Inserting Data
• insert_query = """
• INSERT INTO employees (name, position, salary)
• VALUES (%s, %s, %s)
• """
• data = ("John Doe", "Software Engineer", 75000)
• cursor.execute(insert_query, data)
• conn.commit()
Querying Data
• select_query = "SELECT * FROM employees"
• cursor.execute(select_query)
• results = cursor.fetchall()
• for row in results:
• print(row)
Deleting Data
• delete_query = "DELETE FROM employees WHERE name = %s"
• data = ("John Doe",)
• cursor.execute(delete_query, data)
• conn.commit()
Exercises
• Exercise 1: Create a new database and a table for storing student records.
Insert, update, and query data in the table.
• Exercise 2: Write a Python script that connects to the database and retrieves
records based on specific criteria (e.g., all employees with a salary greater than
a certain amount).
• Exercise 3: Implement a function to delete records older than a certain date
from a table.
Solution1-Create a new database and table
• import mysql.connector
• # Establish the connection
• conn = mysql.connector.connect(
• host="localhost",
• user="yourusername",
• password="yourpassword"
• )
• # Create a cursor object
• cursor = conn.cursor()
• # Create a new database
• cursor.execute("CREATE DATABASE
student_records")
• # Select the database
• conn.database = 'student_records'
• # Create a table
• create_table_query = """
• CREATE TABLE students (
• id INT AUTO_INCREMENT PRIMARY KEY,
• name VARCHAR(255),
• age INT,
• major VARCHAR(255)
• )
• """
• cursor.execute(create_table_query)
• conn.commit()
• # Close the connection
• cursor.close()
• conn.close()
Solution1-Insert data into the table
• import mysql.connector
• conn = mysql.connector.connect(
• host="localhost",
• user="yourusername",
• password="yourpassword",
• database="student_records"
• )
• cursor = conn.cursor()
• insert_query = """
• INSERT INTO students (name, age, major)
• VALUES (%s, %s, %s)
• """
• students = [
• ("Alice Smith", 20, "Computer Science"),
• ("Bob Johnson", 22, "Mathematics"),
• ("Carol Williams", 19, "Biology")
• ]
• cursor.executemany(insert_query, students)
• conn.commit()
• cursor.close()
• conn.close()
Solution1-Query data from the table
• select_query = "SELECT * FROM students"
• cursor.execute(select_query)
• results = cursor.fetchall()
• for row in results:
• print(row)
• cursor.close()
• conn.close()
Solution1-Update data in the table
• update_query = """
• UPDATE students
• SET major = %s
• WHERE name = %s
• """
• data = ("Data Science", "Alice Smith")
• cursor.execute(update_query, data)
• conn.commit()
• cursor.close()
• conn.close()
Solution1-Delete data from the table
• delete_query = "DELETE FROM students WHERE name = %s"
• data = ("Bob Johnson",)
• cursor.execute(delete_query, data)
• conn.commit()
• cursor.close()
• conn.close()
Solution2
• select_query = "SELECT * FROM students WHERE age > %s"
• age = (20,)
• cursor.execute(select_query, age)
• results = cursor.fetchall()
• for row in results:
• print(row)
• cursor.close()
• conn.close()
Solution3
• delete_query = "DELETE FROM students WHERE age < %s"
• age_limit = (21,)
• cursor.execute(delete_query, age_limit)
• conn.commit()
• cursor.close()
• conn.close()
Extra Exercises
• Exercise 1: Write a program that prints the numbers from 1 to 50. But for
multiples of three, print “Three" instead of the number, and for the
multiples of five, print “Five". For numbers which are multiples of both
three and five, print “ThreeFive".
• Exercise 2: Write a program that calculates the sum of all numbers from 1 to
100 that are divisible by 4.
• Exercise 3: Write a program to find the maximum and minimum elements in
a list.
Extra Exercises
• Exercise 4: Write a program to merge two tuples and sort them.
• Exercise 5: Write a program to count the frequency of each character in a
given string.
• Exercise 6: Create a class BankAccount with attributes account_number and
balance. Define methods to deposit and withdraw money from the account.
• Exercise 7: Write a program to filter rows in a DataFrame where a specific
column value is greater than a given number.
Extra Exercises
• Exercise 8: Write a Python script to connect to a MySQL database and create
a table.
• Exercise 9: Write a Python script to insert data into a MySQL table and fetch
all records.

More Related Content

Similar to Python for beginner, learn python from scratch.pptx (20)

PPTX
Review old Pygame made using python programming.pptx
ithepacer
 
PPTX
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
PPTX
Presgfdjfwwwwwwwwwwqwqeeqentation11.pptx
aarohanpics
 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
PPTX
Basics of Python Programming
ManishJha237
 
PPTX
Python basics
TIB Academy
 
PDF
Revision for Python for Artificial Intelligence Labs
Faculty of Computers and Artificial Intelligence
 
PPTX
UNIT 1 .pptx
Prachi Gawande
 
PDF
Introduction to Python for Plone developers
Jim Roepcke
 
PPTX
modul-python-all.pptx
Yusuf Ayuba
 
PPTX
Introduction To Python.pptx
Anum Zehra
 
PPTX
Lecture 1 .
SwatiHans10
 
PPT
Exception handling and function in python
TMARAGATHAM
 
PPTX
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
PDF
AmI 2015 - Python basics
Luigi De Russis
 
PPTX
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
PDF
Python Programming
Saravanan T.M
 
PPTX
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
PPTX
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
PPTX
Lec2_cont.pptx galgotias University questions
YashJain47002
 
Review old Pygame made using python programming.pptx
ithepacer
 
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
Presgfdjfwwwwwwwwwwqwqeeqentation11.pptx
aarohanpics
 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Basics of Python Programming
ManishJha237
 
Python basics
TIB Academy
 
Revision for Python for Artificial Intelligence Labs
Faculty of Computers and Artificial Intelligence
 
UNIT 1 .pptx
Prachi Gawande
 
Introduction to Python for Plone developers
Jim Roepcke
 
modul-python-all.pptx
Yusuf Ayuba
 
Introduction To Python.pptx
Anum Zehra
 
Lecture 1 .
SwatiHans10
 
Exception handling and function in python
TMARAGATHAM
 
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
AmI 2015 - Python basics
Luigi De Russis
 
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Python Programming
Saravanan T.M
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
#Code2Create: Python Basics
GDGKuwaitGoogleDevel
 
Lec2_cont.pptx galgotias University questions
YashJain47002
 

Recently uploaded (20)

PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
Introduction presentation of the patentbutler tool
MIPLM
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Controller Request and Response in Odoo18
Celine George
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Ad

Python for beginner, learn python from scratch.pptx

  • 2. Outlines • Topic 1: Introduction to Python • Topic 2: Python Operators • Topic 3: Variables • Topic 4: Conditional Statements • Topic 5: Iteration • Topic 6: Python Lists • Topic 7: Python Tuples • Topic 8: Advanced Control Flow
  • 3. Outlines • Topic 9: Functions and Modules • Topic 10: Object-Oriented Programming • Topic 11: Data Structures and Algorithms • Topic 12: File Handling and Data Serialization • Topic 13: Final Project
  • 4. Let’s GO • Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. • It is used for: • web development (server-side), • software development, • mathematics, • system scripting.
  • 5. What can Python do? • Python can be used on a server to create web applications. • Python can be used alongside software to create workflows. • Python can connect to database systems. It can also read and modify files. • Python can be used to handle big data and perform complex mathematics.
  • 6. Why Python? • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). • Python has a simple syntax similar to the English language. • Python has syntax that allows developers to write programs with fewer lines than some other programming languages. • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. • Python can be treated in a procedural way, an object-oriented way or a functional way.
  • 7. Python Getting Started • Pycharm: https://www.jetbrains.com/pycharm/download/other.html • Google Colab https://colab.google/ • print("Hello, World!")
  • 8. Execute Python Syntax • Python Indentation: Indentation refers to the spaces at the beginning of a code line.
  • 9. Python Variables • In python, variables are created when you assign a value to it. • x = 5 y = "Hello, World!" • Python has commenting capability for the purpose of in-code documentation. • Comments start with a #, and Python will render the rest of the line as a comment: • #This is a comment. print("Hello, World!")
  • 10. Python Variables • Python has no command for declaring a variable. • Variables do not need to be declared with any particular type, and can even change type after they have been set. • x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
  • 11. Casting • If you want to specify the data type of a variable, this can be done with casting. • x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0
  • 12. Get the Type • You can get the data type of a variable with the type() function. • x = 5 y = "John" print(type(x)) print(type(y)) • Single or Double Quotes? • x = "John" # is the same as x = 'John'
  • 13. Case-Sensitive • Variable names are case-sensitive. • a = 4 A = "Sally" #A will not overwrite a
  • 14. Variable Names • Rules for Python variables: A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables) • A variable name cannot be any of the Python keywords.
  • 16. Variable Names • Camel Case: Each word, except the first, starts with a capital letter: • myVariableName = "John" • Pascal Case: Each word starts with a capital letter: • MyVariableName = "John" • Snake Case: Each word is separated by an underscore character: • my_variable_name = "John"
  • 17. Python Variables - Assign Multiple Values • Many Values to Multiple Variables: Python allows you to assign values to multiple variables in one line: • x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) • One Value to Multiple Variables: And you can assign the same value to multiple variables in one line: • x = y = z = "Orange" print(x) print(y) print(z)
  • 18. Python Variables - Assign Multiple Values • Unpack a Collection: If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. • fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z)
  • 19. Python - Output Variables • The Python print() function is often used to output variables. • x = "Python is awesome" print(x) • x = "Python" y = "is" z = "awesome" print(x, y, z)
  • 20. Python - Output Variables • The Python print() function is often used to output variables. • x = "Python " y = "is " z = "awesome" print(x + y + z) • x = 5 y = 10 print(x + y)
  • 21. Python - Output Variables
  • 22. Python - Global Variables
  • 23. Python - Global Variables
  • 26. Test your knowledge • https:// www.w3schools.com/python/exercise.asp?filename=exercise_variables1
  • 27. Exercises • Create variables with valid names for a person's first name, last name, age, and whether they are a student. Assign appropriate values to these variables and print them. • Assign the values 10, 20, and 30 to the variables x, y, and z respectively in a single line. Print the values of these variables. • Define a global variable named counter. Create a function that increments this counter by 1 each time it is called. Call this function twice and print the value of the counter after each call.
  • 28. Exercises • Create variables with valid names for a person's first name, last name, age, and whether they are a student. Assign appropriate values to these variables and print them. • Assign the values 10, 20, and 30 to the variables x, y, and z respectively in a single line. Print the values of these variables. • Define a global variable named counter. Create a function that increments this counter by 1 each time it is called. Call this function twice and print the value of the counter after each call.
  • 29. User-input variables • User input variables are variables that store data provided by the user during the execution of a program. • In Python, the input() function is used to get input from the user. The data entered by the user is typically stored in a variable for further use in the program.
  • 31. Python Operators • Python Numbers • Python supports several types of numeric data: • Integers (int): Whole numbers, positive or negative, without a decimal point. • Floats (float): Numbers that contain a decimal point. • Complex numbers (complex): Numbers with a real and imaginary part.
  • 32. Python Arithmetic Operators • Arithmetic operators are used to perform mathematical operations. • + (Addition) • - (Subtraction) • * (Multiplication) • / (Division) • % (Modulus) • ** (Exponentiation) • // (Floor Division)
  • 33. Python Comparison Operators • Comparison operators are used to compare two values and return a Boolean result (True or False). • == (Equal to) • != (Not equal to) • > (Greater than) • < (Less than) • >= (Greater than or equal to) • <= (Less than or equal to)
  • 34. Python Logical Operators • Logical operators are used to combine conditional statements. • and (Logical AND) • or (Logical OR) • not (Logical NOT)
  • 35. Exercise • Given the following values: • a = 7 • b = 4 • c = 9 • Calculate the sum of a and b. • Calculate the product of b and c. • Check if a is equal to b. • Check if c is greater than a. • Use a logical AND operator to check if a is greater than b and c is greater than a. • Use a logical OR operator to check if a is greater than b or c is less than b.
  • 36. Conditional Statements in Python • Types of Conditional Statements • if statement • if-else statement • elif statement • Nested conditional statements
  • 37. if statement • The if statement is used to test a specific condition. If the condition is true, the block of code inside the if statement is executed. • age = 18 • if age >= 18: • print("You are an adult.")
  • 38. if-else statement • The if-else statement adds an alternative path of execution when the condition is false. • age = 16 • if age >= 18: • print("You are an adult.") • else: • print("You are not an adult.")
  • 39. elif statement • The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions is true. • score = 85 • if score >= 90: • print("Grade: A") • elif score >= 80: • print("Grade: B") • elif score >= 70: • print("Grade: C") • else: • print("Grade: F")
  • 40. Nested conditional statements • You can use one if or else if statement inside another if or else if statement(s). • num = 10 • if num > 0: • if num % 2 == 0: • print("Positive and Even") • else: • print("Positive but Odd") • else: • print("Negative")
  • 41. Exercises • Write a program that asks the user to input their age. If they are 18 or older, print "You are eligible to vote.“ • Write a program that asks the user to input a number. Print whether the number is positive or negative. • Write a program that asks the user for their exam score, and print the corresponding grade (A, B, C, F). • Write a program that checks whether a given year is a leap year. A year is a leap year if it is divisible by 4 but not 100, except if it is also divisible by 400.
  • 42. Solution-1 • age = int(input("Enter your age: ")) • if age >= 18: • print("You are eligible to vote.")
  • 43. Solution-2 • number = float(input("Enter a number: ")) • if number >= 0: • print("The number is positive.") • else: • print("The number is negative.")
  • 44. Solution-3 • score = int(input("Enter your score: ")) • if score >= 90: • print("Grade: A") • elif score >= 80: • print("Grade: B") • elif score >= 70: • print("Grade: C") • else: • print("Grade: F")
  • 45. Solution-4 • year = int(input("Enter a year: ")) • if year % 4 == 0: • if year % 100 == 0: • if year % 400 == 0: • print(f"{year} is a leap year.") • else: • print(f"{year} is not a leap year.") • else: • print(f"{year} is a leap year.") • else: • print(f"{year} is not a leap year.")
  • 46. Iteration • Iteration is a fundamental concept in programming where a sequence of instructions is repeated until a certain condition is met. • Python supports several constructs to implement iteration, such as loops. • Types of Iteration • for loop • while loop • Nested loops
  • 47. For loop • The for loop in Python is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). • fruits = ["apple", "banana", "cherry"] • for fruit in fruits: • print(fruit)
  • 48. While loop • The while loop in Python repeatedly executes a block of code as long as the condition is true. • count = 0 • while count < 5: • print(count) • count += 1
  • 49. Nested loop • Nested loops are loops within loops. The inner loop runs to completion each time the outer loop runs once. • for i in range(3): • for j in range(2): • print(f"i = {i}, j = {j}")
  • 50. Loop Control Statements • Break: Exits the loop prematurely. • Continue: Skips the current iteration and moves to the next iteration.
  • 51. Examples • for i in range(10): • if i == 5: • break • print(i) • -------------------------------------------------------------------------------------------------- • for i in range(10): • if i % 2 == 0: • continue • print(i)
  • 52. Exercises • Write a program to iterate over a list of numbers and print only the even numbers. • Write a program that calculates the factorial of a given number n. • Write a program to print a multiplication table for numbers from 1 to 5. • Write a program that iterates over numbers from 1 to 10, but skips the number 5 using continue, and stops the loop if the number is 8 using break.
  • 53. Python Lists • A list is a collection which is ordered and changeable. In Python, lists are written with square brackets. • # Creating a list • fruits = ["apple", "banana", "cherry"] • print(fruits) • Create a list named colors that contains at least 5 different color names.
  • 54. Python Lists • You can access list items by referring to the index number, inside square brackets. Note that list indices start at 0. • # Accessing an item • fruits = ["apple", "banana", "cherry"] • print(fruits[1]) # Output: banana • Access the third item in the colors list you created.
  • 55. Python Lists • You can change the value of a specific item by referring to its index. • # Changing item value • fruits = ["apple", "banana", "cherry"] • fruits[1] = "blueberry" • print(fruits) # Output: ['apple', 'blueberry', 'cherry'] • Change the second color in your colors list to "magenta".
  • 56. Python Lists • You can loop through the list items by using a for loop. • # Looping through a list • fruits = ["apple", "banana", "cherry"] • for f in fruits: • print(f) • Write a loop that prints each color in your colors list.
  • 57. Python Lists • To determine if a specified item is present in a list use the in keyword. • # Checking if item exists • fruits = ["apple", "banana", "cherry"] • if "banana" in fruits: • print("Banana is in the list") • Check if the color "blue" is in your colors list and print an appropriate message.
  • 58. Python Lists • To determine how many items a list has, use the len() function. • # Getting the length of a list • fruits = ["apple", "banana", "cherry"] • print(len(fruits)) # Output: 3 • Print the length of your colors list.
  • 59. Python Lists • To add an item to the end of the list, use the append() method. • # Adding an item • fruits = ["apple", "banana", "cherry"] • fruits.append("orange") • print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange'] • Add a new color to your colors list.
  • 60. Python Lists • There are several methods to remove items from a list: • remove(): Removes the first item with the specified value. • pop(): Removes the item at the specified position. • del: Removes the item at the specified index or the entire list. • clear(): Empties the list.
  • 61. Python Lists • # Removing an item using remove() • fruits = ["apple", "banana", "cherry"] • fruits.remove("banana") • print(fruits) # Output: ['apple', 'cherry'] • # Removing an item using pop() • fruits.pop(1) • print(fruits) # Output: ['apple']
  • 62. Python Lists • # Removing an item using del • del fruits[0] • print(fruits) # Output: [] • # Clearing the list • fruits = ["apple", "banana", "cherry"] • fruits.clear() • print(fruits) # Output: [] • Remove the first color from your colors list.
  • 63. Python Lists • You can copy a list using the copy() method or by using list slicing. • # Copying a list using copy() • fruits = ["apple", "banana", "cherry"] • fruits_copy = fruits.copy() • print(fruits_copy) # Output: ['apple', 'banana', 'cherry'] • # Copying a list using slicing • fruits_copy = fruits[:] • print(fruits_copy) # Output: ['apple', 'banana', 'cherry']
  • 64. Python Lists • You can join two lists using the + operator or the extend() method. • # Joining two lists using + • list1 = ["a", "b", "c"] • list2 = [1, 2, 3] • joined_list = list1 + list2 • print(joined_list) # Output: ['a', 'b', 'c', 1, 2, 3] • # Joining two lists using extend() • list1.extend(list2) • print(list1) # Output: ['a', 'b', 'c', 1, 2, 3]
  • 65. Python Lists • Create a copy of your colors list. • Join your colors list with a new list more_colors containing at least 3 different colors.
  • 66. Arrays • An array is a data structure that can hold multiple values at once. • Unlike lists, arrays are designed to store only one type of data. • Arrays are useful for numerical operations and scientific computing.
  • 67. Creating Arrays • Import the array module. • Define the type code (e.g., 'i' for integers, 'f' for floats). • Provide initial values. • import array as arr • # Creating an array of floats • floats = arr.array('f', [1.1, 2.2, 3.3]) • print(floats)
  • 68. Accessing Array Elements • Access elements using their index. • Indexing starts at 0. • import array as arr • numbers = arr.array('i', [1, 2, 3, 4, 5]) • print(numbers[0]) # Output: 1 • print(numbers[2]) # Output: 3
  • 69. Modifying Arrays • Change the value of an array element by accessing its index. • import array as arr • numbers = arr.array('i', [1, 2, 3, 4, 5]) • numbers[1] = 10 • print(numbers) # Output: array('i', [1, 10, 3, 4, 5])
  • 70. Array Operations • You can perform various operations like adding, removing, and slicing elements. • import array as arr • numbers = arr.array('i', [1, 2, 3, 4, 5]) • # Adding elements • numbers.append(6) • print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6]) • # Removing elements • numbers.pop(2) • print(numbers) # Output: array('i', [1, 2, 4, 5, 6])
  • 71. Array Slicing • Access a range of elements using slicing. • import array as arr • numbers = arr.array('i', [1, 2, 3, 4, 5]) • print(numbers[1:4]) # Output: array('i', [2, 3, 4])
  • 72. Looping Through Arrays • Use loops to iterate over array elements. • import array as arr • numbers = arr.array('i', [1, 2, 3, 4, 5]) • for num in numbers: • print(num)
  • 73. Exercises • Exercise 1: • Create an array of integers from 1 to 10. • Replace the value at index 5 with 50. • Print the updated array. • Exercise 2: • Create an array of floats: [1.5, 2.5, 3.5, 4.5]. • Append the value 5.5 to the array. • Remove the value at index 2. • Print the final array.
  • 74. Solutions • # Exercise 1 • import numpy as np • # Create an array of integers from 1 to 10 • array1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) • print("Original array:", array1) • # Replace the value at index 5 with 50 • array1[5] = 50 • print("Updated array:", array1)
  • 75. Solutions • # Exercise 2 • # Create an array of floats: [1.5, 2.5, 3.5, 4.5] • array2 = np.array([1.5, 2.5, 3.5, 4.5]) • print("Original array:", array2) • # Append the value 5.5 to the array • array2 = np.append(array2, 5.5) • print("Array after appending 5.5:", array2) • # Remove the value at index 2 • array2 = np.delete(array2, 2) • print("Final array:", array2)
  • 76. Difference between range and arange • range is a built-in Python function that generates a sequence of numbers. • arange is a function in the NumPy library that generates arrays. • Using Range: • range(start, stop, step) generates a sequence of numbers from start to stop - 1 with a step size of step. • range returns a range object, not an array or list.
  • 77. range • # Using range in Python • numbers = range(1, 10, 2) • print(numbers) # Output: range(1, 10, 2) • print(list(numbers)) # Output: [1, 3, 5, 7, 9]
  • 78. Arange • arange(start, stop, step) generates an array of numbers from start to stop with a step size of step. • arange returns a NumPy array. • import numpy as np • # Using arange in NumPy • numbers = np.arange(1, 10, 2) • print(numbers) # Output: [1 3 5 7 9]
  • 79. Conclusion • range is built-in and returns a range object, which can be converted to a list. • arange is part of NumPy and returns a NumPy array, which is more flexible for numerical operations. • # range example • numbers_range = range(1, 10, 2) • print(list(numbers_range)) # Output: [1, 3, 5, 7, 9] • # arange example • import numpy as np • numbers_arange = np.arange(1, 10, 2) • print(numbers_arange) # Output: [1 3 5 7 9]
  • 80. Exercises • Exercise 1: • Use range to generate a sequence of numbers from 0 to 20 with a step of 3.Convert the range object to a list and print it. • Exercise 2: • Use arange to generate an array of numbers from 0 to 20 with a step of 3.Print the resulting array.
  • 81. Solution • # Exercise 1 • # Use range to generate a sequence of numbers from 0 to 20 with a step of 3 • sequence = range(0, 21, 3) • # Convert the range object to a list and print it • sequence_list = list(sequence) • print("List from range object:", sequence_list)
  • 82. Solution • # Exercise 2 • import numpy as np • # Use arange to generate an array of numbers from 0 to 20 with a step of 3 • array = np.arange(0, 21, 3) • # Print the resulting array • print("Array from arange:", array)
  • 83. Python Tuples • Creating Tuples • Tuples are similar to lists but are immutable, meaning their values cannot be changed once defined. • # Creating a tuple • my_tuple = (1, 2, 3) • print(my_tuple) # Output: (1, 2, 3)
  • 84. Python Tuples • Exercise • Create a tuple named fruits with the values "apple", "banana", and "cherry“. • # Your code here • fruits = ("apple", "banana", "cherry") • print(fruits)
  • 85. Python Tuples • Access Tuple Items • You can access tuple items using indexing. • # Accessing tuple items • my_tuple = (1, 2, 3) • print(my_tuple[0]) # Output: 1 • print(my_tuple[1]) # Output: 2
  • 86. Python Tuples • Access and print the second item in the fruits tuple. • # Your code here • print(fruits[1]) # Output: banana
  • 87. Python Tuples • Change Tuple Values: • Tuples are immutable, but you can convert them to a list, change the value, and convert them back to a tuple. • # Changing tuple values • my_tuple = (1, 2, 3) • temp_list = list(my_tuple) • temp_list[0] = 4 • my_tuple = tuple(temp_list) • print(my_tuple) # Output: (4, 2, 3)
  • 88. Python Tuples • Exercise:Convert the fruits tuple to a list, change "banana" to "orange", and convert it back to a tuple. • # Your code here • temp_list = list(fruits) • temp_list[1] = "orange" • fruits = tuple(temp_list) • print(fruits) # Output: ('apple', 'orange', 'cherry')
  • 89. Python Tuples • Loop Through a TupleYou can loop through the items in a tuple using a for loop. • # Looping through a tuple • my_tuple = (1, 2, 3) • for item in my_tuple: • print(item)
  • 90. Python Tuples • Check if Item Exists: You can check if an item exists in a tuple using the in keyword. • # Check if item exists • my_tuple = (1, 2, 3) • print(2 in my_tuple) # Output: True • print(4 in my_tuple) # Output: False
  • 91. Python Tuples • Tuple Length: You can find the length of a tuple using the len() function. • # Finding tuple length • my_tuple = (1, 2, 3) • print(len(my_tuple)) # Output: 3
  • 92. Python Tuples • Add Items • Since tuples are immutable, you cannot add items to an existing tuple. Instead, you can concatenate tuples. • # Adding items to a tuple • my_tuple = (1, 2, 3) • my_tuple += (4,) • print(my_tuple) # Output: (1, 2, 3, 4)
  • 93. Python Tuples • Remove Items • Tuples are immutable, so you cannot directly remove items. You can convert the tuple to a list, remove the item, and convert it back to a tuple. • # Removing items from a tuple • my_tuple = (1, 2, 3) • temp_list = list(my_tuple) • temp_list.remove(2) • my_tuple = tuple(temp_list) • print(my_tuple) # Output: (1, 3)
  • 94. Python Tuples • Join Two TuplesYou can join two tuples using the + operator. • # Joining two tuples • tuple1 = (1, 2, 3) • tuple2 = (4, 5, 6) • result = tuple1 + tuple2 • print(result) # Output: (1, 2, 3, 4, 5, 6)
  • 95. Exercise • Add the item "grape" to the fruits tuple. • Remove "orange" from the fruits tuple. • Join the fruits tuple with another tuple containing "pear" and "mango".
  • 96. Dictionary • Definition: A dictionary is a collection of key-value pairs. Each key is unique and is used to access its corresponding value. • student = { • "name": "Alice", • "age": 21, • "major": "Computer Science" • } • print(student) # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
  • 97. Accessing Dictionary Elements • student = { • "name": "Alice", • "age": 21, • "major": "Computer Science" • } • print(student["name"]) # Output: Alice
  • 98. Using get() Method • Syntax: dictionary.get(key, default) • print(student.get("age")) # Output: 21 • print(student.get("GPA", "Not Available")) # Output: Not Available
  • 99. Modifying Dictionaries • Syntax: dictionary[key] = value • student["GPA"] = 3.8 # Adding a new key-value pair • student["age"] = 22 # Updating an existing key-value pair • print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'GPA': 3.8}
  • 100. Removing Elements • Using del • del student["GPA"] • print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science'} • Using pop() • age = student.pop("age") • print(age) # Output: 22 • print(student) # Output: {'name': 'Alice', 'major': 'Computer Science'}
  • 101. Dictionary Methods • keys(): Returns a view object containing the dictionary's keys. • values(): Returns a view object containing the dictionary's values. • items(): Returns a view object containing the dictionary's key-value pairs. • update(): Updates the dictionary with the key-value pairs from another dictionary.
  • 102. Examples • keys = student.keys() • print(keys) # Output: dict_keys(['name', 'major']) • values = student.values() • print(values) # Output: dict_values(['Alice', 'Computer Science']) • items = student.items() • print(items) # Output: dict_items([('name', 'Alice'), ('major', 'Computer Science')]) • student.update({"age": 22, "GPA": 3.8}) • print(student) # Output: {'name': 'Alice', 'major': 'Computer Science', 'age': 22, 'GPA': 3.8}
  • 103. Looping Through Dictionaries • Looping Through Keys • for key in student: • print(key, student[key]) • Looping Through Key-Value Pairs • for key, value in student.items(): • print(key, value)
  • 104. Exercise-1 • Create a dictionary representing a grocery store inventory with items and their prices, perform the following operations: • Add a new item with its price. • Update the price of an existing item. • Remove an item from the inventory. • Print the final inventory. • N.B. inventory={“apples”:2.99,”bananas:1.99,”orange”:3.24}
  • 105. Solution-1 • # Initial inventory dictionary • inventory = { • "apples": 2.99, • "bananas": 1.99, • "oranges": 3.49 • } • inventory["grapes"] = 4.99 • inventory["bananas"] = 2.49 • del inventory["oranges"] • for item, price in inventory.items(): • print(f"{item}: ${price:.2f}")
  • 106. Exercise-2 • Create a dictionary to store information about three students. Each student should have a dictionary containing their name, age, and grade. Print the details of each student in a readable format
  • 107. Solution-2 • # Creating the nested dictionary • students = { • "student1": {"name": "John", "age": 20, "grade": "A"}, • "student2": {"name": "Alice", "age": 22, "grade": "B"}, • "student3": {"name": "Bob", "age": 21, "grade": "A-"} • } • # Printing the details of each student • for student_id, student_info in students.items(): • print(f"Details of {student_id}:") • for key, value in student_info.items(): • print(f" {key}: {value}")
  • 108. Lambda() • Definition: lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. The expression is evaluated and returned. • Examples: • # Lambda function to add two numbers • add = lambda x, y: x + y • print(add(2, 3)) # Output: 5 • # Lambda function to square a number • square = lambda x: x**2 • print(square(4)) # Output: 16
  • 109. Map() • Definition: The map() function applies a given function to all items in an input list (or any iterable) and returns an iterator (which can be converted to a list). • # Using map to double the numbers in a list • numbers = [1, 2, 3, 4, 5] • doubled = list(map(lambda x: x * 2, numbers)) • print(doubled) # Output: [2, 4, 6, 8, 10] • # Using map to convert a list of temperatures from Celsius to Fahrenheit • celsius = [0, 10, 20, 30] • fahrenheit = list(map(lambda x: (x * 9/5) + 32, celsius)) • print(fahrenheit) # Output: [32.0, 50.0, 68.0, 86.0]
  • 110. Filter() • Definition: The filter() function constructs an iterator from elements of an iterable for which a function returns true. • # Using filter to get even numbers from a list • numbers = [1, 2, 3, 4, 5, 6] • evens = list(filter(lambda x: x % 2 == 0, numbers)) • print(evens) # Output: [2, 4, 6] • # Using filter to get words longer than 3 characters from a list • words = ["apple", "it", "banana", "cat"] • long_words = list(filter(lambda word: len(word) > 3, words)) • print(long_words) # Output: ['apple', 'banana']
  • 111. Exercises • Exercise 1: Use map() with lambda: Given a list of numbers, use map() and a lambda function to create a new list with the square of each number. • Exercise 2: Use filter() with lambda: Given a list of strings, use filter() and a lambda function to create a new list with only the strings that contain the letter 'a'. • Exercise 3: Combine map() and filter(): Given a list of numbers, first use filter() and a lambda function to create a new list of only the even numbers. Then use map() and a lambda function to create a new list with the squares of those even numbers.
  • 112. Solution • numbers = [1, 2, 3, 4, 5] • squares = list(map(lambda x: x**2, numbers)) • print(squares) # Output: [1, 4, 9, 16, 25] • words = ["apple", "banana", "cherry", "date", "fig"] • words_with_a = list(filter(lambda word: 'a' in word, words)) • print(words_with_a) # Output: ['apple', 'banana', 'date']
  • 113. Solution • numbers = [1, 2, 3, 4, 5, 6, 7, 8] • evens = list(filter(lambda x: x % 2 == 0, numbers)) • squared_evens = list(map(lambda x: x**2, evens)) • print(squared_evens) # Output: [4, 16, 36, 64]
  • 114. Practical Application • Task: Given a list of dictionaries representing employees, each with a name and salary, use map() and a lambda function to give each employee a 10% raise. Then use filter() and a lambda function to filter out employees with salaries less than $50,000 after the raise.
  • 115. Solution • employees = [ • {"name": "Alice", "salary": 45000}, • {"name": "Bob", "salary": 50000}, • {"name": "Charlie", "salary": 60000} • ] • # Giving a 10% raise • raised_salaries = list(map(lambda e: {"name": e["name"], "salary": e["salary"] * 1.1}, employees)) • print(raised_salaries) • # Output: [{'name': 'Alice', 'salary': 49500.0}, {'name': 'Bob', 'salary': 55000.0}, {'name': 'Charlie', 'salary': 66000.0}] • # Filtering out employees with salaries less than $50,000 • high_salaries = list(filter(lambda e: e["salary"] >= 50000, raised_salaries)) • print(high_salaries) • # Output: [{'name': 'Bob', 'salary': 55000.0}, {'name': 'Charlie', 'salary': 66000.0}]
  • 116. Error Handling with try, except, and finally • Error handling is a crucial part of writing robust and error-free code. Python provides a way to handle errors gracefully using the try, except, and finally blocks. • try: • number = int(input("Enter a number: ")) • result = 10 / number • print(f"The result is {result}") • except ZeroDivisionError: • print("Error: Division by zero is not allowed.") • except ValueError: • print("Error: Invalid input. Please enter a valid number.")
  • 117. Using finally • try: • file = open('example.txt', 'r') • content = file.read() • print(content) • except FileNotFoundError: • print("Error: The file does not exist.") • finally: • file.close() • print("The file has been closed.")
  • 118. Catching Multiple Exceptions • try: • data = [1, 2, 3] • print(data[3]) # This will raise an IndexError • number = int("abc") # This will raise a ValueError • except IndexError: • print("Error: Index out of range.") • except ValueError: • print("Error: Invalid value.")
  • 119. Exercises • Exercise 1: Write a program that takes two numbers as input from the user and divides them. Use try and except blocks to handle the ZeroDivisionError and ValueError exceptions. • Exercise 2: Write a program that reads a number from the user, converts it to an integer, and divides 100 by this number. Use nested try and except blocks to handle ValueError and ZeroDivisionError.
  • 120. Solution-1 • try: • num1 = float(input("Enter the first number: ")) • num2 = float(input("Enter the second number: ")) • result = num1 / num2 • print(f"The result is {result}") • except ZeroDivisionError: • print("Error: Division by zero is not allowed.") • except ValueError: • print("Error: Invalid input. Please enter valid numbers.")
  • 121. Solution -2 • try: • num_str = input("Enter a number: ") • try: • num = int(num_str) • result = 100 / num • print(f"The result is {result}") • except ZeroDivisionError: • print("Error: Division by zero is not allowed.") • except ValueError: • print("Error: Invalid input. Please enter a valid number.")
  • 122. Functions and Modules • Definition: A function is a block of organized, reusable code that is used to perform a single, related action. • def function_name(parameters): • """docstring""" • statement(s) • return expression
  • 123. Example • def greet(name): • """This function greets the person whose name is passed as a parameter""" • return f"Hello, {name}!" • # Calling the function • print(greet("Alice")) # Output: Hello, Alice!
  • 124. Working with Modules and Packages • A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. # Save this as my_module.py def add(a, b): return a + b def subtract(a, b): return a - b # Importing and using the module import my_module print(my_module.add(5, 3)) # Output: 8 print(my_module.subtract(5, 3)) # Output: 2
  • 125. Packages • A package is a way of collecting related modules together within a single tree- like hierarchy. They are just directories containing a special __init__.py file. • # Importing and using the package • from my_package import module1, module2 • print(module1.function_in_module1()) • print(module2.function_in_module2())
  • 126. Importing and Using Third-Party Libraries • These are external modules and packages that are not included in the Python Standard Library but can be installed using a package manager like pip.
  • 127. Exercises • Write a function factorial that takes a positive integer and returns its factorial • Create a module math_operations.py with functions to add, subtract, multiply, and divide two numbers. Import this module in another script and use these functions. • Install and use the numpy library to create an array and perform basic arithmetic operations.
  • 128. Solution-1 • def factorial(n): • """This function returns the factorial of a given number.""" • if n == 0: • return 1 • else: • return n * factorial(n-1) • print(factorial(5)) # Output: 120
  • 129. Solution-2 • # math_operations.py • def add(a, b): • return a + b • def subtract(a, b): • return a - b • def multiply(a, b): • return a * b • def divide(a, b): • if b != 0: • return a / b • else: • return "Division by zero is not allowed"
  • 130. Solution-2 • # main.py • import math_operations as mo • print(mo.add(10, 5)) # Output: 15 • print(mo.subtract(10, 5)) # Output: 5 • print(mo.multiply(10, 5)) # Output: 50 • print(mo.divide(10, 5)) # Output: 2.0 • print(mo.divide(10, 0)) # Output: Division by zero is not allowed
  • 131. Soluiotn-3 • import numpy as np • # Creating a numpy array • arr = np.array([1, 2, 3, 4, 5]) • # Performing arithmetic operations • print(arr + 5) # Output: [ 6 7 8 9 10] • print(arr * 2) # Output: [ 2 4 6 8 10]
  • 132. Object-Oriented Programming • Definition: • Class: A blueprint for creating objects. It defines a set of attributes and methods that the created objects will have. • Object: An instance of a class.
  • 134. Inheritance and Polymorphism • Inheritance allows a class (called the child class) to inherit attributes and methods from another class (called the parent class). • class ParentClass: • # parent class implementation • class ChildClass(ParentClass): • # child class implementation
  • 136. Inheritance and Polymorphism • Polymorphism allows methods to do different things based on the object it is acting upon. In the example above, the speak method is polymorphic, behaving differently depending on whether the object is an instance of Dog or Cat.
  • 137. Advanced Class Features • Class Methods: • Class methods are methods that are bound to the class and not the instance. They can modify the class state that applies across all instances of the class. • class Dog: • species = "Canis familiaris" • @classmethod • def get_species(cls): • return cls.species • print(Dog.get_species()) # Output: Canis familiaris
  • 138. Static Methods: • Static methods are methods that do not operate on an instance or the class. They are utility-type methods that can be called on the class itself. • class Math: • @staticmethod • def add(a, b): • return a + b • print(Math.add(5, 3)) # Output: 8
  • 139. Properties • Properties are a way of customizing access to instance attributes. They can be used to add logic to getting and setting a value. • class ClassName: • @property • def property_name(self): • # getter method • @property_name.setter • def property_name(self, value): • # setter method
  • 141. Exercises • Exercise 1: Create a class Car with attributes make, model, and year. Add a method description that returns a formatted string describing the car. • Exercise 2: Create a base class Person with attributes name and age. Create a derived class Employee that inherits from Person and adds an attribute employee_id. Add a method to the Employee class that returns the employee's details.
  • 142. Exercises • Exercise 3: Create a class Temperature with a class attribute unit set to "Celsius". Add a class method change_unit to change the unit to "Fahrenheit". Add a static method convert_to_fahrenheit that converts a temperature from Celsius to Fahrenheit. • Exercise 4: Create a class Rectangle with attributes width and height. Add a property area that calculates and returns the area of the rectangle. Add a property perimeter that calculates and returns the perimeter.
  • 147. Advanced Data Structures (Sets, Queues, Stacks) • Sets • A set is a collection of unique elements. Sets are useful for membership tests, removing duplicates, and performing mathematical set operations like union, intersection, and difference. • Examples • Go pycharm
  • 149. Queues • A queue is a collection where elements are added from one end and removed from the other (FIFO: First In, First Out). • from collections import deque • # Creating a queue • queue = deque() • # Enqueuing elements • queue.append(1) • queue.append(2) • queue.append(3) • print(queue) # Output: deque([1, 2, 3]) • # Dequeuing elements • queue.popleft() • print(queue) # Output: deque([2, 3])
  • 150. Stacks • A stack is a collection where elements are added and removed from the same end (LIFO: Last In, First Out). • # Creating a stack • stack = [] • # Pushing elements onto the stack • stack.append(1) • stack.append(2) • stack.append(3) • print(stack) # Output: [1, 2, 3] • # Popping elements from the stack • stack.pop() • print(stack) # Output: [1, 2]
  • 151. Exercises • Write a function that takes two lists and returns a set containing the common elements (intersection) and another set containing all unique elements from both lists (union). • Implement a stack using a list. The stack should support the following operations: push (add an element to the top), pop (remove and return the top element), and peek (return the top element without removing it). • Implement a queue using a list (or deque). The queue should support the following operations: enqueue (add an element to the end), dequeue (remove and return the element from the front), and front (return the front element without removing it).
  • 152. Solution-1 • def set_operations(list1, list2): • set1 = set(list1) • set2 = set(list2) • intersection = set1.intersection(set2) • union = set1.union(set2) • return intersection, union • # Example usage • list1 = [1, 2, 3, 4, 5] • list2 = [4, 5, 6, 7, 8] • intersection, union = set_operations(list1, list2) • print("Intersection:", intersection) # Output: {4, 5} • print("Union:", union) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
  • 153. Solution-2 • class Stack: • def __init__(self): • self.stack = [] • def push(self, item): • self.stack.append(item) • def pop(self): • if len(self.stack) == 0: • return "Stack is empty" • return self.stack.pop() • def peek(self): • if len(self.stack) == 0: • return "Stack is empty" • return self.stack[-1] • def is_empty(self): • return len(self.stack) == 0 • # Example usage • stack = Stack() • stack.push(1) • stack.push(2) • stack.push(3) • print(stack.peek()) # Output: 3 • print(stack.pop()) # Output: 3 • print(stack.peek()) # Output: 2
  • 154. Solution-3 • from collections import deque • class Queue: • def __init__(self): • self.queue = deque() • def enqueue(self, item): • self.queue.append(item) • def dequeue(self): • if len(self.queue) == 0: • return "Queue is empty" • return self.queue.popleft() • def front(self): • if len(self.queue) == 0: • return "Queue is empty" • return self.queue[0] • def is_empty(self): • return len(self.queue) == 0 • # Example usage • queue = Queue() • queue.enqueue(1) • queue.enqueue(2) • queue.enqueue(3) • print(queue.front()) # Output: 1 • print(queue.dequeue()) # Output: 1 • print(queue.front()) # Output: 2
  • 155. File Handling • Text files are the most common types of files used to store data. Python provides built-in functions to read from and write to text files.
  • 156. File Handling and Data Serialization
  • 157. Exercise • Create a text file named myfile.txt and write a few lines of text into it. • Read the content of myfile.txt and print it to the console. • Append a new line to myfile.txt and print the updated content.
  • 158. Solution • with open('myfile.txt', 'w') as file: • file.write("Line 1: Hello, world!n") • file.write("Line 2: Welcome to file handling in Python.n") • with open('myfile.txt', 'r') as file: • content = file.read() • print("Content of myfile.txt:") • print(content) • with open('myfile.txt', 'a') as file: • file.write("Line 3: Appending a new line.n") • with open('myfile.txt', 'r') as file: • updated_content = file.read() • print("Updated content of myfile.txt:") • print(updated_content)
  • 159. CSV manipulation • CSV (Comma-Separated Values) files are used to store tabular data. The pandas library provides powerful functionality to read from and write to CSV files using DataFrames.
  • 162. Exercise • Create a CSV file named students.csv with columns Name, Age, and Grade using a pandas DataFrame. • Write at least three rows of data into students.csv. • Read the content of students.csv into a pandas DataFrame and print it to the console. • Add a new row to the students.csv file and print the updated DataFrame.
  • 163. Solution • import pandas as pd • data = { • 'Name': ['Alice', 'Bob', 'Charlie'], • 'Age': [20, 21, 22], • 'Grade': ['A', 'B', 'C'] • } • df = pd.DataFrame(data) • df.to_csv('students.csv', index=False) • df = pd.read_csv('students.csv') • print(df) • new_data = pd.DataFrame({'Name': ['David'], 'Age': [23], 'Grade': ['B']}) • df = pd.concat([df, new_data], ignore_index=True) • df.to_csv('students.csv', index=False) • print("Updated content of students.csv:") • print(df)
  • 164. Pandas dataframe • One of the most powerful and commonly used data structures in pandas. • Creating DataFrames • From a Dictionary • From a List of Dictionaries • From a CSV File
  • 165. From a dictionary • import pandas as pd • data = { • 'Name': ['Alice', 'Bob', 'Charlie'], • 'Age': [25, 30, 35], • 'City': ['New York', 'Los Angeles', 'Chicago'] • } • df = pd.DataFrame(data) • print(df)
  • 166. From a list of dictionaries • data = [ • {'Name': 'Alice', 'Age': 25, 'City': 'New York'}, • {'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'}, • {'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'} • ] • df = pd.DataFrame(data) • print(df)
  • 167. Exercise • Create a DataFrame from a dictionary with the columns Product, Price, and Quantity. • Create a DataFrame from a list of dictionaries with the columns Student, Grade, and Subject. • Read a CSV file named sales.csv into a DataFrame and print the first 5 rows.
  • 168. Solution • import pandas as pd • data = { • 'Product': ['Apples', 'Bananas', 'Cherries'], • 'Price': [1.2, 0.5, 3.0], • 'Quantity': [10, 20, 15] • } • df1 = pd.DataFrame(data) • print("DataFrame from dictionary:") • print(df1) • data = [ • {'Student': 'Alice', 'Grade': 'A', 'Subject': 'Math'}, • {'Student': 'Bob', 'Grade': 'B', 'Subject': 'Science'}, • {'Student': 'Charlie', 'Grade': 'C', 'Subject': 'History'} • ] • df2 = pd.DataFrame(data) • print("nDataFrame from list of dictionaries:") • print(df2) • df3 = pd.read_csv('sales.csv') • print("nFirst 5 rows of sales.csv:") • print(df3.head())
  • 170. Exercise • Print the first 3 rows of a DataFrame. • Select and print the Product column from a DataFrame. • Select and print rows where the Price is greater than 50.
  • 171. Solution • import pandas as pd • # Sample DataFrame for demonstration • data = { • 'Product': ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries'], • 'Price': [1.2, 0.5, 3.0, 10.0, 50.5], • 'Quantity': [10, 20, 15, 5, 2] • } • df = pd.DataFrame(data) • # Solution 1: Printing the first 3 rows • print("First 3 rows of DataFrame:") • print(df.head(3)) • # Solution 2: Selecting and printing the 'Product' column • print("n'Product' column of DataFrame:") • print(df['Product']) • # Solution 3: Selecting and printing rows where the 'Price' is greater than 50 • print("nRows where 'Price' is greater than 50:") • print(df[df['Price'] > 50])
  • 172. Data manipulation • Add a new column Total to a DataFrame, which is the product of Price and Quantity. • Rename the Product column to Item in a DataFrame. • Fill missing values in a DataFrame with the mean of the column.
  • 173. Exercise • import pandas as pd • # Sample DataFrame for demonstration • data = { • 'Product': ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries'], • 'Price': [1.2, 0.5, 3.0, 10.0, 50.5], • 'Quantity': [10, 20, 15, 5, 2] • } • df = pd.DataFrame(data) • df['Total'] = df['Price'] * df['Quantity'] • print("DataFrame with 'Total' column added:") • print(df) • df = df.rename(columns={'Product': 'Item'}) • print("nDataFrame with 'Product' column renamed to 'Item':") • print(df) • # Creating a sample DataFrame with missing values for Solution 3 • data_with_na = { • 'Product': ['Apples', 'Bananas', 'Cherries'], • 'Price': [1.2, None, 3.0], • 'Quantity': [10, 20, None] • } • df_na = pd.DataFrame(data_with_na) • # Solution 3: Filling missing values with the mean of the column • df_na['Price'] = df_na['Price'].fillna(df_na['Price'].mean()) • df_na['Quantity'] = df_na['Quantity'].fillna(df_na['Quantity'].mean()) • print("nDataFrame with missing values filled with column mean:") • print(df_na)
  • 174. Python with DB • Connecting to a MySQL Database with Python. • Basic Operations: • Connecting to the Database • Creating a Table • Inserting Data • Querying Data • Updating Data • Deleting Data
  • 175. Connecting to the Database • import mysql.connector • # Establish the connection • conn = mysql.connector.connect( • host="localhost", • user="yourusername", • password="yourpassword", • database="yourdatabase" • ) • # Create a cursor object • cursor = conn.cursor()
  • 176. Creating a Table • create_table_query = """ • CREATE TABLE employees ( • id INT AUTO_INCREMENT PRIMARY KEY, • name VARCHAR(255), • position VARCHAR(255), • salary DECIMAL(10, 2) • ) • """ • cursor.execute(create_table_query)
  • 177. Inserting Data • insert_query = """ • INSERT INTO employees (name, position, salary) • VALUES (%s, %s, %s) • """ • data = ("John Doe", "Software Engineer", 75000) • cursor.execute(insert_query, data) • conn.commit()
  • 178. Querying Data • select_query = "SELECT * FROM employees" • cursor.execute(select_query) • results = cursor.fetchall() • for row in results: • print(row)
  • 179. Deleting Data • delete_query = "DELETE FROM employees WHERE name = %s" • data = ("John Doe",) • cursor.execute(delete_query, data) • conn.commit()
  • 180. Exercises • Exercise 1: Create a new database and a table for storing student records. Insert, update, and query data in the table. • Exercise 2: Write a Python script that connects to the database and retrieves records based on specific criteria (e.g., all employees with a salary greater than a certain amount). • Exercise 3: Implement a function to delete records older than a certain date from a table.
  • 181. Solution1-Create a new database and table • import mysql.connector • # Establish the connection • conn = mysql.connector.connect( • host="localhost", • user="yourusername", • password="yourpassword" • ) • # Create a cursor object • cursor = conn.cursor() • # Create a new database • cursor.execute("CREATE DATABASE student_records") • # Select the database • conn.database = 'student_records' • # Create a table • create_table_query = """ • CREATE TABLE students ( • id INT AUTO_INCREMENT PRIMARY KEY, • name VARCHAR(255), • age INT, • major VARCHAR(255) • ) • """ • cursor.execute(create_table_query) • conn.commit() • # Close the connection • cursor.close() • conn.close()
  • 182. Solution1-Insert data into the table • import mysql.connector • conn = mysql.connector.connect( • host="localhost", • user="yourusername", • password="yourpassword", • database="student_records" • ) • cursor = conn.cursor() • insert_query = """ • INSERT INTO students (name, age, major) • VALUES (%s, %s, %s) • """ • students = [ • ("Alice Smith", 20, "Computer Science"), • ("Bob Johnson", 22, "Mathematics"), • ("Carol Williams", 19, "Biology") • ] • cursor.executemany(insert_query, students) • conn.commit() • cursor.close() • conn.close()
  • 183. Solution1-Query data from the table • select_query = "SELECT * FROM students" • cursor.execute(select_query) • results = cursor.fetchall() • for row in results: • print(row) • cursor.close() • conn.close()
  • 184. Solution1-Update data in the table • update_query = """ • UPDATE students • SET major = %s • WHERE name = %s • """ • data = ("Data Science", "Alice Smith") • cursor.execute(update_query, data) • conn.commit() • cursor.close() • conn.close()
  • 185. Solution1-Delete data from the table • delete_query = "DELETE FROM students WHERE name = %s" • data = ("Bob Johnson",) • cursor.execute(delete_query, data) • conn.commit() • cursor.close() • conn.close()
  • 186. Solution2 • select_query = "SELECT * FROM students WHERE age > %s" • age = (20,) • cursor.execute(select_query, age) • results = cursor.fetchall() • for row in results: • print(row) • cursor.close() • conn.close()
  • 187. Solution3 • delete_query = "DELETE FROM students WHERE age < %s" • age_limit = (21,) • cursor.execute(delete_query, age_limit) • conn.commit() • cursor.close() • conn.close()
  • 188. Extra Exercises • Exercise 1: Write a program that prints the numbers from 1 to 50. But for multiples of three, print “Three" instead of the number, and for the multiples of five, print “Five". For numbers which are multiples of both three and five, print “ThreeFive". • Exercise 2: Write a program that calculates the sum of all numbers from 1 to 100 that are divisible by 4. • Exercise 3: Write a program to find the maximum and minimum elements in a list.
  • 189. Extra Exercises • Exercise 4: Write a program to merge two tuples and sort them. • Exercise 5: Write a program to count the frequency of each character in a given string. • Exercise 6: Create a class BankAccount with attributes account_number and balance. Define methods to deposit and withdraw money from the account. • Exercise 7: Write a program to filter rows in a DataFrame where a specific column value is greater than a given number.
  • 190. Extra Exercises • Exercise 8: Write a Python script to connect to a MySQL database and create a table. • Exercise 9: Write a Python script to insert data into a MySQL table and fetch all records.