Fourth Contact_Part 5 813
Fourth Contact_Part 5 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 5
6
Learning Outcomes
7
Why Program Organization Matters
8
Structuring Your Program
● Modules:
○ A module is a file (code library) containing Python definitions and statements.
○ Modules help in organizing related functions, classes, and variables into separate files.
○ Example: A file math_functions.py containing functions like add() and multiply().
● Packages:
○ A package is a collection of modules.
○ Packages allow for a hierarchical structure of the program.
○ Example: A package utilities might contain modules like math_functions.py, string_functions.py, etc.
9
Importing Modules and Packages
● Importing a Module:
import math_functions
result = math_functions.add(5, 3)
● Importing Specific Functions from a Module:
from math_functions import add
result = add(5, 3)
● Importing Packages:
from utilities import math_functions
result = math_functions.multiply(2, 5)
● Explanation: Use import to bring functions, classes, or entire modules into your program, enabling better code
organization.
10
Principles of Program Structure
● Separation of Concerns:
○ Separate different functionalities into distinct sections of code (e.g., separate data handling, business logic, and presentation
layers).
● Modularity:
○ Break your program into smaller, reusable modules or functions.
○ This makes the code easier to test and debug.
11
API
● An Application Programming Interface (API) is a set of rules that allows different software programs to
communicate with each other.
● Types of APIs:
○ Web APIs: Enable communication between a client and server over the web (e.g., REST APIs).
○ Library APIs: Provide functions to interact with a library (e.g., TensorFlow's API for machine learning).
12
RESTful APIs
● REST (Representational State Transfer) is a web-based architectural style for designing networked applications,
where HTTP requests are used to access and manipulate resources.
● HTTP Methods:
○ GET: Retrieve data from a server.
○ POST: Send new data to a server.
○ PUT: Update existing data on a server.
○ DELETE: Remove data from a server.
13
Making API Requests with Python
● Example:
import requests
# Send a GET request to a weather API
response = requests.get("https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key")
# Check if the request was successful
if response.status_code == 200:
data = response.json()
print(data)
else:
print("Error:", response.status_code)
● Explanation:
○ A GET request is sent to the weather API to fetch data for London.
○ If the request is successful, the response is converted to JSON format and printed.
14
Handling API Responses
● JSON Responses:
○ Many APIs return data in JSON (JavaScript Object Notation) format, which is easy to parse and use in your program.
● Example:
import requests
response = requests.get("https://api.example.com/data")
data = response.json()
print(data)
● Error Handling:
○ Check the status code of the response to handle errors properly.
● Example:
if response.status_code == 404:
print("Resource not found")
● Authentication:
○ Some APIs require authentication via API keys, OAuth tokens, etc.
○ Include the API key in the request header or query string.
15
API Rate Limits and Best Practices
● Rate Limits:
○ Many APIs limit the number of requests you can make in a certain period (e.g., 100 requests per minute).
○ Exceeding the limit may result in being temporarily blocked from accessing the API.
● Best Practices:
○ Cache Responses: Store API responses to avoid repeated requests for the same data.
○ Error Handling: Implement robust error handling for cases like rate limits, server downtime, or invalid responses.
○ Respect Rate Limits: Follow the API's rate limits and avoid overloading the server.
16
Using API for Iterators, Enumerators, List, Stack,
and Queue
● API is a set of methods and tools that allow developers to interact with a library or framework.
● API for Data Structures
○ Provides ready-to-use functionality for common operations like traversal, addition, and deletion.
○ Simplifies development by abstracting underlying complexities.
17
Using API for Iterators, Enumerators, List, Stack,
and Queue
● Iterator: An object used to traverse through all elements in a collection, one element at a time
● Application: Efficient looping, especially for large datasets.
● Key Features:
○ Keeps track of the current position in the sequence.
○ Can be used in loops like for or with next().
● Use Case: Iterating through files, large datasets, or custom collections
● Example:
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator)) # Output: 10
print(next(iterator)) # Output: 20
18
Using API for Iterators, Enumerators, List, Stack,
and Queue
● Enumerator: Similar to iterators but used to traverse both index and value in a collection
● Application: Simplifies working with indexed collections.
● Key Features:
○ Often used for numbered collections like lists or tuples.
○ Returns index-value pairs.
● Use Case: Accessing both position and content in loops
● Example:
fruits = ['apple', 'banana', 'cherry’]
19
Using API for Iterators, Enumerators, List, Stack,
and Queue
● List API: An ordered, mutable collection of elements
● Application: Versatile, supports dynamic resizing and operations.
● Key Methods:
○ append(item): Adds an item to the end of the list.
○ insert(index, item): Inserts an item at a specified position.
○ remove(item): Removes the first occurrence of the item.
○ sort(): Sorts the list.
● Use Case: Managing ordered data like a task list or a sequence of events
● Example:
names = ['Alice', 'Bob', 'Charlie’]
names.append('Diana’)
names.sort()
print(names) # Output: ['Alice', 'Bob', 'Charlie', 'Diana']
20
Using API for Iterators, Enumerators, List, Stack,
and Queue
● Stack API: A Last-In-First-Out (LIFO) data structure
● Application: Useful for scenarios needing LIFO, e.g., reversing a string.
● Key Methods:
○ append(item): Push an item onto the stack.
○ pop(): Remove and return the top item.
○ peek: Not explicitly available but can be simulated using stack[-1].
● Use Case: Undo functionality in text editors, backtracking algorithms
● Example:
stack.append(10) # Push
stack.append(20)
print(stack.pop()) # Output: 20
print(stack[-1]) # Output: 10 (peek)
21
Using API for Iterators, Enumerators, List, Stack,
and Queue
● Queue API: A First-In-First-Out (FIFO) data structure
● Application: Crucial for FIFO scenarios, e.g., task scheduling or messaging systems.
● Key Methods:
○ enqueue: Add an element (simulated using append).
○ dequeue: Remove the front element (simulated using pop(0)).
● Use Case: Scheduling tasks, processing events, or managing buffers
● Example:
from collections import deque
queue = deque()
queue.append(1) # Enqueue
queue.append(2)
print(queue.popleft()) # Output: 1 (Dequeue)
print(queue) # Output: deque([2])
22
Introduction to Searching and Sorting
23
Introduction to Searching and Sorting
● Linear Search: A simple search algorithm that checks every element in the list until the target is found or the list ends
● Use Case: When the list is unsorted or small.
● Example:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if element is not found
24
Introduction to Searching and Sorting
● Binary Search: A more efficient search algorithm that works on sorted arrays. It repeatedly divides the search
interval in half
● Use Case: When the list is sorted.
● Example: def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid # Element found at index mid
elif arr[mid] < target:
low = mid + 1 # Search the right half
else:
high = mid - 1 # Search the left half
return -1 # Element not found
26
Introduction to Searching and Sorting
● Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and
swaps them if they are in the wrong order
● Use Case: Small datasets or when simplicity is important.
● Example:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap
27
Introduction to Searching and Sorting
● Insertion Sort: Builds the sorted array one element at a time by picking elements from the unsorted part and
inserting them into the correct position in the sorted part
● Use Case: When a list is nearly sorted
● Example:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
28
Introduction to Searching and Sorting
● Merge Sort: A divide-and-conquer sorting algorithm that divides the array into halves, recursively sorts each half,
and then merges the sorted halves
● Use Case: Efficient for large datasets
● Example:
i=j=k=0
def merge_sort(arr): while i < len(left_half) and j < len(right_half):
if len(arr) > 1: if left_half[i] < right_half[j]:
mid = len(arr) // 2 arr[k] = left_half[i]
left_half = arr[:mid] i += 1 while j < len(right_half):
right_half = arr[mid:] else: arr[k] = right_half[j]
arr[k] = right_half[j] j += 1
merge_sort(left_half) j += 1 k += 1
merge_sort(right_half) k += 1
arr = [64, 34, 25, 12, 22, 11, 90]
while i < len(left_half): merge_sort(arr)
arr[k] = left_half[i] print(arr) # Output: [11, 12, 22, 25, 34, 64, 90]
i += 1
k += 1 29
Introduction to Searching and Sorting
● Merge Sort
30
In-Class Activity - API Integration
● Task: Use a public API to create a simple application that fetches real-time data.
● API Example: Use the OpenWeatherMap API to retrieve and display the current weather for a city provided by the
user.
● Steps:
○ Sign up for an API key on OpenWeatherMap.
○ Make a GET request to the API using the requests library.
○ Parse the JSON response and display the weather information.
● Challenge: Extend the program to allow the user to enter different cities and see their weather data.
31
Common API Errors and Troubleshooting
● Timeout Errors:
○ The request took too long to get a response. Try increasing the timeout or handle the error gracefully.
32
Summary
● Program Organization:
Modular design with packages and modules enhances code readability, maintainability, and collaboration.
● APIs and Data Structures:
APIs simplify interaction with complex structures like iterators, enumerators, lists, stacks, and queues, enabling
efficient data management.
● Searching and Sorting:
Algorithms like Linear and Binary Search, Bubble Sort, and Merge Sort organize and retrieve data efficiently based
on the problem's needs.
33
Recap: Key Takeaways
● Program Organization:
○ Organizing code into modules and packages improves maintainability, readability, and collaboration.
● API Basics:
○ APIs allow different software systems to communicate and exchange data.
○ RESTful APIs use HTTP methods to interact with resources.
● Making API Requests:
○ Use the requests library in Python to send HTTP requests, handle responses, and integrate external data.
● Best Practices:
○ Handle errors and rate limits properly when using APIs in your program.
● Iterators and Enumerators :
○ Enable effective traversal of collections.
● Stacks and Queues:
○ Manage data in specific orders using simple APIs.
● Searching and Sorting:
○ Optimize data handling through various algorithms.
34
Assignment
● Task: Write a Python program that uses the GitHub API to retrieve a list of repositories for a specific user and display
the name and description of each repository.
● Task: Write Python implementations of the following algorithms:
○ Searching: Linear Search, Binary Search
○ Sorting: Bubble Sort, Merge Sort
● Create a list of 1,000 random integers and test each algorithm.
● Group Discussion: Share experiences integrating an API into a program. What challenges did you face, and how did
you resolve them?
35