SlideShare a Scribd company logo
Introduction to Python
Programming
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
Introduction to Python Prog. - Lecture 3
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}")
Introduction to Python Prog. - Lecture 3
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.
Introduction to Python Prog. - Lecture 3
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
Introduction to Python Prog. - Lecture 3
Some Applications
Snake Game
Snake Game
Keylogger Program
Keylogger Program
⋮
Final tip: Searching is a crucial skill.
End of lecture 3
ThankYou!

More Related Content

Similar to Introduction to Python Prog. - Lecture 3 (20)

PPTX
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
PPTX
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
PPTX
Python for beginners textbook slides ppt
AnithaChristyAngelin
 
DOCX
Exception handlingpdf
gandra jeeshitha
 
PPT
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
PPT
Py-Slides-9.ppt
wulanpermatasari27
 
PPTX
Exception Handling in python programming.pptx
shririshsri
 
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
PPT
Exception handling and function in python
TMARAGATHAM
 
PPT
Exception handling in python and how to handle it
s6901412
 
PPT
Exception Handling using Python Libraries
mmvrm
 
PPTX
Python Lecture 7
Inzamam Baig
 
PPTX
Exception Handling.pptx
Pavan326406
 
PPTX
exceptioninpython.pptx
SulekhJangra
 
PPTX
Exception Handling in Python Programming.pptx
vinayagrawal71
 
PPTX
Mastering Errors and Exceptions in Python: A Comprehensive Guide
Vignan's Foundation for Science, Technology & Research (Deemed to be University)
 
PDF
Wondershare UniConverter Crack FREE Download 2025 version
mu394968
 
PDF
GE3151_PSPP_UNIT_5_Notes
Guru Nanak Technical Institutions
 
PPTX
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
xaybhagfsus
 
Adobe Photoshop 2025 Cracked Latest Version
hyderik195
 
FL Studio Producer Edition Crack 24 + Latest Version [2025]
hyderik195
 
Python for beginners textbook slides ppt
AnithaChristyAngelin
 
Exception handlingpdf
gandra jeeshitha
 
Exception Handling on 22nd March 2022.ppt
Raja Ram Dutta
 
Py-Slides-9.ppt
wulanpermatasari27
 
Exception Handling in python programming.pptx
shririshsri
 
lecs101.pdfgggggggggggggggggggddddddddddddb
MrProfEsOr1
 
Exception handling and function in python
TMARAGATHAM
 
Exception handling in python and how to handle it
s6901412
 
Exception Handling using Python Libraries
mmvrm
 
Python Lecture 7
Inzamam Baig
 
Exception Handling.pptx
Pavan326406
 
exceptioninpython.pptx
SulekhJangra
 
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Mastering Errors and Exceptions in Python: A Comprehensive Guide
Vignan's Foundation for Science, Technology & Research (Deemed to be University)
 
Wondershare UniConverter Crack FREE Download 2025 version
mu394968
 
GE3151_PSPP_UNIT_5_Notes
Guru Nanak Technical Institutions
 
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
xaybhagfsus
 

More from Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt (20)

PDF
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

PPTX
原版一样(EC Lille毕业证书)法国里尔中央理工学院毕业证补办
Taqyea
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
Biosensors, BioDevices, Biomediccal.pptx
AsimovRiyaz
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PDF
Digital water marking system project report
Kamal Acharya
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
darshai cross section and river section analysis
muk7971
 
PPTX
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
原版一样(EC Lille毕业证书)法国里尔中央理工学院毕业证补办
Taqyea
 
Distribution reservoir and service storage pptx
dhanashree78
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Biosensors, BioDevices, Biomediccal.pptx
AsimovRiyaz
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Digital water marking system project report
Kamal Acharya
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
darshai cross section and river section analysis
muk7971
 
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
Ad

Introduction to Python Prog. - Lecture 3

  • 1. Introduction to Python Programming By Mohamed Gamal © Mohamed Gamal 2024
  • 2. The topics of today’s lecture: Agenda
  • 4. Types of Errors Syntax Error Semantic Error Logical Error Run-time Error
  • 5. 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.
  • 6. 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
  • 7. 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.
  • 8. 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:
  • 9. 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
  • 10. 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
  • 12. 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.
  • 13. 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:
  • 14. 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.")
  • 15. 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
  • 16. 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
  • 17. 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}")
  • 19. 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.
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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.
  • 25. 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)
  • 26. 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)
  • 27. 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)
  • 28. 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
  • 29. 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
  • 31. Some Applications Snake Game Snake Game Keylogger Program Keylogger Program ⋮ Final tip: Searching is a crucial skill.
  • 32. End of lecture 3 ThankYou!