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

Pseudo code to Python Translation Guide

The document provides a comprehensive guide for translating pseudocode into Python, covering basic syntax, control structures, data types, and common algorithm patterns. It includes examples of output, input, assignment, selection statements, loops, functions, and data structures like lists and dictionaries. Additionally, it highlights essential programming constructs and common algorithms such as input validation, searching, and sorting.

Uploaded by

Liane Regnard
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 views13 pages

Pseudo code to Python Translation Guide

The document provides a comprehensive guide for translating pseudocode into Python, covering basic syntax, control structures, data types, and common algorithm patterns. It includes examples of output, input, assignment, selection statements, loops, functions, and data structures like lists and dictionaries. Additionally, it highlights essential programming constructs and common algorithms such as input validation, searching, and sorting.

Uploaded by

Liane Regnard
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
You are on page 1/ 13

Pseudocode to Python Translation Guide

Basic Syntax Comparison

Concept Pseudocode Python

Output OUTPUT "Hello" print("Hello")

Input INPUT name name = input()

Assignment total ← 0 total = 0

Comments // This is a comment # This is a comment

Selection (If Statements)

Pseudocode:

IF age >= 18 THEN


OUTPUT "You can vote"
ELSE
OUTPUT "Too young to vote"
ENDIF

Python:

if age >= 18:


print("You can vote")
else:
print("Too young to vote")
Multiple Conditions

Pseudocode:

IF score >= 90 THEN


OUTPUT "Grade A"
ELSE IF score >= 70 THEN
OUTPUT "Grade B"
ELSE IF score >= 50 THEN
OUTPUT "Grade C"
ELSE
OUTPUT "Fail"
ENDIF

Python:

if score >= 90:


print("Grade A")
elif score >= 70:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Fail")
Iteration - For Loops

Pseudocode:

FOR i ← 1 TO 5
OUTPUT i
NEXT i

Python:

for i in range(1, 6): # Note: range(1, 6) gives 1, 2, 3, 4, 5


print(i)
Iteration - While Loops

Pseudocode:

counter ← 1
WHILE counter <= 5 DO
OUTPUT counter
counter ← counter + 1
ENDWHILE

Python:

counter = 1
while counter <= 5:
print(counter)
counter = counter + 1 # or counter += 1

Iteration - Repeat Until

Pseudocode:

counter ← 1
REPEAT
OUTPUT counter
counter ← counter + 1
UNTIL counter > 5

Python:

counter = 1
while True:
print(counter)
counter = counter + 1
if counter > 5:
break

OR

counter = 1
while not (counter > 5):
print(counter)
counter = counter + 1
Arrays/Lists

Pseudocode:

DECLARE numbers : ARRAY[1:5] OF INTEGER


numbers[1] ← 10
numbers[2] ← 20
OUTPUT numbers[1]

Python:

numbers = [0] * 5 # Creates [0, 0, 0, 0, 0]


# Python uses 0-based indexing!
numbers[0] = 10 # First element
numbers[1] = 20 # Second element
print(numbers[0])
Functions/Procedures

Pseudocode (Procedure):

PROCEDURE greet(name)
OUTPUT "Hello, " + name
ENDPROCEDURE

greet("Alex")

Python:

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

greet("Alex")

Pseudocode (Function):

FUNCTION square(number)
RETURN number * number
ENDFUNCTION

result ← square(4)
OUTPUT result

Python:

def square(number):
return number * number

result = square(4)
print(result)
Essential Programming Constructs
1. Variables and Constants

Python:

# Variables
name = "Alex" # String
age = 16 # Integer
height = 1.75 # Float
is_student = True # Boolean

# Constants (by convention, use uppercase)


PI = 3.14159
MAX_STUDENTS = 30

Key points:

• Python automatically determines data types


• Variable names should be descriptive
• Cannot use reserved words (if, for, while, etc.)

2. String Operations

Python:

name = "Computer Science"

# Length
length = len(name) # 16

# Accessing characters (zero-indexed)


first_char = name[0] # 'C'

# Slicing
substr = name[0:8] # 'Computer'

# Concatenation
greeting = "Hello, " + name # 'Hello, Computer Science'

