Course Lecturer: Mr.
Utoda Reuben
Lecture Note Summary: Computer Lab1
Course: Computer Practical using Python
Target Audience: Year 1 Computer Science Students
Objective: To understand the principles, architectures, and technologies
underpinning computer practical, focusing on basic computer practical ethics,
hands-on experience in programming using Python, and other programming tools.
Introduction to Computer Practical
What is a Computer Laboratory?
A computer laboratory is a dedicated space equipped with computers and
related resources for learning, practicing, and conducting computer-related
activities. It provides a controlled environment where students can:
• Learn computer skills (e.g., typing, software use).
• Practice programming, data processing, and internet research.
• Conduct experiments or simulations using specialized software
Purpose of a Computer Lab:
• To facilitate hands-on learning and practical application of computer
knowledge.
• To provide access to technology for academic and research purposes.
Components of a Computer Laboratory
A typical computer lab contains the following:
1. Hardware:
• Computers: Desktops or laptops with monitors, keyboards, and mice.
• Central Processing Unit (CPU): The brain of the computer that processes
instructions.
• Input Devices: Keyboard, mouse, scanner, etc.
• Output Devices: Monitor, printer, speakers, etc.
• Storage Devices: Hard drives, USB drives, or external storage.
• Networking Equipment: Routers, switches, or LAN cables for internet
connectivity.
2. Software:
• Operating Systems: Windows, macOS, or Linux.
• Applications: Microsoft Office (Word, Excel, PowerPoint), web browsers,
programming tools, etc.
3. Furniture and Accessories:
• Ergonomic chairs and tables.
• Power supply units, extension cords, and surge protectors.
• Projectors or smartboards for teaching.
4. Internet and Network:
• High-speed internet for research and communication.
• Local Area Network (LAN) for file sharing and collaboration.
3. Safety and Usage Guidelines in the Computer Laboratory
To ensure a productive and safe environment, students must adhere to the
following rules:1. Safety Rules:
• Do not eat or drink in the lab to avoid damaging equipment.
• Keep bags and personal items in designated areas to prevent tripping hazards.
• Handle equipment carefully to avoid damage.
• Report any faulty equipment (e.g., loose cables, broken keyboards) to the lab
instructor immediately.
• Avoid touching exposed wires or power sockets.
2. Usage Rules:
• Log in with your assigned username and password (if applicable).
• Use the computer for academic purposes only; avoid games or unauthorized
websites.
• Save your work regularly to avoid data loss.
• Do not install software or modify system settings without permission.
• Log out and shut down the computer properly after use.
3. Etiquette:
• Keep noise levels low to maintain a conducive environment.
• Respect other users’ space and equipment.
• Seek permission before using shared resources like printers.
4. Basic Computer Operations in the Lab
a. Starting a Computer
1. Press the power button on the CPU or laptop.
2. Wait for the operating system to load (e.g., Windows login screen).
3. Enter your username and password (if required).
4. Familiarize yourself with the desktop interface, including icons, taskbar, and
start menu.
b. Shutting Down a Computer
1. Save all open files and close all applications.
2. Click the Start button (bottom-left corner in Windows).
3. Select Shut Down or Power Off from the menu.
4. Wait for the system to completely power off before leaving.
c. Basic File Management
• Creating a Folder: Right-click on the desktop or in File Explorer → Select New
→ Folder → Name the folder.
• Saving a File: When saving a document, choose a location (e.g., Desktop,
Documents folder) and give the file a meaningful name.
• Copying/Moving Files: Right-click a file → Select Copy or Cut → Navigate to
the destination folder → Right-click → Select Paste.
5. Introduction to Common Software in the Lab
1. Microsoft Word: For typing documents, reports, and essays.
2. Microsoft Excel: For data analysis, calculations, and creating charts.
3. Web Browsers: For internet research (e.g., Google Chrome, Mozilla Firefox).
4. Antivirus Software: To protect the computer from viruses and malware.
Activity:
• Open Microsoft Word and type a short paragraph about yourself.
• Save the document in a folder named “My Files” on the desktop.
6. Importance of Computer Labs in Education
• Hands-On Learning: Provides practical experience with software and
hardware.
• Skill Development: Enhances digital literacy, programming, and research
skills.
• Collaboration: Enables group projects and resource sharing.
• Access to Technology: Bridges the gap for students without personal
computers.
HARDWARE REQUIREMENT:
• Processor: Intel Core i3 or equivalent.
• RAM: 8GB or higher recommended.
• Storage: Minimum 256GB SSD for better performance.
• Display: 15-inch monitor or larger for better workspace.
• Graphics Card: Integrated graphics are sufficient.
• External Hard Drive: For backups and additionalstorage.
• Internet connectivity.
• Operating System : Windows 10
Introduction to Python Programming
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum in the late 1980s and officially released in
1991. Today, it is widely used in various fields such as web development, data science,
artificial intelligence, machine learning, automation, and software development.
Why Learn Python?
Simple Syntax: Its code looks like English, making it easy for beginners to understand and
write.
Versatile: Python can be used for small scripts as well as large applications.
Large Community: There is a large support community and many learning resources.
Portable: Python works on different operating systems like Windows, Mac, and Linux.
Powerful Libraries: It has numerous libraries for various applications (e.g., math, data
analysis, graphics).
Features of Python
Interpreted: Code is executed line by line.
Object-Oriented: Supports classes and objects for programming.
High-Level Language: Easier to read, write, and maintain.
Extensible: Can integrate with other languages like C or C++.
Dynamic Typing: No need to declare variable types explicitly.
First Python Program
A simple Python program to display “Hello, World!”:
print("Hello, World!")
Here, print() is a built-in function that outputs text to the screen.
Variable Declaration in Python
A variable is a named storage location in a program used to hold data that can be
modified during program execution.
How to Declare a Variable in Python
• Python does not require explicit declaration of variable types (it’s dynamically
typed).
• Assign a value to a variable using the assignment operator (=).
• Variable names:
• Must start with a letter (a-z, A-Z) or underscore (_).
• Can contain letters, numbers, and underscores.
• Case-sensitive (e.g., name and Name are different).
• Avoid Python keywords (e.g., if, for, while).
Examples:
name = "Alice" # String variable
age = 20 # Integer variable
height = 5.6 # Float variable
is_student = True # Boolean variable
Types of Variables
Variables in Python can be categorized based on their scope (where they are
accessible):
1. Local Variables: Declared inside a function and accessible only within that
function.
def calculate():
x = 10 # Local variable
print(x)
calculate() # Output: 10
# print(x) # Error: x is not defined outside the function
2. Global Variables: Declared outside functions and accessible throughout the
y = 5 # Global variable
def show():
print(y) # Access global variable
show() # Output: 5
Note: Use global variables carefully to avoid unintended changes.
Data Types in Python
Python supports several built-in data types to represent different kinds of data.
Data type. Description Example
int Interger ( whole number. Age=25
Float Float-point( decimal num) height=5.7
Str String ( text or characters) name = “John”
Bool. Boolean ( true or False ) is_active = True
Nonetype Represents absent of a value. result= none
Checking Data Type: Use the type() function.
x = 10
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
Activity: Write a Python program to declare variables of different data types and
print their types.
Data Structures in Python
Data structures are ways to organize and store data for efficient access and
manipulation. Python’s built-in data structures include:
1. List: Ordered, mutable collection of items.
• Syntax: my_list = [1, 2, "apple", True]
• Access: my_list[0] → 1
• Modify: my_list[1] = 5
• Example:
fruits = ["apple", "banana", "orange"]
print(fruits[1]) # Output: banana
fruits.append("mango") # Add item
print(fruits) # Output: ['apple', 'banana', 'orange', 'mango']
2. Tuple: Ordered, immutable collection.
• Syntax: my_tuple = (1, 2, 3)
• Access: my_tuple[0] → 1
• Example:
coordinates = (10, 20)
print(coordinates[1]) # Output: 20
# coordinates[1] = 30 # Error: Tuples are immutable
3. Dictionary: Key-value pairs, mutable.
• Syntax: my_dict = {"name": "Alice", "age": 20}
• Access: my_dict["name"] → "Alice"
• Example:
student = {"name": "Bob", "grade": "A"}
print(student["name"]) # Output: Bob
student["grade"] = "B" # Update value
print(student) # Output: {'name': 'Bob', 'grade': 'B'}
4. Set: Unordered collection of unique items.
• Syntax: my_set = {1, 2, 3}
numbers = {1, 2, 2, 3}
print(numbers) # Output: {1, 2, 3} # Duplicates removed
numbers.add(4)
print(numbers) # Output: {1, 2, 3, 4}
Activity: Create a list of 3 fruits, a tuple of 2 numbers, and a dictionary with your
name and age. Print each.
Errors in Python Programming
When writing Python programs, errors are common, especially for beginners. An error is a
problem in the program that prevents it from running correctly. Understanding errors helps in
debugging and writing better code.
Types of Errors in Python
1. Syntax Errors
• These occur when the rules of Python syntax are violated.
• It is like wrong grammar in English.
• The program will not run until the error is corrected.
Example: print("Hello, World!"
Error Explanation: Missing closing parenthesis.
Corrected: print("Hello, World!")
2. Runtime Errors
• These errors occur while the program is running.
• They happen after the syntax is correct but the program fails to execute due to invalid
operations.
Example: num = int(input("Enter a number: "))
print(10 / num)
If the user enters 0, it will produce:
ZeroDivisionError: division by zero
Because dividing by zero is mathematically undefined
3. Logical Errors
• These are errors in the logic or meaning of the program.
• The program runs without errors, but the output is incorrect or not as intended.
Example:
# Program to calculate area of a rectangle
length = 5
width = 3
area = length + width # Incorrect logic (should be multiplication)
print("Area is:", area)
Output: Area is: 8
Explanation: The programmer used addition instead of multiplication. The correct formula
is:
area = length * width
4. Name Errors
• Occur when you try to use a variable or function that has not been defined.
Example: print(num)
If num has not been assigned a value earlier, Python will show: NameError: name 'num' is
not defined
5. Type Errors
• Happen when an operation is applied to an object of inappropriate type.
Example: num = 5 + "five"
This will produce: TypeError: unsupported operand type(s) for +: 'int' and 'str'
Because you cannot add an integer and a string directly.
How to Avoid Errors
✅ Check syntax carefully
✅ Test your code with different inputs
✅ Use meaningful variable names
✅ Understand the problem before coding
✅ Practice regularly to identify and fix errors quickly
Practical Lab Activities
1. Variable and Data Type Task:
• Declare variables: name (string), age (integer), height (float), is_student
(boolean).
• Print each variable and its type using type().
2. Data Structure Task:
• Create a list of 4 subjects you’re studying.
• Create a tuple with 2 exam scores.
• Create a dictionary with your name and one subject score.
• Print the second item in the list, first item in the tuple, and a value from the
dictionary.
3. Error Handling Task:
• Write a program to accept a number from the user and calculate its square.
• Use try-except to handle invalid inputs (e.g., non-numeric input).
Programming Language Tools
Programming language tools are techniques and notations used to design, analyse, and
communicate algorithms and program logic before actual coding. They help programmers
plan and structure solutions effectively.
1. Flowcharts
Definition
A flowchart is a graphical representation of an algorithm or program logic using standard
symbols to show the sequence of steps needed to solve a problem.
Features
Visual representation of logic flow.
Uses symbols like ovals (start/end), rectangles (process), diamonds (decision), parallelograms
(input/output), arrows (flow lines).
Advantages
Easy to understand and explain logic flow.
Simplifies debugging and documentation.
2. Pseudocode
Definition
Pseudocode is an informal, high-level description of an algorithm written in a style
resembling programming languages but without strict syntax rules.
Features
Uses plain English mixed with programming-like structures.
Helps focus on logic rather than syntax.
Easily converted to actual programming code later.
Example;
Pseudocode to find maximum of two numbers
Start
Input A, B
If A > B then
Print A is maximum
Else
Print B is maximum
EndIf
End
Advantages
Easy to write and modify.
Language-independent tool for algorithm design.
3. Algorithm
Definition
An algorithm is a finite, well-defined sequence of steps to solve a specific problem.
Properties of Algorithms
Finiteness – must terminate after a finite number of steps.
Definiteness – each step is clearly and unambiguously defined.
Input – zero or more inputs.
Output – at least one output (result).
Effectiveness – each operation is basic enough to be performed precisely.
Example
Problem: Find the sum of two numbers.
Algorithm:
Start
Read A, B
Compute Sum = A + B
Print Sum
End
Programming Languages
Definition
Formal languages with syntax and semantics used to write programs that instruct computers
to perform tasks.
Types of Programming Languages
Low-level (machine, assembly)
High-level (C, Java, Python)
Fourth-generation (SQL)
Fifth-generation (Prolog)
5. Translators
Definition
Tools that convert programs written in high-level or assembly languages into machine
language.
Types
Compiler – translates entire program before execution (e.g. C compiler).
Interpreter – translates and executes line by line (e.g. Python interpreter).
Assembler – converts assembly code to machine code.
6. Debuggers
Definition
Tools used to detect, analyse, and correct errors (bugs) in programs during development.
Features
Allows step-by-step execution.
Monitors variable values at different execution stages.
Essential for logical and runtime error detection.
7. Editors and IDEs (Integrated Development Environments)
Definition
Software tools for writing, editing, compiling, running, and debugging programs within a
single interface.
Examples
Code::Blocks, Dev C++ for C/C++
NetBeans, IntelliJ IDEA for Java
Visual Studio Code, PyCharm for multiple languages
Simple Python practical programs suitable for Year One Computer Science students to
aid their foundational understanding in programming.
1. Print “Hello, World!”
print("Hello, World!")
2. Python program to add Two Numbers
a=5
b=3
sum = a + b
print("The sum is:", sum)
3. Python program to Input Two Numbers and Multiply
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
product = num1 * num2
print("The product is:", product)
4. Python program to Check if a Number is Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
5. Python program to find the Largest of Three Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
print(a, "is the largest")
elif b >= a and b >= c:
print(b, "is the largest")
else:
print(c, "is the largest")
6. Python Program to Calculate Area of a Circle
radius = float(input("Enter radius: "))
area = 3.14 * radius * radius
print("Area of the circle is:", area)
7. Using a Loop to Print Numbers from 1 to 10
for i in range(1, 11):
print(i)
8. Simple While Loop Example
count = 1
while count <= 5:
print("This is loop number", count)
count += 1
9. Create a Simple List and Print Each Item
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
10.Basic Function to Add Two Numbers
def add_numbers(x, y):
return x + y
result = add_numbers(4, 5)
print("The sum is:", result)
11.Python program to Calculate Simple Interest
# Get user input for principal, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (as a percentage): "))
time = float(input("Enter the time period in years: "))
# Calculate simple interest using the formula: SI = (P * R * T) / 100
simple_interest = (principal * rate * time) / 100
# Print the calculated simple interest
print(f"The simple interest is: {simple_interest:.2f}")
12.Python Program to Calculate the Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("Factorial of 0 is 1.")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("Factorial of", num, "is", factorial)