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
| Operator | Name | Example |
|---|---|---|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 5 - 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| / | Division | 15 / 3 = 5 |
| // | Integer division | 15 // 4 = 3 |
| % | Modulo (remainder) | 15 % 4 = 3 |
| ** | Exponentiation | 2 ** 3 = 8 |
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal | 5 == 5 → True |
!= | Not equal | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater or equal | 5 >= 5 → True |
<= | Less or equal | 3 <= 5 → True |
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
| AND | Both true | True AND False → False |
| OR | At least one true | True OR False → True |
| NOT | Inverts | NOT 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
- Variables store data of specific types
- Data types: Integer, Float, String, Boolean
- Operators: Arithmetic, Comparison, Logical
- Control flow: if-else, for, while
- Functions encapsulate reusable code
- Lists/arrays: Ordered collections
- Dictionaries: Key-value storage
- Strings: Text with manipulation methods
Practice Questions
- Write variable declarations
- Write arithmetic expressions
- Create if-else statements
- Write for and while loops
- Define and call functions
- Use lists and dictionaries
- 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