[go: up one dir, main page]

0% found this document useful (0 votes)
11 views40 pages

Fifth Contact - Part 6 813

The document outlines a course on Programming Fundamentals, covering key concepts such as variables, loops, functions, and object-oriented programming. It emphasizes the importance of coding in technology, software development methodologies, and ethical considerations in programming. The course aims to enhance problem-solving skills and proficiency in languages like Java, C++, and Python through hands-on projects and event-driven programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

Fifth Contact - Part 6 813

The document outlines a course on Programming Fundamentals, covering key concepts such as variables, loops, functions, and object-oriented programming. It emphasizes the importance of coding in technology, software development methodologies, and ethical considerations in programming. The course aims to enhance problem-solving skills and proficiency in languages like Java, C++, and Python through hands-on projects and event-driven programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

MIT 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

Table of 02 Study Session 2: Basic Data Types and Variables


03 Study Session 3: Object-Oriented Concepts
Contents 04 Revision
05 Study Session 4: Program Organization and API Usage
06 Study Session 5: Event-Driven Programming
07 Study Session 6: Input/Output and Control Structures
08 Study Session 7: Recursive Algorithms and Inheritance
09 Revision
10 Study Session 8: Polymorphism
11 Study Session 9: Project Development
12 Revision
13 Revision

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

● By the end of this course, you should be able to:


○ develop proficiency in computer programming concepts and principles.
○ enhance your problem-solving skills through coding and algorithm development.
○ cultivate a strong foundation in programming languages such as Java, C++, and Python.
○ explore software development methodologies and best practices.
○ prepare yourself for advanced programming courses and real-world applications in the field of computer
programming.

4
Course Objectives

● At the end of the course, you should be able to:


○ understand fundamental programming concepts such as variables, loops, functions, and data structures.
○ apply programming principles to solve problems and write efficient code.
○ practice coding in different programming languages and develop proficiency in at least one language.
○ learn about software development processes, including debugging and testing techniques.
○ engage in hands-on programming projects to demonstrate understanding of concepts and skills acquired in
the course.

5
Week 6

Event-Driven Programming
Event-driven programming fundamentals
Exception handling and debugging
Strings and String Processing

6
Learning Outcomes

● Understand the principles of event-driven programming.


● Write programs that handle and respond to events such as user input, clicks, or system notifications.
● Implement event listeners and handlers in your code.
● Develop interactive applications using event-driven programming.
● Handle exceptions effectively when programming

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.

● Examples of Event-Driven Programming


○ Graphical User Interfaces (GUIs):
■ Applications with buttons, sliders, and forms that trigger actions based on user input (e.g., desktop applications, websites).

○ 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

● User Input Events:


○ Mouse Events: click, dblclick, mousemove, mousedown, mouseup.
○ Keyboard Events: keydown, keyup, keypress.
○ Form Events: submit, change, focus, blur.

● 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

Label Displays static text or images.


Button A clickable button to perform an action.
Entry A single-line text input field.
Text A multi-line text input field.
Frame A container to organize other widgets.
Canvas Used for drawing shapes, lines, and custom graphics.
Checkbutton A checkbox widget for binary options.
Scrollbar Adds scrolling functionality to other widgets.
Menu Adds a menu bar to the application window.
13
Tkinter

● 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.

Event Name Description

<Button-1> Left mouse button click.


<Button-2> Middle mouse button click.
<Button-3> Right mouse button click.
<Double-Button-1> Double left-click.
<Enter> Mouse enters the widget area.
<Leave> Mouse leaves the widget area.
<KeyPress> Any key is pressed.
<KeyPress-a> Specific key (e.g., "a") is pressed.
14
Tkinter

● 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

● Example: Creating a Simple GUI:


import tkinter as tk
def handle_click():
label.config(text="Button Pressed!")
window = tk.Tk()
window.title("Event-Driven Example")
label = tk.Label(window, text="Press the button")
label.pack()
button = tk.Button(window, text="Click Me", command=handle_click)
button.pack()
window.mainloop()
● Explanation: In this example, the handle_click function changes the text of the label when the button is pressed. The
window.mainloop() keeps the GUI running and waits for events.

17
Tkinter

● Advanced Example: Calculator App


