0% found this document useful (0 votes)
3 views18 pages

Programming Principles Guide

This document is a comprehensive beginner's guide to programming principles in Python, covering essential topics such as variables, data types, operators, conditionals, loops, and functions. It includes explanations, examples, and common mistakes to help beginners understand the foundational concepts of Python programming. The guide also provides a quick reference for syntax and common pitfalls to avoid.

Uploaded by

Polycarp Gekonge
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)
3 views18 pages

Programming Principles Guide

This document is a comprehensive beginner's guide to programming principles in Python, covering essential topics such as variables, data types, operators, conditionals, loops, and functions. It includes explanations, examples, and common mistakes to help beginners understand the foundational concepts of Python programming. The guide also provides a quick reference for syntax and common pitfalls to avoid.

Uploaded by

Polycarp Gekonge
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

Elementary

Programming
Principles
A comprehensive beginner's revision guide — Python edition

01 Variables

02 Data Types

03 Operators

04 Conditionals

05 Loops

06 Functions
Elementary Programming Principles Page 2

Contents
Variables
01
What they are, naming rules, assignment

Data Types
02
int, float, str, bool — and type conversion

Operators
03
Arithmetic, comparison, and logical operators

Conditionals
04
if, elif, else — making decisions in code

Loops
05
for and while — automating repetition

Functions
06
Defining, calling, parameters, return values, scope

Common Mistakes
07
Pitfalls every beginner hits — and how to avoid them

Quick Reference
08
Cheat sheet — all syntax at a glance

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 3

Variables
1 Named containers that hold your program's data

What is a Variable?
A variable is a named storage location in your computer's memory. You give it a name, assign it a
value, and then use that name anywhere in your program to read or update the value. Think of it as a
labelled box — the label is the variable name, and whatever you put inside is the value.

ANALOGY

Imagine a row of jars in a kitchen. Each jar has a label — 'sugar', 'salt', 'coffee'. You can look
inside any jar by reading its label, and you can replace the contents whenever you like. Variables
work exactly like this.

Variables — named containers that hold data

▼ stored value ▼ stored value ▼ stored value

"Alice" 17 98.5

name age score


(variable name) (variable name) (variable name)
Variables as labelled jars — the label is the name, the contents are the value.

Creating and Assigning Variables


In Python, you create a variable simply by writing its name, followed by = and the value. There is no
separate 'declare' step — assignment creates the variable on the spot.

# Creating variables
name = "Alice" # str — text
age = 17 # int — whole number
score = 98.5 # float — decimal
passed= True # bool — True/False

# Reading a variable
print(name) # Alice

# Updating a variable
age = age + 1 # now age is 18

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 4

Naming Rules
✓ Start with a letter or underscore

✓ Use only letters, digits, and underscores

✓ Use snake_case: first_name, total_score

✗ No spaces: first name is INVALID

✗ No starting with a digit: 1name is INVALID

✗ No reserved words: if, for, while, def, etc.

IMPORTANT — = IS NOT EQUALS!

In Python, the = sign means ASSIGNMENT (store this value). It is NOT the mathematical equals
sign. Writing x = x + 1 is perfectly valid — it means: take the current value of x, add 1, then store
the result back in x. To CHECK equality, use == (double equals).

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 5

Data Types
2 The kind of value a variable holds

Why Do Types Matter?


Every value in Python has a type that tells the computer what kind of data it is and what you can do
with it. You cannot add a number to a word without converting one of them — just like you cannot
pour water into a paper bag. Types protect you from accidental bugs.

int float str bool

42 3.14 "hello" True

Whole numbers Decimals Text True / False

The four core primitive data types in Python


The four primitive types — each tile shows the type name, an example value, and what it represents.

The Four Core Types in Depth


int — Integers
Whole numbers, positive or negative, with no decimal point. Used for counting, indexing (picking an
item from a list), and loop counters. Range is effectively unlimited in Python.

x = 42 y = -7 z = 0

float — Floating Point


Numbers with a decimal point. Used for measurements, percentages, averages, and any calculation
that might produce a fraction. Note: floats can have tiny rounding errors due to how computers store
decimals.

pi = 3.14159 temp = -0.5

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 6

str — String
Any sequence of characters enclosed in single or double quotes. Can hold letters, numbers, symbols,
even emojis. The number 42 as a string is '42' — you cannot do maths with it until you convert it.

name = "Alice" city = 'Nairobi'

bool — Boolean
The simplest type — only two possible values: True or False. The result of every comparison or
logical expression is a bool. Used to control if-statements and while-loops.

is_raining = False passed = True

Type Conversion (Casting)


You can convert between types using built-in functions. This is called casting. Always convert before
mixing types in operations.

