Python Programming
Variables in Python
In Python there is no need to declare variables you just go ahead and assign values to them
So what would usually be:
DECLARE X : INTEGER
X <- 10
In python is just:
x = 10
Python doesn't care about datatypes but it keeps track of them so X currently is an integer
and treating it like a string will cause errors in your code.
However you can assign to x a new datatype afterwards and python will not throw an error:
x = 10
x = "CS" # works!
Input and Output
In order to show output to the user the print statement is used.
DECLARE X, Y, Z : INTEGER
X <- 10
Y <- 20
Z <- X + Y
OUTPUT "hello there"
OUTPUT X
OUTPUT Y
OUTPUT "x + y =", Z
x = 10
y = 20
z = x + y
print("hello there")
print(x)
print(y)
print("x + y =", z)
note that print(x) and print("x") are different:
print(x) outputs the value stored in the variable x
print("x") outputs the string x to the screen as is.
To get input from the user we can use the input function
so to write:
DECLARE Name : STRING
OUTPUT "Can you tell me your name?"
INPUT Name
OUTPUT "Hello There", Name
in python it can be written as:
name = input("Can you tell me your name?")
print("Hello There", name)
However, in python since there is no declaration statements there is nothing that tells
python that name is a string, as a matter of fact input always returns a string and you are
supposed to turn it into an Integer or Real number if you need to.
DECLARE X : INTEGER
DECLARE Y : REAL
OUTPUT "please enter a number:"
INPUT X
OUTPUT "please enter a decimal number:"
INPUT Y
x = int(input("please enter a number: "))
y = float(input("please enter a decimal number: "))
if statements
in python there are no end statements rather than using end statements indentation is used
to describe where the code block ends and a colon (:) is used to describe that a code block
will start.
IF Age > 18 THEN
OUTPUT "You can legally drive"
ELSE
OUTPUT "You cannot legally drive yet"
END IF
if age > 18:
print("You can legally drive")
else:
print("You cannot legally drive yet")
print("code that will run either way")
Because of the usage of indentation nesting if statements can get very tedious
DECLARE X, Y, Z : INTEGER
INPUT X, Y, Z
IF X > Y AND X > Z THEN
OUTPUT X
ELSE
IF Y > Z THEN
OUTPUT Y
ELSE
OUTPUT Z
END IF
END IF
x = int(input("please enter a number:"))
y = int(input("please enter a number:"))
z = int(input("please enter a number:"))
if x > y and x > z:
print(x)
else:
if y > z:
print(y)
else:
print(z)
rather you can use elif to mean else if and nest if statements in a very logical manner
x = int(input("please enter a number:"))
y = int(input("please enter a number:"))
z = int(input("please enter a number:"))
if x > y and x > z:
print(x)
elif y > z:
print(y)
else:
print(z)
For loops
look at the if statement section to understand how indentation works in python
FOR I <- 0 TO 9
OUTPUT I
ENDFOR
for i in range(10):
print(i)
print("This is outside the while loop due to indentation")
this loop causes i to start at 0 and go up to but not including 10 so the output of the previous
for loop is 0,1,2,3,4,5,6,7,8,9.
You can control what number the loop starts at and the step by which the loop moves
FOR I <- 0 TO 9 STEP 2
OUTPUT I
ENDFOR
for i in range(1,10,2):
print(i)
this causes the loop to start at 1 go up to but not including 10 and increment each number
by 2 so the output is 1,3,5,7,9.
While loops
look at the if statement section to understand how indentation works in python
while loops in python work in exactly the same way as in psuedocode.
DECLARE I : INTEGER
I <- 0
WHILE I < 10 DO
OUTPUT I
I <- I + 1
END WHILE
OUTPUT "This is outside the while loop"
i = 0
while i < 10:
print(i)
i = i + 1
print("This is outside the while loop due to indentation")
There are no repeat until loops in python
Functions & Procedures
in Python there is no specific distinction between functions and procedures, you just use the
def keyword to create either.
Again there is no need to specify the datatypes of the parameters, python just lets you pass
in any datatype to the function or procedure
PROCEDURE MyProcedure(Name : STRING)
DECLARE Out : STRING
Out = "Hello, " & Name
OUTPUT Out
END PROCEDURE
FUNCTION MyFunction(X : INTEGER, Y : INTEGER) : INTEGER
DECLARE Z : INTEGER
Z <- X + Y
RETURN Z
END FUNCTION
def MyProcedure(name):
out = "Hello," + name
print(out)
def MyFunction(x, y):
z = x + y
return z
In python everything is a function, a procedure (function without a return) simply returns
None.
So if you catch the result of calling MyProcedure("Hawary") in a variable called value, this
will not cause an error and value will be set to null.
value = MyProcedure("Hawary")
print(value) # outputs None
Arrays
To create an array you just assign an array to a variable, arrays in python are identified by
square brackets [ ]. To access an element of the array you write very psuedo-code like
syntax.
note that myList[2] returns 5 this is because arrays are zero-indexed in python
myList = [1, 10, 5, 4, 2, 7]
print(myList[2]) # 5
You can add items to an array by using the append function
myList = [1, 10, 5, 4, 2, 7]
[Link](8)
print(myList) # [1, 10, 5, 4, 2, 7]
you can calculate the size of the elements of the array using the len builtin function
myList = [1, 10, 5, 4, 2, 7]
for i in range(len(myList)): # len(myList) => 6
print(myList[i])
you can generate arrays using the append function, for example to generate an array of 20
zeros
myList = []
for i in range(20):
[Link](0)
Since this code is used a lot python has a shorthand for it
myList = [0 for i in range(20)]
2D Arrays
The way to create 2d arrays is by specifying to python the rows and columns in this manner
This creates a 2d array of 20 columns and 10 rows
myList = [[0 for col in range(20)] for row in range(10)]
if you wanted less columns you could have hardcoded them this way
this creates a 2d array of 3 columns and 10 rows
myList = [[0,0,0] for row in range(10)]
To access a specific element use arrayName[row][col] for example:
myList[1][2]
access col index 1 and row index 2 but remember arrays are zero-indexed in python so this
means the second row and the third column
you can now use nested loops to loop over the array
for row in range(len(myList)):
for col in range(len(myList[0])):
print(myList[i][j])
String Manipulation
In Python, strings are a sequence of characters enclosed in either single quotes ( ' ) or
double quotes ( " ). String manipulation is a common task in programming, and Python
provides a wide range of operations to work with strings effectively. Let's explore some of
these operations.
Substrings
A substring is a part of a string. In Python, you can extract substrings using slicing:
Syntax:
string[start:end]
start : The starting index (inclusive).
end : The ending index (exclusive).
Example:
text = "Hello, World!"
substring = text[0:5] # Extracts 'Hello'
print(substring)
You can also use negative indices to count from the end of the string:
substring = text[-6:-1] # Extracts 'World'
print(substring)
If you omit the start or end , it defaults to the beginning or end of the string, respectively:
print(text[:5]) # Outputs 'Hello'
print(text[7:]) # Outputs 'World!'
Changing Case
Python provides methods to convert the case of a string:
.upper()
Converts all characters in the string to uppercase.
DECLARE text : STRING
text <- "hello"
OUTPUT UCASE(text)
text = "hello"
print([Link]()) # Outputs 'HELLO'
.lower()
Converts all characters in the string to lowercase.
DECLARE text : STRING
text <- "HELLO"
OUTPUT LCASE(text)
text = "HELLO"
print([Link]()) # Outputs 'hello'
Length of a String
To find the number of characters in a string, use the len() function:
DECLARE text : STRING
text <- "HELLO"
OUTPUT LENGTH(text)
text = "Hello, World!"
length = len(text)
print(length) # Outputs 13
Accessing Characters
Strings in Python are zero-indexed, meaning the first character has an index of 0. You can
access individual characters using their index:
Example:
text = "Python"
print(text[0]) # Outputs 'P'
print(text[5]) # Outputs 'n'
You can also use negative indices to access characters from the end:
print(text[-1]) # Outputs 'n'
print(text[-2]) # Outputs 'o'
Additional Modules in Python
The Import Statement
The import statement in Python is used to include and access external libraries or
specific routines (functions, classes, or variables) within your Python program.
A library in Python is a collection of pre-written code that provides additional functionality,
and a routine is a specific operation or task defined in the library, such as a function or a
class.
You can import libraries in python in one of two main ways:
1. Import the entire library
import math
print([Link](16))
1. Import some routines from a library
from math import sqrt, sin
print(sqrt(16)) # Outputs: 4.0
print(sin(3.14)) # Outputs: ~0.0
Random Numbers
Python's random module allows you to generate random numbers for various use cases.
[Link](a, b)
Generates a random integer between a and b (inclusive):
import random
random_number = [Link](1, 10)
print(random_number) # Random number between 1 and 10
Example:
import random
for _ in range(5):
print("Rolling a dice:", [Link](1, 6))
[Link]()
Generates a random floating-point number between 0.0 and 1.0 :
DECLARE random_float : REAL
random_float <- RANDOM()
OUTPUT random_float
import random
random_float = [Link]()
print(random_float) # Random number between 0.0 and 1.0
Example:
import random
random_percentage = [Link]() * 100
print("Random percentage:", random_percentage)
Working with Dates
Python's datetime module provides tools for working with dates and times.
Getting the Current Date
To get the current date, use [Link]() :
from datetime import date
current_date = [Link]()
print("Today's date:", current_date)
Creating a Date Object
You can create a date object using date(year, month, day) :
from datetime import date
specific_date = date(2023, 1, 1)
print("Specific date:", specific_date)
Accessing Date Components
You can extract individual components from a date object:
from datetime import date
current_date = [Link]()
print("Year:", current_date.year)
print("Month:", current_date.month)
print("Day:", current_date.day)
Example:
from datetime import date
birthday = date(2000, 5, 15)
today = [Link]()
age = [Link] - [Link]
if ([Link], [Link]) < ([Link], [Link]):
age -= 1
print(f"You are {age} years old.")