0% found this document useful (0 votes)
4 views7 pages

1183 - File - Programming Basics

The document outlines the three main programming constructs: sequence, selection, and iteration, each with definitions, purposes, and Python examples. It also discusses types of programming errors, including syntax errors, logic errors, and runtime errors, providing definitions and examples for each. Additionally, it covers the importance of constants in programming, advantages of using them, and techniques for writing readable and maintainable code.

Uploaded by

hassansalako32
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)
4 views7 pages

1183 - File - Programming Basics

The document outlines the three main programming constructs: sequence, selection, and iteration, each with definitions, purposes, and Python examples. It also discusses types of programming errors, including syntax errors, logic errors, and runtime errors, providing definitions and examples for each. Additionally, it covers the importance of constants in programming, advantages of using them, and techniques for writing readable and maintainable code.

Uploaded by

hassansalako32
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

# Programming Constructs: The three main programming constructs are:

- Sequence
- Selection
- Iteration
Programming constructs are fundamental building blocks used to control the flow of
execution in a program. They allow developers to create structured and efficient code.
The three main constructs are sequence, selection, and iteration. Below, each is
explained with examples in Python.

## 1. Sequence
- **Definition**: Sequence refers to the straightforward execution of code statements
one after another, in the order they appear. It's the default flow in most programs unless
altered by other constructs.
- **Purpose**: Ensures instructions are followed logically from top to bottom.
- **Example**:
```python
# Simple sequence example: Calculating area of a rectangle
length = 5 // Step 1: Assign length
width = 3 // Step 2: Assign width
area = length * width // Step 3: Calculate area
print("The area is:", area) // Step 4: Output result
- Output: `The area is: 15`
- Explanation: Each line executes sequentially without any conditions or loops.

## 2. Selection
- **Definition**: Selection (also known as conditional statements) allows the program to
make decisions based on certain conditions. It executes different blocks of code
depending on whether a condition is true or false.
- Purpose: Handles branching logic, like choosing between options.
- **Common Statements**: `if`, `if-else`, `if-elif-else`, CASE OF.
- **Example**:
Python
# Selection example: Check if a number is positive or negative
number = -7
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
```
- Output (for `number = -7`): `The number is negative.`
- Explanation: The program evaluates the condition and selects the appropriate branch.

## 3. Iteration
- **Definition**: Iteration (or looping) allows a block of code to be repeated multiple
times until a condition is met. It’s useful for performing repetitive tasks.
- **Purpose**: Automates repetition, reducing code duplication.
- **Common Statements**: `For loop (for a known number of iterations), `while` loop
(for unknown iterations based on a condition).
- **Example** (Using `for` loop):
Python
# Iteration example: Print numbers from 1 to 5
for count in range(1, 6):
print(count)
- Output:
1
2
3
4
5
```
- Explanation: The loop repeats 5 times, printing each number in sequence.

- **Another Example** (Using `while` loop):


Python
# While loop: Sum numbers until user enters 0
total = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total += num
num = int(input("Enter a number (0 to stop): "))
print("Total sum:", total)
```
- Explanation: The loop continues as long as `num` is not 0, adding inputs to the total.

# Types of Programming Errors:


- Syntax error
- Logic error
- Runtime Error
Errors (or bugs) in programming are issues that prevent a program from running correctly
or at all. They are classified into three main types: **syntax errors**, **logic errors**, and
**runtime errors**. Understanding them helps in debugging.

## 1. Syntax Errors
- **Definition**: These occur when the code violates the rules of the programming
language's grammar or structure. The code cannot be compiled or interpreted.
- **Characteristics**: Detected by the compiler/interpreter before execution; easy to
spot as they prevent the program from running.
- **Example** (in Python):
```python
print("Hello World" # Missing closing parenthesis
```
- Error Message: `SyntaxError: unexpected EOF while parsing`
- Explanation: The missing `)` breaks the syntax rules, so the program doesn't run.

## 2. Logic Errors
- **Definition**: Logic error is an error that makes the program to produce an incorrect
result i.e. the output is wrong. This happens when the code runs without crashing but
produces incorrect results or output due to flawed reasoning or algorithm.
- **Characteristics**: Hardest to detect; the program executes fully, but output is wrong.
Requires testing and debugging.
- **Example** (in Python):
# Intended: Calculate average of two numbers
num1 = 10
num2 = 20
average = num1 + num2 / 2 #Logic flaw: Division happens first due to operator
precedence
print("Average:", average)
- Output: `Average: 20.0` (Incorrect; should be 15)
- Corrected statement: `average = (num1 + num2) / 2
- Explanation: The logic ignores operator precedence, leading to wrong computation.