# str -> int


age = int("17") # now you can do maths

# int -> str


msg = "Your score: " + str(98) # "Your score: 98"

# Check a type
type(42) # <class 'int'>
isinstance("hi", str) # True

WATCH OUT

Trying to cast a non-numeric string to int crashes the program: int('hello') raises a ValueError.
Always be sure the string actually contains a number before casting.

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 7

Operators
3 Performing actions on values

Operators are special symbols that perform operations on one or more values (called operands).
Python has three main families of operators, each producing different kinds of results.

Arithmetic Comparison Logical

+ − * / == != > < and or

% ** // >= <= not

Three operator families — each returns a different kind of result


Three operator families — arithmetic produces numbers; comparison and logical produce True/False.

Arithmetic Operators
Operator Name Example Result

+ Addition 7+3 10

- Subtraction 7-3 4

* Multiplication 7*3 21

/ Division 7/3 2.333...

// Floor division 7 // 3 2 (rounds down)

% Modulus 7%3 1 (remainder)

** Exponent 2 ** 8 256

Comparison Operators
Comparison operators compare two values and always return a bool (True or False). They are the
backbone of if-statements and while-loops.

Operator Meaning Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 8

> Greater than 7>3 True

< Less than 2<1 False

>= Greater or equal 5 >= 5 True

<= Less or equal 3 <= 2 False

Logical Operators
Logical operators combine or modify boolean values. They let you check multiple conditions at once.

age = 17 score = 85

# and — BOTH conditions must be True


age >= 16 and score >= 80 # True

# or — AT LEAST ONE must be True


age < 10 or score >= 80 # True

# not — FLIPS the result


not (age > 18) # True

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 9

Conditionals
4 Making decisions — running different code based on conditions

What are Conditionals?


A conditional statement lets your program choose between different paths of execution. Without
conditionals, every program would do the same thing every time — completely useless in practice.

ANALOGY

Think of a traffic light. The light checks a condition (how long has it been red?) and decides what
to do (stay red, or switch to green). Your program does the same — it checks a condition and
takes the appropriate action.

score = ?

Yes
score >= 80? "Distinction"

No

Yes
score >= 50? "Pass"

No

"Fail — try again"

The if / elif / else decision tree

The if / elif / else decision tree — only one branch executes per run.

Syntax and Structure

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 10

score = 72

if score >= 80: # condition 1


print("Distinction — well done!")
elif score >= 50: # condition 2
print("Pass")
elif score >= 40: # condition 3
print("Borderline — review needed")
else: # catch-all
print("Fail — please resit")

# Output for score = 72:


# Pass

Nested Conditionals
You can put an if-statement inside another if-statement. This is called nesting. Each level of nesting
requires another 4-space indent.

if age >= 18:


if has_id == True:
print("Welcome!")
else:
print("Show your ID please")
else:
print("Too young to enter")

INDENTATION IS NOT OPTIONAL

Python uses indentation (4 spaces per level) to define which code belongs inside a block. An
incorrect indent changes the logic of your program — or raises an IndentationError that stops it
running entirely. Always use 4 spaces (not a tab character).

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 11

Loops
5 Repeating code automatically — without copy-paste

Why Use Loops?


Loops let you execute a block of code multiple times without rewriting it. Instead of writing print(1),
print(2), print(3)... a hundred times, you write it once inside a loop. This is one of the most powerful
tools in programming.

for loop — known count while loop — unknown count

for i in range(5): count = 0

print(i) while count < 3:

# 0 1 2 3 4 count += 1

0 1 2 3 4 ?
Runs exactly 5 times Repeats until condition is False

for vs while — choose based on whether you know the iteration count in advance.

The for Loop — iterating a known number of times

# range(start, stop, step)


for i in range(0, 10, 2): # 0,2,4,6,8
print(i)

# Iterating over a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like " + fruit)

# range(5) is shorthand for range(0, 5, 1)


for i in range(5): # 0, 1, 2, 3, 4
print(i)

The while Loop — repeating until a condition changes

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 12

count = 1
while count <= 5:
print("Count:", count)
count += 1 # MUST change count or loop runs forever!

# Waiting for valid input


answer = ""
while answer != "yes" and answer != "no":
answer = input("Enter yes or no: ")

Loop Control: break and continue

# break — exit the loop immediately


for i in range(10):
if i == 5:
break # stops at 5
print(i) # prints 0 1 2 3 4

# continue — skip the rest of this iteration


for i in range(6):
if i == 3:
continue # skips 3
print(i) # prints 0 1 2 4 5

INFINITE LOOP DANGER

