FIT9136 Catchup Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

FIT9136 Cheat Sheet

The Basics Basic Programming Concepts


Function Purpose Programming Concept Definition
Print Display formatted messages onto the screen. A variable stores a value in memory. This value can be either a string, an
Variable integer, a float, etc. The name assigned to that value via the “=” can be
The spaces at the beginning of the code line accessed later with that name.
Indentation
which indicate a block of code.
Variables have a variety of types. The most common ones are integers,
Syntax free representation of code to represent Value Types
Pseudocode floats, strings, Booleans, and lists.
algorithmic logic similar to a blueprint for your code.
We can convert compatible types such as integers into floats or numeric
Type Conversion
strings into integers and vice versa.
Maths Using the “+” operator we can append (add to the end) strings to one
String Concatenation
Operator Functionality Shortcut/Comments another.
+ Addition += Boolean operators and Boolean logic are considered binary values True
Boolean Operators and False. They can also be represented by 1 and 0 and are the basis
- Subtraction -=
for comparisons.
* Multiplication x * y
/ Division Will always return a float Basic Data Types
// Integer Division Will always return an integer Python classifies data items. A classification represents the type of value that a particular data can
have and what operations may be performed on them. There are many more data types but these
% Modulo Returns the remainder of a division are the most common. You can get the type of a variable with print(type(variable_name)).
** Exponentiation x ^ y Data Type Values Allowed Examples

The maths module in Python provides access to mathematical int Integers 1, 2


functions which include methods and constants. You can call the Floating
Decimal Numbers 1.0, 9.136
maths library with import math. Numbers
Order of Operations Booleans True or False True, False
B-E-M-D-A-S Strings Written text, which can include numbers “Hi there”, “one”, “1”
A collection of items, all values allowed
Function Description Lists [True,1,1.0,”list”,[1]]
(including other lists)
math.pi Returns π
It is possible to transform one data type into another through a process called type conversion!
math.e Returns e
math.gcd(x, y) Returns the greatest common divisor of x and y Handy Tips!
● Focus on the fundamentals - you will always need them!
math.sqrt(x) Returns the square root of x ● Always practice - practicing is the best way to absorb material!
math.pow(x, y) Returns the value of x to the power of y ● Help! - always seek help and resources for things you don’t understand!
Integers Boolean Comparisons
Integers in Python can be 0, positive or negative numbers that do not include a fractional Boolean operators are ubiquitous in programming as it enables programs to make
part. You can perform mathematical operations such as addition, multiplication, integer decisions by comparing things and establishing a True or a False results. This
division, take them to a power as well as compare them using the comparison operators.
result is then used to select what behaviours we want our program to undertake.
We compare things with the following symbols:
Boolean
Booleans represent the truth value True or False and are commonly used to represent Example
Symbol Functionality Truth Value
the truth value of a statement or an expression. They can also be assigned to variables in Comparison
the same way that strings floats and integers can and may be the result of a comparison. Equality (not to be confused 5 == 5 True
== with the assignment operator
Floats “=”) 3 == 4 False
Floats (floating point numbers) represent decimals in Python. They can be assigned to
4 != 5 True
variables or be the result of a division using the ‘/’ on two integers. Due to the way in which
!= Not equal
they are stored they have limited precision so be very careful when handling small decimal 4 != 4 False
numbers.
3 < 4 True
Strings < Less than
Strings are a collection of alphabets, words, or characters (this also includes an empty 4 < 3 False
space!). Strings can be indexed as well as iterated over in loops. When calling a method on
4 > 3 True
a string we use string.method(). > Greater than
3 > 4 False
Method Functionality
4 <= 4 True
.upper() Converts a string into uppercase <= Less than or equal to
.lower()
4 <= 3 False
Converts a string into lowercase

.count(x)
4 >= 3 True
Counts the number of times x occurs within a string
>= Greater than or equal to
3 >= 4 False
.isnumeric() Returns True if ALL the characters in the string are numeric