import tkinter as tk # Entry widget for input/output
entry = tk.Entry(root, font=("Arial", 18), justify="right", bd=5)
def click(button_text): entry.pack(fill="both", padx=10, pady=10)
if button_text == "=":
try: # Button layout
result = eval(entry.get()) # Evaluate the math expression buttons = [
entry.delete(0, tk.END) ["7", "8", "9", "/"],
entry.insert(0, str(result)) ["4", "5", "6", "*"],
except Exception: ["1", "2", "3", "-"],
entry.delete(0, tk.END) ["C", "0", "=", "+"]
entry.insert(0, "Error") ]
elif button_text == "C":
entry.delete(0, tk.END) # Clear the entry field # Add buttons to the window
else: for row in buttons:
entry.insert(tk.END, button_text) # Add button text to the entry field frame = tk.Frame(root)
# Create the main window frame.pack(fill="both", expand=True)
root = tk.Tk() for button_text in row:
root.title("Simple Calculator") button = tk.Button(frame, text=button_text, font=("Arial", 16),
root.geometry("300x400") command=lambda text=button_text: click(text))
button.pack(side="left", fill="both", expand=True)

# Run the application


root.mainloop() 18
Advantages of Event-Driven Programming

● 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

● Exception handling is crucial to writing robust and reliable programs.


● Exceptions are unexpected events or errors that occur during a program's execution due to invalid inputs,
unavailable resources, or other programming issues.
● Using proper exception handling techniques ensures your program doesn't crash unexpectedly and behaves
predictably.
● Here’s how to handle exceptions effectively

20
Exception Handling

● Use try-except Blocks


● A try-except block is used to catch and handle exceptions. Code that might throw an exception is placed inside the
try block, and any exceptions are caught and handled in the except block.
● Example:

try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")

21
Exception Handling

● Catch Specific Exceptions


● Catching specific exceptions allows you to respond differently depending on the exception type, rather than using a
generic except clause.
● Example:

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

● Use the finally Block


● The finally block defines code that is always executed, regardless of whether an exception occurs. It is commonly
used for cleanup tasks like closing files or releasing resources.
● Example:

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

● Throw Custom Exceptions


● You can define and throw custom exceptions to handle specific error conditions in your program. This improves
error messaging and program structure.
● Example:

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

● Handle Exceptions Gracefully


● Providing user-friendly error messages and recovery options enhances the user experience.
● Example:

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

● In programming, a string is a sequence of characters—letters, numbers, symbols, or spaces—used to represent text.


● Strings are an essential part of nearly every program, as text manipulation is a common requirement in tasks
ranging from displaying information to processing user input.
● By understanding how to process and manipulate strings, you unlock powerful tools for interacting with text in your
programs.
● Basic String Operations
● String Concatenation
● Concatenation is the process of combining two or more strings to create a new string. In Python, this is done using
the + operator.
● Example:
greeting = "Hello"
name = "World"
message = greeting + " " + name
print(message) # Output: Hello World

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}")

# GUI Setup with Tkinter


root = tk.Tk()
root.title("Event-Driven GUI Example")

tk.Label(root, text="Enter your name:").pack(pady=5)


name_entry = tk.Entry(root)
name_entry.pack(pady=5)

tk.Button(root, text="Greet", command=greet_user).pack(pady=5)


greeting_label = tk.Label(root, text="")
greeting_label.pack(pady=10)

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

● Blocking the Event Loop:


○ Long-running tasks can block the event loop, causing the program to become unresponsive. Use asynchronous programming
techniques to avoid this.

● Memory Leaks:
○ Incorrectly attaching event listeners that are not removed can lead to memory leaks and performance issues.

● Overuse of Global Variables:


○ Over-relying on global variables to store event-related data can make code harder to maintain and debug.

36
Best Practices for Event-Driven Programming

● Use Modular Event Handlers:


○ Break event handlers into small, reusable functions to improve code clarity and reusability.

● 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.

● Optimize Event Listeners:


○ Ensure you are not attaching unnecessary event listeners that can slow down your program.

● Remove Unnecessary Event Listeners:


○ Clean up event listeners that are no longer needed to avoid memory leaks.

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

● Event-Driven Programming makes applications interactive and responsive.


● Listeners and Handlers ensure effective responses to user actions.
● Asynchronous Techniques maintain responsiveness during long-running tasks.
● Tkinter is a powerful tool for building event-driven graphical interfaces.
● Exception Handling ensures graceful error management and enhances user experience.
● String Manipulation is vital for input validation and dynamic content handling in applications.

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

You might also like