# String methods
lowercase = name.lower() # 'computer science'
uppercase = name.upper() # 'COMPUTER SCIENCE'
3. Mathematical Operations

Python:

a = 10
b = 3

addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333... (float)
integer_division = a // b # 3 (integer)
remainder = a % b # 1
power = a ** b # 1000 (10^3)

4. Logical Operators

Python:

x = 5
y = 10

# Comparison operators
is_equal = x == y # False
not_equal = x != y # True
greater_than = x > y # False
less_than = x < y # True
greater_equal = x >= y # False
less_equal = x <= y # True

# Logical operators
and_result = (x > 0) and (y > 0) # True
or_result = (x > 10) or (y > 0) # True
not_result = not (x > 0) # False
Common Algorithm Patterns
1. Input Validation

Python:

# Validate numeric input


valid_input = False
while not valid_input:
user_input = input("Enter a number between 1-10: ")
if user_input.isdigit():
number = int(user_input)
if 1 <= number <= 10:
valid_input = True
else:
print("Number must be between 1 and 10")
else:
print("You must enter a number")

2. Finding Maximum Value

Python:

numbers = [45, 22, 67, 34, 18]


max_value = numbers[0] # Assume first is largest

for num in numbers:


if num > max_value:
max_value = num

print(max_value) # 67

3. Counting Occurrences

Python:

text = "hello world"


target = "l"
count = 0

for char in text:


if char == target:
count += 1

print(count) # 3
4. Linear Search

Python:

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i # Return position if found
return -1 # Return -1 if not found

numbers = [5, 8, 12, 16, 23]


position = linear_search(numbers, 12)
print(position) # 2

5. Binary Search (for sorted lists)

Python:

def binary_search(arr, target):


low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1 # Not found

sorted_numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]


position = binary_search(sorted_numbers, 23)
print(position) # 5
6. Bubble Sort

Python:

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
# Swap elements
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

numbers = [64, 34, 25, 12, 22, 11, 90]


sorted_numbers = bubble_sort(numbers)
print(sorted_numbers) # [11, 12, 22, 25, 34, 64, 90]

7. Total and Average

Python:

numbers = [10, 20, 30, 40, 50]


total = 0

for num in numbers:


total += num

average = total / len(numbers)


print(f"Total: {total}, Average: {average}") # Total: 150, Average: 30.0
Data Structures
1. Lists (Arrays)

Python:

# Creating lists
empty_list = []
numbers = [10, 20, 30, 40, 50]
mixed = [1, "hello", True, 3.14]

# Accessing elements (zero-indexed)


first = numbers[0] # 10
last = numbers[-1] # 50

# Modifying elements
numbers[1] = 25 # [10, 25, 30, 40, 50]

# List operations
length = len(numbers) # 5
numbers.append(60) # Add to end: [10, 25, 30, 40, 50, 60]
numbers.insert(1, 15) # Insert at position: [10, 15, 25, 30, 40, 50, 60]
numbers.remove(30) # Remove by value: [10, 15, 25, 40, 50, 60]
popped = numbers.pop() # Remove & return last: 60, list becomes [10, 15, 25,
40, 50]
numbers.sort() # Sort in place: [10, 15, 25, 40, 50]

2. Two-dimensional Lists (2D Arrays)

Python:

# Creating a 2D list (3x3 grid)


grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Accessing elements (row, column)


element = grid[1][2] # row 1, column 2: value 6

# Iterating through a 2D list


for row in grid:
for item in row:
print(item, end=" ")
print() # New line after each row
3. Dictionaries (Key-Value Pairs)

Python:

# Creating a dictionary
student = {
"name": "Alex",
"age": 16,
"grades": [85, 90, 78]
}

# Accessing values
name = student["name"] # "Alex"
# Alternative safer method
age = student.get("age", 0) # 16 (returns 0 if key doesn't exist)

# Adding/modifying entries
student["school"] = "High School"
student["age"] = 17

# Checking if key exists


has_email = "email" in student # False

# Iterating through a dictionary


for key in student:
print(f"{key}: {student[key]}")

# Get all keys or values


keys = student.keys()
values = student.values()

You might also like