## 3. Runtime Error
- **Definition**: This occurs during program execution when the code encounters an
invalid or illegal operation, like dividing by zero or accessing invalid memory.
- **Characteristics**: Code compiles/runs initially but crashes midway; often due to
unexpected inputs or conditions.
- **Example** (in Python):
# Runtime error: Division by zero
a = 10
b=0
result = a / b
print(result)
```
- Error Message: `ZeroDivisionError: division by zero`
- Explanation: The code is syntactically correct, but at runtime, dividing by zero is
impossible, causing a crash.

# Constants in Programming and Advantages of Using Constants


## Constants in Programming
- **Definition**: Constants are variables whose values cannot be changed after they are
initialized. They represent fixed values used throughout the program, like mathematical
constants (e.g., π).
- **How to Declare**: In languages like Python, constants are conventionally named in
UPPERCASE (e.g., `PI = 3.14159`), though Python doesn't enforce immutability. In other
languages like C++ or Java, keywords like `const` or `final` are used.
- **Example** (in Python):
# Constants for a circle area calculator
PI = 3.14159 # Constant for pi
radius = 5 # Variable
area = PI * radius ** 2
print("Area:", area)
```
- Explanation: `PI` is treated as a constant and not reassigned.

## Advantages of Using Constants in a program


- **Readability and Maintainability**: Constants make code easier to understand by giving
meaningful names to fixed values (e.g., `TAX_RATE = 0.15` instead of hardcoding 0.15
everywhere).
- If the value needs updating, you can change it in one place only.
- **Error Prevention**: It prevents accidental modification of values that should remain
fixed, reducing bugs.
- **Reusability**: Promotes code reuse by centralizing fixed values, making the program
more modular.

How to make a computer program easy to read and understand?


Making a computer program easy to read and understand is a key skill in programming. A
clean, readable program is easier to debug, maintain, and **share** with others. Here
are practical, proven techniques used by professional developers to make a computer
program easy to read and understand:
1. Use Meaningful Names
Choose clear, descriptive names for variables, functions, and classes.

Bad Good

x, a, temp total_price, user_age, calculate_tax()

data student_records, monthly_sales


2. Follow Consistent Naming Conventions

Language Convention

Python snake_case for variables/functions → calculate_average()

JavaScript camelCase → calculateAverage()

Constants UPPER_SNAKE_CASE → MAX_LOGIN_ATTEMPTS = 3

3. Add Comments (But Not Too Many)


Explain why, not what the code does. Use # for comments in Python
# Calculate total with 15% tax
total = price * 1.15 # Good: explains intent

4. Use Proper Indentation and Spacing


Makes your code visually structured.
# Good
if user_age >= 18:
print("Adult")
grant_access()
else:
print("Minor")
show_warning()

Use 4 spaces (not tabs) in Python. Add blank lines between logical sections.

5. Keep Functions Short and Focused


def calculate_area(length, width):
return length * width

def print_result(area):
print(f"Area: {area}")
# Main logic
area = calculate_area(5, 3)
print_result(area)

6. Use Constants
Replace unclear numbers with named constants.
TAX_RATE = 0.15
DISCOUNT_THRESHOLD = 1000

if total > DISCOUNT_THRESHOLD:


total *= (1 - TAX_RATE)

7. Use Whitespace to Group Related Code


Add blank lines to separate logical blocks.
# Input
name = input("Enter name: ")
age = int(input("Enter age: "))

# Processing
is_adult = age >= 18

# Output
if is_adult:
print(f"{name} is an adult.")
else:
print(f"{name} is a minor.")

Final Tip:
Readable code = fewer bugs + faster learning + happier teammates (and future you!)

You might also like