Skip to main content

Programming Fundamentals

Subject: Computer Science
Topic: 5
Cambridge Code: 0478


Programming Basics

Program - Set of instructions for computer

Programming Languages

Levels:

  • High-level: Python, Java, JavaScript (human-friendly)
  • Low-level: Assembly (machine-oriented)

Types:

  • Imperative: Step-by-step instructions (Python, Java)
  • Declarative: Describe what to do (SQL)
  • Object-oriented: Objects and classes (Java, C++)
  • Functional: Functions and immutability (Haskell, Scheme)

Variables and Data Types

Variables

Variable - Named storage location

Naming conventions:

  • Start with letter or underscore
  • Alphanumeric + underscore
  • Case-sensitive
  • Meaningful names

Declaration: Reserve memory and assign type

name = "Alice"
age = 25
score = 95.5

Data Types

Integer:

  • Whole numbers: -100, 0, 25, 1000
  • Operations: +, -, *, //, %

Float (Real):

  • Decimal numbers: 3.14, -0.5, 99.99
  • Operations: +, -, *, /

String:

  • Text: "Hello", "2024"
  • Operations: Concatenation, slicing, length

Boolean:

  • True or False
  • Logical operations: AND, OR, NOT

Operators

Arithmetic Operators

OperatorNameExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division15 / 3 = 5
//Integer division15 // 4 = 3
%Modulo (remainder)15 % 4 = 3
**Exponentiation2 ** 3 = 8

Comparison Operators

OperatorMeaningExample
==Equal5 == 5 → True
!=Not equal5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater or equal5 >= 5 → True
<=Less or equal3 <= 5 → True

Logical Operators

OperatorMeaningExample
ANDBoth trueTrue AND False → False
ORAt least one trueTrue OR False → True
NOTInvertsNOT True → False

Assignment Operators

x = 5        # Assignment
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 2 # x = x * 2

Control Flow

If-Else Statements

Conditional execution based on conditions

if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")

Loops

For Loop - Fixed iterations

for i in range(1, 6):  # 1 to 5
print(i)

While Loop - Conditional iterations

count = 0
while count < 5:
print(count)
count += 1

Loop Control:

  • break: Exit loop
  • continue: Skip to next iteration

Functions

Function - Reusable block of code

Definition and Calling

def greet(name):
return f"Hello, {name}!"

message = greet("Alice") # Calling
print(message) # Hello, Alice!

Parameters and Arguments

Parameters: Variables in function definition Arguments: Values passed when calling

def add(a, b):           # Parameters
return a + b

result = add(5, 3) # Arguments

Return Values

def circle_area(radius):
import math
area = math.pi * radius ** 2
return area # Returns value

Scope

Local scope: Variables defined inside function Global scope: Variables defined outside functions

x = 10  # Global

def func():
y = 5 # Local
print(x) # Can access global
print(y)

# print(y) # ERROR: y not accessible

Data Structures

Lists (Arrays)

Ordered collection of elements

numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]

numbers[0] # 1 (access)
numbers[1:3] # [2, 3] (slicing)
numbers.append(6) # Add element

Dictionaries

Key-value pairs

person = {
"name": "Alice",
"age": 25,
"city": "NYC"
}

person["name"] # "Alice"
person["age"] = 26 # Update

Tuples

Immutable list

coordinates = (10, 20)
color = (255, 128, 0) # RGB

coordinates[0] # 10
# coordinates[0] = 15 # ERROR: Cannot modify

String Operations

String Methods

text = "Hello World"

text.lower() # "hello world"
text.upper() # "HELLO WORLD"
text.replace("World", "Alice") # "Hello Alice"
text.split() # ["Hello", "World"]
len(text) # 11

String Formatting

name = "Alice"
age = 25

# Concatenation
message = "Name: " + name + ", Age: " + str(age)

# Format string (modern Python)
message = f"Name: {name}, Age: {age}"

Input and Output

Input

name = input("What's your name? ")
age = int(input("How old are you? "))

Output

print("Hello, world!")
print(f"Name: {name}, Age: {age}")

Comments and Documentation

Comments

# Single-line comment

"""
Multi-line comment
or docstring
"""

Docstrings

def add(a, b):
"""Add two numbers and return sum."""
return a + b

Key Points

  1. Variables store data of specific types
  2. Data types: Integer, Float, String, Boolean
  3. Operators: Arithmetic, Comparison, Logical
  4. Control flow: if-else, for, while
  5. Functions encapsulate reusable code
  6. Lists/arrays: Ordered collections
  7. Dictionaries: Key-value storage
  8. Strings: Text with manipulation methods

Practice Questions

  1. Write variable declarations
  2. Write arithmetic expressions
  3. Create if-else statements
  4. Write for and while loops
  5. Define and call functions
  6. Use lists and dictionaries
  7. Manipulate strings

Revision Tips

  • Practice variable naming
  • Know operator precedence
  • Understand control flow
  • Practice function writing
  • Know data structure uses
  • Test code frequently
  • Use meaningful names