0% found this document useful (0 votes)
7 views35 pages

Fourth Contact_Part 5 813

The document outlines a course on Programming Fundamentals, covering key concepts such as variables, loops, functions, and object-oriented programming. It aims to develop proficiency in programming languages like Java, C++, and Python, while emphasizing software development methodologies and best practices. The course includes practical applications of APIs, data structures, and algorithms, along with ethical considerations in software development.
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)
7 views35 pages

Fourth Contact_Part 5 813

The document outlines a course on Programming Fundamentals, covering key concepts such as variables, loops, functions, and object-oriented programming. It aims to develop proficiency in programming languages like Java, C++, and Python, while emphasizing software development methodologies and best practices. The course includes practical applications of APIs, data structures, and algorithms, along with ethical considerations in software development.
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/ 35

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 5

Program Organization and API Usage


Program structure and organization
API usage for common data structures (List, Stack, Queue)
Searching and Sorting Algorithms

6
Learning Outcomes

● Understand the importance of organizing code into modules and packages.


● Apply principles of program structure for better readability and maintainability.
● Understand what APIs are and how they are used to interact with external services.
● Make API calls using common libraries and handle responses in a programming language (e.g., Python).
● Understand and implement searching and sorting algorithms

7
Why Program Organization Matters

● Readability: Well-structured code is easier to read and understand.


● Maintainability: Organized code can be updated and modified with minimal effort.
● Reusability: Code that is modularized can be reused across different projects.
● Collaboration: In teams, organized code enables multiple developers to work on different parts of the program
simultaneously.

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.

● Example Directory Structure:


my_project/
├── main.py
├── utilities/
│ ├── __init__.py
│ ├── math_functions.py
│ └── string_functions.py
└── data/
└── database.py

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

● Single Responsibility Principle:


○ Each module or function should have a single purpose or responsibility.
○ Example: A function that only calculates the average of a list, without handling input/output.

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

● DRY (Don't Repeat Yourself):


○ Avoid duplicate code by using functions or modules that can be reused across the project.

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

● Examples of Popular APIs:


○ Google Maps API: Provides geographic data and map services.
○ Twitter API: Enables access to Twitter data (tweets, user profiles).
○ Weather API: Provides weather data and forecasts.

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.

● Example of an HTTP Request:


GET /users
POST /users
● Response Codes:
○ 200 OK: Request was successful.
○ 404 Not Found: The resource was not found.
○ 500 Internal Server Error: A server error occurred.

13
Making API Requests with Python

● Using the requests Library:


○ The requests library in Python is commonly used to send HTTP requests to APIs.

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

● Objects and Interfaces


○ Iterators
○ Enumerators
○ List API
○ Stack API
○ Queue API

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’]

for index, fruit in enumerate(fruits):


print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: 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

● Searching Algorithms: Used to find the position of an element in a collection.


○ Examples: Linear Search, Binary Search.
● Sorting Algorithms: Arrange the elements of a collection in a specific order.
○ Examples: Bubble Sort, Insertion Sort, Merge Sort.

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

arr = [10, 20, 30, 40, 50]


target = 30
print(linear_search(arr, target)) # Output: 2

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

arr = [10, 20, 30, 40, 50]


target = 30
print(binary_search(arr, target)) # Output: 2 25
Introduction to Searching and Sorting

● Binary vs Linear Search Methods

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

arr = [64, 34, 25, 12, 22, 11, 90]


bubble_sort(arr)
print(arr) # Output: [11, 12, 22, 25, 34, 64, 90]

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

arr = [64, 34, 25, 12, 22, 11, 90]


insertion_sort(arr)
print(arr) # Output: [11, 12, 22, 25, 34, 64, 90]

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

● Invalid API Key:


○ Ensure that you are using a valid API key and include it in the request headers or parameters.

● 404 Not Found:


○ The endpoint or resource might not exist. Double-check the API documentation.

● 500 Internal Server Error:


○ The server might be down or experiencing issues. Try again later.

● 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

You might also like