Introduction to Python Prog. - Lecture 3

1mohamedgamal54 36 views 32 slides Sep 12, 2024
Slide 1
Slide 1 of 32
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32

About This Presentation

Introduction to Python Programming Language for absolute beginners level.


Slide Content

Introduction to Python
Programming
By Mohamed Gamal
© Mohamed Gamal 2024

The topics of today’s lecture:
Agenda

Types of
Errors
Syntax Error
Semantic Error
Logical Error
Run-time Error

Types of Errors
–Syntax Errors: occur when the code does not follow the grammatical rules of the
programming language and detected by the interpreter during the code parsing phase.
–Semantic Errors: occur when the code follows the syntax rules but does not make logical
sense or produce the intended result, often arise from incorrect use of language constructs
and typically not detected by the interpreter.
–Logical Errors: occur when the code executes without syntax errors or semantic issues but
produces incorrect results due to flaws in the logic of the program, typically not detected by
the interpreter and identified through testing and debugging.
–Run-time Errors: occur while the program is executing and not detected during the parsing
phase and only show up during the actual execution of the code causing the program to
crash or terminate unexpectedly.

Examples
# Syntax Error: Missing colon
if x > 10
print("x is greater than 10")
# Semantic Error: Function name suggests addition
def add(a, b):
return a – b
# Logical Error: This function checks for odd numbers instead of even.
def is_even(n):
return n % 2 == 1
# Run-time Error: Division by zero
x = 10 / 0

Exception handling
–Exception handling in Python involves managing runtime errors that occur
during program execution.
–Python offers features for handling these errors, including exception handling
and assertions, to improve program stability and debugging.

1) Assertion
–Assertions in Python are a debugging aid that test whether a condition in your code is true.
–They are used to catch logical errors by ensuring that certain conditions hold true at specific
points in the program.
–How Assertions Work:
–An assertion is written using the assert keyword followed by a condition.
–If the condition is True, the program continues execution without interruption.
–If the condition is False, an AssertionError is raised, which can include an optional error message.
assert condition, "Error message if condition is False"
Syntax:

Example
def divide(a, b):
assert b != 0, "Division by zero is not allowed"
return a / b
print(divide(10, 2)) # Works fine
print(divide(10, 0)) # Raises AssertionError

2) Exceptions
–In Python, exceptions are errors that occur during program execution (run-time), disrupting
its normal flow.
–They can be raised automatically by the interpreter or manually using the raise keyword to
help manage errors and maintain program stability.
–Common Exceptions:
–ZeroDivisionError
–ValueError
–IndexError
–FileNotFoundError

Exception
Hierarchy

Handling Exceptions
1)Use try to wrap code that might raise an exception.
2)Use except to handle the exception.
3)Optionally, use else for code that runs if no exception occurs.
4)Use finally for code that always executes, regardless of exceptions.

Python Try-Except Block
try:
# Code that might raise exceptions
except FirstExceptionType:
# Handle the first type of exception
except SecondExceptionType:
# Handle the second type of exception
...
Syntax:

try:
result = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Error: Cannot divide by zero." )
try:
number = int("abc") # Invalid literal for int()
except ValueError:
print("Error: Invalid value provided." )
try:
my_list = [1, 2, 3]
print(my_list[5]) # Index out of range
except IndexError:
print("Error: Index out of range." )

Python Try-Except-Else Block
try:
user_input = input("Enter an integer: ") # Attempt to get user input
number = int(user_input) # Try to convert input to integer
except ValueError:
# Handle invalid input
print("Error: Invalid input. Please enter a valid integer." )
else:
square = number ** 2 # Compute square if no exception occurred
print(f"The square of {number} is {square}.") # Output the result

try:
result = 10 / 2 # No error
except ZeroDivisionError:
print("Error: Cannot divide by zero." )
else:
print(f"Division successful. Result: {result}")
finally:
print("This block always executes." )
Python Try-Except-Else-Finally Block

2) Raising Exceptions
–In Python, you can raise exceptions explicitly using the raise statement.
–Raising exceptions allows you to indicate that an error has occurred and to control
the flow of your program by handling these exceptions appropriately.
def check_positive(number):
if number <= 0:
raise ValueError("The number must be positive." )
return number
try:
result = check_positive(-5) # This will raise ValueError
except ValueError as e:
print(f"Error: {e}")

Raising Exceptions
–Multithreading allows you to run multiple threads (smaller units of a process)
concurrently, which can be useful for tasks like I/O-bound operations.
–Python’s threading module provides the tools for working with threads.

import threading
threading.current_thread ().name
example_thread = threading.Thread()
example_thread.setName()
example_thread.daemon = True
example_thread.start()
example_thread.join()
Most commonly used Thread related methods

import threading
import time
def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1)
def print_letters():
for letter in 'abcde':
print(f"Letter: {letter}")
time.sleep(1)
# Create threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Start threads
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()
print("Finished executing both threads" )
Example 1

import threading
def print_repeated(text, times):
for _ in range(times):
print(text)
# Create threads with arguments
thread1 = threading.Thread(target=print_repeated, args=("Hello", 3))
thread2 = threading.Thread(target=print_repeated, args=("World", 3))
# Start threads
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()
Example 2

import threading, time
def background_task():
while True:
print("Background task running..." )
time.sleep(1)
# Create a daemon thread
thread = threading.Thread(target=background_task)
thread.daemon = True # Set as daemon thread
# Start the daemon thread
thread.start()
# Main thread execution
print("Main thread is running" )
# thread.join()
time.sleep(5)
print("Main thread is done")
Example 3
•A daemon thread runs in the
background and terminates when
the main program exits.

Python Generators
–Python generators are a powerful and efficient way to handle large sequences of
data.
–A generator is a special type of iterator that generates values on the fly and yields
them one at a time using the yield keyword. This makes them memory efficient
because they don’t store all the values in memory.
squares = (x * x for x in range(5))
for square in squares:
print(square)

Example 1
squares = (x * x for x in range(5))
print(type(squares))
print(squares)
# print next item
print(next(squares))
print(next(squares))
print(next(squares))
# print all items
for square in squares:
print(square)

Example 2
# generator function
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
# Using the generator
counter = count_up_to(5)
for num in counter:
print(num)

PIP Package Installer
–pip is the package installer for Python, it allows you to install and manage Python
libraries and dependencies from the Python Package Index (PyPI) and other package
repositories.
–Here’s a basic usage:
$ pip install package_name
$ pip uninstall package_name
$ pip list
$ pip show package_name
$ pip install --upgrade package_name

import time
localtime = time.asctime(time.localtime(time.time()))
print(f"Local current time: {localtime}")
import calendar
cal = calendar.month(2024, 7)
print(cal)
Time and Calendar Modules

Some Applications
S na k e Ga me
Snake Game
Key log g er Prog ra m
Keylogger Program

Final tip: Searching is a crucial skill.

End of lecture 3
Thank You!