A while loop without something that eventually makes its condition False will run forever —
crashing or freezing your program. Always double-check that something inside the loop brings
you closer to the condition being False. If in doubt, add a safety counter: safety += 1 and break if
safety > 1000.

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 13

Functions
6 Reusable named blocks — write once, call anywhere

What is a Function?
A function is a named, reusable block of code that performs a specific task. Instead of repeating the
same ten lines of code in five places, you write them once inside a function and call the function's
name wherever you need it. Functions also let you pass in different inputs (arguments) so the same
logic can work on different data.

ANALOGY

A function is like a recipe in a cookbook. You write the recipe once. Whenever you want to make
that dish, you open the book to that page (call the function). You can even make variations by
changing the ingredients (passing different arguments).

def keyword function name parameter

def greet(name):
message = "Hello, " + name
return message

result = greet("Alice")
print(result) # Hello, Alice!

return sends result back argument — actual value

Anatomy of a Python function

Annotated anatomy of a Python function — each part explained.

Parameters vs Arguments
These two words are often confused. A parameter is the placeholder variable in the function
definition. An argument is the actual value you pass when calling the function.

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 14

def add(a, b): # a and b are PARAMETERS


return a + b

result = add(10, 5) # 10 and 5 are ARGUMENTS


print(result) # 15

# Default parameter values


def greet(name, greeting="Hello"):
print(greeting + ", " + name)

greet("Alice") # Hello, Alice


greet("Bob", "Hi") # Hi, Bob

Return Values
The return keyword sends a value back to the caller. A function without a return statement returns
the special value None. You can return any type — number, string, bool, or even a list.

def is_even(n):
return n % 2 == 0 # returns True or False

print(is_even(4)) # True
print(is_even(7)) # False

Variable Scope
Scope determines where a variable is visible. Variables created inside a function are local — they
only exist while the function runs. Variables outside all functions are global — visible everywhere.

Global Scope

x = 10
Local Scope (inside function)

def my_func():
y = 20 # local only
print(x) # can see x!
print(y) # works here
print(y) # ERROR — y not here!

Global vs local scope — inner functions can read global variables, but not vice versa.

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 15

Common Mistakes
7 Pitfalls every beginner hits — and how to avoid them

Using = instead of == in conditions


= assigns; == compares. Using = inside an if causes a SyntaxError in Python.

Wrong Correct

if x = 5: if x == 5: # == checks equality

Off-by-one errors in range()


range(start, stop) stops BEFORE stop. To include 10, write range(1, 11).

Wrong Correct

for i in range(1, 10): # only goes to


9 for i in range(1, 11): # goes to 10

Forgetting to update a while counter


Without count += 1, the condition never becomes False — infinite loop.

Wrong Correct

while count < 5:


while count < 5: print(count)
print(count) # infinite! count += 1

Mixing types without converting


You cannot concatenate a string and an int directly. Convert with str().

Wrong Correct

name = "Alice"
age = 17
print("Name: " + name + age) # ERROR print("Name: " + name + str(age)) # OK

Indentation errors
Everything inside a block must be indented by exactly 4 spaces.

Wrong Correct

if x > 0: if x > 0:
print('positive') # IndentationError print('positive') # 4 spaces

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 16

Calling a function before defining it


Python reads top-to-bottom. Define functions before calling them.

Wrong Correct

result = add(3, 4) # NameError def add(a, b):


def add(a, b): return a + b
return a + b result = add(3, 4) # OK

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 17

Quick Reference
8 All essential syntax at a glance

Variables & Types

Create a variable name = 'Alice'

Integer x = 42

Float pi = 3.14

String msg = 'hello'

Boolean done = True

Check type type(x)

Convert to int int('42')

Convert to str str(99)

Operators

Add / subtract a + b a - b

Multiply / divide a * b a / b

Floor div / modulus a // b a % b

Power a ** b

Equal / not equal a == b a != b

Greater / less a > b a < b

Logical AND / OR / NOT and or not

Conditionals

if statement if condition:

elif (else if) elif condition:

else (catch-all) else:

Ternary (one-liner) x if cond else y

Loops

for with range for i in range(n):

for over list for item in my_list:

while loop while condition:

A Beginner's Comprehensive Revision Guide • Python Edition


Elementary Programming Principles Page 18

break (exit loop) break

continue (skip iter.) continue

Increment shorthand x += 1

Functions

Define function def my_func(param):

Return a value return value

Call a function result = my_func(arg)

Default parameter def f(x, y=10):

No return = None print(my_func()) # None

KEEP PRACTISING!

The best way to learn programming is to write code every day — even just 15 minutes. Try
modifying the examples in this guide. Break them on purpose, then fix them. Every error message
teaches you something. You've got this!

A Beginner's Comprehensive Revision Guide • Python Edition

You might also like