Fifth Contact - Part 6 813
Fifth Contact - Part 6 813
Programming
Fundamentals
Dr. Barroon Isma’eel Ahmad
Department of Computer and Information Technology
Photo by Pexels
01 Study Session 1: Introduction to Computer Programming
2
Introduction to Programming Fundamentals
● An overview of the core concepts of programming including variables, loops, and functions.
● Understand the importance of coding in modern-day technology and its applications in various industries.
● Explore the fundamentals of programming languages, syntax rules, and problem-solving strategies.
● Delve into the significance of structured programming and algorithmic thinking in software development.
● Discover the evolution of programming languages and the role of programming paradigms in shaping software
design.
● Learn about object-oriented programming and its advantages in creating reusable code.
● Understand the key principles of software testing, debugging, and version control.
● Explore common programming errors and methodologies to enhance code quality and maintainability.
● Reflect on the ethical considerations in software development and the importance of adhering to coding standards
and best practices.
● Explore the interdisciplinary nature of programming and its impact on innovation.
3
Course Aims
4
Course Objectives
5
Week 6
Event-Driven Programming
Event-driven programming fundamentals
Exception handling and debugging
Strings and String Processing
6
Learning Outcomes
7
Event-Driven Programming
● Event-driven programming is a programming paradigm in which the flow of the program is determined by events
such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs.
● Key Concepts:
○ Event: An action or occurrence recognized by the program (e.g., clicking a button).
○ Event Listener: A function or method that waits for an event to happen.
○ Event Handler: A function that gets called in response to an event.
○ Real-Time Systems:
■ Systems like sensors, IoT devices, and gaming applications that react to external stimuli in real-time.
○ Web Development:
■ JavaScript is heavily event-driven, responding to user interactions such as clicks, form submissions, and page loads.
8
Event Loop, Event Handling and Event Listeners
● Event Loop:
○ The event loop continuously checks for events and dispatches them to the appropriate event handlers.
○ The loop processes events like user inputs or system messages and executes the corresponding code.
● Event Handling:
○ Once an event is detected, the event handler is triggered to execute a block of code.
○ Example: In a button click event, the event handler performs the action associated with the button.
● Event Listeners
○ A procedure or function that waits for an event to occur.
○ Example: javascript
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
● Explanation:
● In this example, the addEventListener function attaches a listener to a button with the ID myButton. When the button
is clicked, it triggers the event handler (an alert message).
9
Common Events in Event-Driven Programming
● System Events:
○ Load Events: load (when a page or component is loaded).
○ Resize Events: resize (when a window or element is resized).
○ Scroll Events: scroll (when the user scrolls on a page).
10
Writing Event Handlers
● Event Handlers: Functions or methods that are triggered by an event listener when an event occurs.
● Example:
import tkinter as tk
def on_button_click():
print("Button clicked!")
window = tk.Tk()
button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack()
window.mainloop()
● Explanation: When the user clicks the button, the on_button_click function is executed, printing "Button clicked!" in
the console.
11
Implementing Event-Driven Programming in Python
● Python has several frameworks for building Graphical User Interfaces (GUI). One of such framework is tkinter.
● Tkinter is a standard Python library used for creating Graphical User Interfaces (GUIs).
● Why Use Tkinter?
○ Beginner-Friendly: Its simplicity makes it ideal for learning and experimenting with GUI programming.
○ Pre-Installed: No additional installation is required for most Python distributions.
○ Cross-Platform: Applications built with Tkinter can run on Windows, macOS, and Linux.
○ Customizable: Provides a variety of widgets like buttons, labels, text fields, and more, which can be customized
to meet specific needs.
○ Lightweight: Doesn't require any additional dependencies.
12
Tkinter
● When building GUI applications with Tkinter, understanding its fundamental concepts is crucial.
● Widgets: Widgets are the building blocks of a Tkinter application. They represent UI elements such as buttons, labels,
input fields, etc.
○ Common Widgets
Widget Description
● Events and Callbacks: Events are actions triggered by the user, such as clicking a button, typing text, or moving the
mouse. In Tkinter, you can bind events to widgets and respond to them using callback functions.
● Event Handling:
○ Events include clicks (<Button-1>), key presses (<Key>), mouse movements, etc.
○ Callbacks are functions executed when an event occurs.
● Layout Management: Tkinter provides three layout managers to arrange widgets in the window
○ Pack: Simplistic layout; stacks widgets vertically or horizontally.
○ Grid: Uses rows and columns for precise placement.
○ Place: Absolute positioning with x, y coordinates.
● The Mainloop: The mainloop is the core of every Tkinter application. It is an event-driven loop that listens for user
inputs and keeps the application window open. Without the mainloop, the window would close immediately after
being created.
15
Tkinter
● Styling and Configuration: Widgets in Tkinter can be customized with properties like fonts, colors, sizes, and more.
● Common styling options include:
○ Font: Set the font type, size, and style.
○ Foreground (fg): Text color.
○ Background (bg): Widget background color.
○ Padding (padx, pady): Add space around the widget.
● Handling User Input: User input can be collected through widgets like Entry (for text input) or Text (for multi-line
input).
16
Tkinter
17
Tkinter
● Asynchronous Execution:
○ The program does not have to follow a linear flow and can wait for events to occur, making it more interactive.
● Responsiveness:
○ Event-driven programs respond to user input immediately, improving user experience.
● Modularity:
○ Code can be organized into small, independent event handlers that handle specific tasks, making the program easier to maintain.
19
Exception Handling
20
Exception Handling
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
21
Exception Handling
try:
value = int(input("Enter a number: ")) # Might raise a ValueError
print(f"The square of the number is {value ** 2}")
except ValueError:
print("Error: Please enter a valid integer.")
22
Exception Handling
try:
file = open("example.txt", "r") # Open a file
print(file.read())
except FileNotFoundError:
print("Error: File not found.")
finally:
if 'file' in locals() and not file.closed:
file.close() # Ensure the file is closed
print("File closed.")
23
Exception Handling
class NegativeNumberError(Exception):
pass
def calculate_square_root(number):
if number < 0:
raise NegativeNumberError("Cannot calculate the square root of a negative number.")
return number ** 0.5
try:
print(calculate_square_root(-9))
except NegativeNumberError as e:
print(f"Error: {e}")
24
Exception Handling
● Log Exceptions
● Logging exceptions helps track errors and debug the program. Python’s logging module is ideal for recording
exception details.
● Example:
import logging
logging.basicConfig(filename="app.log", level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("An error occurred: %s", e)
print("An error occurred. Check the logs for more details.")
25
Exception Handling
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"You are {age} years old.")
except ValueError as e:
print(f"Invalid input: {e}. Please try again.")
26
Exception Handling
● By incorporating exception handling, you can make your Python programs more resilient to errors and provide a
better user experience.
● Here's a quick checklist:
○ Use try-except for error handling.
○ Catch specific exceptions to handle errors appropriately.
○ Utilize the finally block for cleanup tasks.
○ Define custom exceptions for unique scenarios.
○ Log exceptions for debugging and monitoring.
○ Handle errors gracefully to improve usability.
● With these techniques, you’ll write code that is robust, reliable, and user-friendly.
27
Strings and String Processing
28
Strings and String Processing
● String Length
● The length of a string is the number of characters it contains, including spaces and symbols. You can find the length
of a string using the len() function.
● Example:
text = "Python Programming"
length = len(text)
print(f"The length of the string is {length}.") # Output: The length of the string is 18.
● Accessing Characters in a String
● Strings in Python are indexed, meaning you can access individual characters using their position. Indexing starts at 0
for the first character.
● Example:
word = "Python"
print(word[0]) # Output: P (first character)
print(word[-1]) # Output: n (last character)
29
Strings and String Processing
● Substrings
● A substring is a portion of a string. You can extract substrings using slicing, which specifies a starting and ending
index.
● Example:
text = "Python Programming"
substring = text[0:6] # Extracts characters from index 0 to 5
print(substring) # Output: Python
● String Searching
● You can search for the presence of a character or substring within a string using the in keyword or the .find()
method.
● Example:
text = "Learning Python is fun!"
print("Python" in text) # Output: True
print(text.find("Python")) # Output: 9 (starting index of "Python")
30
Strings and String Processing
● Replacing Characters
● The .replace() method allows you to replace certain characters or substrings with others.
● Example:
text = "I love programming."
new_text = text.replace("love", "enjoy")
print(new_text) # Output: I enjoy programming.
● Changing Case
● Python provides methods to convert the case of strings, such as .lower(), .upper(), and .capitalize().
● Example:
text = "Python is Amazing"
print(text.lower()) # Output: python is amazing
print(text.upper()) # Output: PYTHON IS AMAZING
print(text.capitalize()) # Output: Python is amazing
31
Strings and String Processing
● String Formatting
● Strings can be formatted to display data in a structured way. Python provides various methods for string formatting,
including f-strings.
● Example:
name = "Alice"
age = 25
print(f"My name is {name}, and I am {age} years old.")
# Output: My name is Alice, and I am 25 years old.
32
Strings and String Processing
import tkinter as tk
● Example:
# Event handler with exception handling and string manipulation
def greet_user():
try:
name = name_entry.get().strip()
if not name:
raise ValueError("Name cannot be empty.")
greeting_label.config(text=f"Hello, {name.capitalize()}!") # Capitalize name
except ValueError as e:
greeting_label.config(text=f"Error: {e}")
root.mainloop() 33
Real-World Applications of Event-Driven Programming
● Interactive Websites:
○ Websites that respond to clicks, form submissions, or mouse movements (e.g., JavaScript in web development).
● Game Development:
○ Games constantly respond to user inputs like keyboard presses or mouse clicks to control characters or perform actions.
● IoT Devices:
○ Sensors in smart devices that respond to environmental changes (e.g., temperature, motion).
● Mobile Apps:
○ Applications that handle touch events, gestures, and other mobile-specific actions.
34
In-Class Activity - Building an Interactive Application
● Task: Build a simple event-driven program using Python and Tkinter to create a click counter. Each time the button is
clicked, the program should increment a counter and display the result.
● Steps:
○ Create a Tkinter window with a label and a button.
○ Use an event handler to increment the counter when the button is clicked.
○ Display the updated count on the label.
● Challenge: Extend the program to include a "Reset" button that resets the counter to zero.
35
Common Pitfalls in Event-Driven Programming
● Memory Leaks:
○ Incorrectly attaching event listeners that are not removed can lead to memory leaks and performance issues.
36
Best Practices for Event-Driven Programming
● Asynchronous Execution:
○ Use asynchronous techniques (e.g., asyncio in Python or setTimeout in JavaScript) for tasks that take a long time to complete to
avoid blocking the main thread.
37
Summary
● Event-Driven Programming
○ Program flow is determined by events like user input or system messages.
● Event Listeners and Handlers
○ Event Listeners: Wait for specific events (e.g., button clicks).
○ Event Handlers: Define logic to respond to those events.
● Asynchronous Programming
○ Ensures applications remain responsive with non-blocking operations.
● Graphical User Interfaces (GUI) with Tkinter
○ Tkinter enables interactive GUIs with event-driven elements like buttons and input fields.
● Exception Handling
○ Prevent crashes and provide user feedback using try-except blocks.
● String Manipulation
○ Process and validate user inputs, format text, and display meaningful outputs.
38
Recap: Key Takeaways
39
Assignment
● Task: Create a basic GUI application using Python and Tkinter. The application should have a text field and a button.
When the user enters text in the field and clicks the button, display the entered text in a label.
● Group Discussion: Share your thoughts on how event-driven programming differs from traditional programming
paradigms and discuss challenges you faced in the practical exercise.
40