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 Snake Game Snake Game Keylogger Program Keylogger Program ⋮ Final tip: Searching is a crucial skill.
End of lecture 3 ThankYou!

Introduction to Python Prog. - Lecture 3

  • 1.
    Introduction to Python Programming ByMohamed Gamal © Mohamed Gamal 2024
  • 2.
    The topics oftoday’s lecture: Agenda
  • 4.
    Types of Errors Syntax Error SemanticError 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 – Exceptionhandling 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 – Assertionsin 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): assertb != 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 – InPython, 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
  • 11.
  • 12.
    Handling Exceptions 1) Usetry 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 – Multithreadingallows 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 defprint_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 defbackground_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 – Pythongenerators 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 # generatorfunction 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 SnakeGame Keylogger Program Keylogger Program ⋮ Final tip: Searching is a crucial skill.
  • 32.
    End of lecture3 ThankYou!