Finds the first occurrence of the specified value and return an Variable Assignment
.find()
index A Python variable is a reserved memory location to store values. These values can
Splits the string at the specified separator (, or .) and returns a be integers, strings, floats, and lists among other things. We can then refer to that
.split() value by the variable name we gave it. We assign variables with “=”.
list
my_integer = 5 # We have assigned 5 to a variable my_integer
Returns a string where a specified value is replaced with a my_string = "Hello" # We have assigned a string "Hello" to my_string
.replace() my_list = [1, 2, 3, 4] # We have assigned a list to my_list
specified value my_float = 3.5 # We have assigned a float to my_float
Converting Variable Types Handy Tips!
It is possible to convert one data type into another (in some cases) and often you might find ● Make sure you know what data type you are working with, this
yourself doing it in order to perform some operation. There are two types of conversions in is often the source of much confusion.
Python: ● Make sure you choose the best data type for the job.
● If you are confused about a Boolean comparison try working it
Implicit Explicit out on paper first.
Users convert the data type of an object to the ● IndexErrors and ValueErrors are often trickier to find. Use print
required data type. We use the predefined functions statements when debugging to see where a program stops
Python automatically type converts one
like int(), float(), or str() to specify the desired type as working.
data type into another data type without
long as the data types are compatible (e.g., we cannot ● Get familiar with errors, you will encounter them often and
user involvement. One example of where
convert “hello” into an integer”. knowing how to read and interpret them is the best way
this happens is when we add an integer to
a float - the result is automatically a float. my_integer = 123 forward.
my_float = 1.23
my_integer = 123 my_string = "123" Logic Errors
my_float = 1.23 my_integer = str(my_integer) These occur when a program runs without crashing, but the output
result = my_integer + my_float my_string = float(my_string)
print(result) # 124.23 print(type(my_integer)) # <class 'str'> it produces is incorrect. This means that the logic implemented in
print(type(my_float)) # <class 'float'>
print(type(my_string)) # <class 'float'> incorrect. Python will not give you an error! It is important to
always double check your output and to check it often. Here are
Errors
Errors are the problem in a program which cause a program to stop executing. The error report some things that can help:
that Python gives us includes the type of error, the statement which caused the error and the line
● Understand the process you are implementing
where it occurred. Reading error reports is the first step to debugging. The advice is to run your
code often and make sure you fix them early. Below are some common errors you might ● Try and step through the code with print statements
encounter.
● Try it out on pen and paper
Error Description Advice
● Give the program a smaller range or smaller input to see
Raised when the index of a sequence is out of Double check the index of what
IndexError
range you are trying to access where it breaks down
Raised when a variable is not found in the Double check that this is the
NameError ● If the program is really long, test individual parts of it
local or global scope name of the variable
Raised by the parser when a syntax error is ● Try to explain it to someone else – rubber-ducking a
SyntaxError Double check your spelling
encountered
program is a tried and tested method
E.g., Taking the square root of a
Raised when a function gets an argument of negative number ● If all else fails, step away from the computer and the
ValueError
the correct type but improper value Double check the content of
the value input answer might just come to you.
Control Statements Lists
If and else statements are used to control the flow of a program. If a statement is true then Lists are data structures in Python which store items. They can store a variety of
we execute the body of the if statement. If the if statement is False then we consider the
data types and have notions of start, end and next. Items within a list can be
next statement which may be either an elif or an else. If neither the if or else statement is
directly accessed via their index (remember in Python indexing begins at 0) and
executed then we continue on to the rest of the program.
can be iterated over. We declare a list with the [ ] in Python and they can contain
Begin Control Flow any number of items which may or may not be of the same type. They can also
contain other lists.

num_list = [1, 2, 3, 4, 5] # A list of integers


word_list = ["Hello", "World"] # A list of strings
if True
expression
If code bool_list = [True, False, False] # A list of Booleans
mixed_list = ["Hello", 3, False] # A list with multiple data types

False
List Indexing
elif mixed_list = ["Hello", 3, False] # A list with multiple data types
expression True Else if code
print(mixed_list[0]) # The first item - Hello
print(mixed_list[1]) # 3
print(mixed_list[2]) # False
False print(mixed_list[-1]) # The last item - False
print(mixed_list[-2]) # 3
print(mixed_list[-3]) # Hello
else Else code print(mixed_list[4]) # IndexError!

List Indexing
Program Continues
We can apply a number of useful methods to lists. We call them using
list.method(). These are just a small number of methods which can be used with
my_number = 5 # Let's assign a variable lists. Make sure you explore!

Function Purpose
if my_number == 2: # If my_number is equal to 2 then… len() Returns the number of items in a list
print("My number is 2") # …execute this statement
elif my_number == 3: # If my_number is equal to 3 then… .append() Adds an item to the end of the list
print("My number is 3") # …execute this statement
.pop(index) Removes an item at a specified index and returns it
else: # If my_number isn't 2 or 3 then…
print("My number isn't 2 or 3") # …execute this statement .insert(index, item) Inserts item at index

# The program will print "My number isn't 2 or 3" .sort() Sorts a list in ascending order
Loops While Loops
While loops execute statements while a condition is satisfied. They
A control flow statement which is used to repeatedly execute a group of statements as long as a
are used to repeat a task for an indefinite amount of time. They
specific condition is satisfied - also known as iteration. There are two types of loops - while and for check the condition after every loop and stop when the condition
loops. All for loops can be written as while loops although the reverse is not true (think asking is false. Remember to initialise the counter and your exit condition
to avoid infinite loops.
users for input).
# Printing 1 to 5
i = 1
While Loop Structure while i < 6:
print(i)
Step 1: Initialise a counter. i += 1

# Print every item in my_list


Step 2: Define the condition to be tested each time the loop iterates or is performed. my_list = ["First", "Second", "Third"]
i = 0
while i < len(my_list):
Step 3: Use the while key word which begins the loop followed by your condition. print(my_list[i])
i += 1
Step 4: Add the condition which determines when the code block runs.
while
Step 5: Add in the code in the while loop body.

Handy Tips! condition


● Make sure you always have a condition which becomes false (at some point in time) otherwise
the loop will run forever.
● If there is no output when you are running it, add a print statement in the body to make sure
Checks True
it’s running. condition False
● Remember to initialise your counter (usually denoted by i)
● If you are confused about how many times the loop is running – try printing i, so you can get
an idea of what is going on. Code inside loop body
● You can use a while loop to read a file into a variable, asking for user input or increment i by
something non standard.
● Remember you can have complex while conditions! End of Loop
For Loops For Loop Structure Remember indexing in
For loops are used when a task is to be repeated a definite (known) Python starts at 0!
0 1 2 3
number of times such as looping of all the items in a list. They can
also be used to loop over a numeric range with the range function my_colours = ["black", "green", "red", "yellow"]
range(start, stop, step).
for colour in my_colours:
# Every 2nd number from 10 to 20 print(colour)
for i in range(10, 20, 2):
print(i) # black 0
# Print every item in a list Our for loop takes every colour in our list of colours
# green 1
my_list = ["First", "Second", "Third"] one by one and prints it until it reaches the end of
list_length = len(my_list)
for i in range(list_length): # red 2 our list.
print(my_list[i])
# yellow 3
for
Handy Tips!
Element ● Use a for loop to iterate over a string or a list!
exists? ● Remember the range function which allows you to select every nth element.
● Use the print statement to debug your loop – you can print which element you are working
False with at each step.
Increment
element True ● For loops are susceptible to IndexError as you might be trying to access things that aren’t IN
your list.
● If you get an IndexError add a print statement in your loop to see what iteration you get up to.
Code inside loop body

A Final Note…
End of Loop
Loops are the bread and butter of programming, and you are likely to use them often. They are
incredibly powerful tools for processing, and it is strongly encouraged that you practice them early

Good Luck! and get familiar with all their intricacies. Loops aid us in conducting repetitive tasks (which are
common) and are essential to saving time and minimising errors.

You might also like