Show Menu
Cheatography

Python - Beginner Syntax Cheat Sheet (DRAFT) by

A summary of all the Python programming language syntax I have learned so far. Still a noob so will have to be updated now and then.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Augmented assign­ment/ Assignment operators

a = b
Standard variable assignment
a += b
Equivalent to a = a + b
a -= b
Equivalent to a = a - b
a *= b
Equivalent to a = a * b
a /= b
Equivalent to a = a / b
a %= b
Equivalent to a = a % b
a **= b
Equivalent to a = a ** b;
a //= b
Equivalent to a = a // b;
Augmented assignment: Python supports augmented assignment for common arithmetic and logical operators.
Note: This is not an exhaustive list.

Input and output

input()
The input function prints text and expects a value from the user (string typed by user). Type functions (e.g. int()) can be used around it to get only certain types of values.
print()
The print function can print any number of expres­sions (separated by commas). Successive print statements will display on separate lines. A bare print will print a blank line.

General variable declar­ation and assignment

Declar­ation and initial assign­ment:
var_name = new_value

var_name
= 3 ** new_value`
var_name = other_var

etc.

Assignment statements involving initial variable value:
var_name = 2 * var_name

var_name = var_name ** 2 + 5


Simult­aneous assign­ment:
var_1, var_2... = value1, value2...
Variables: The basic mechanism by which data is organised and stored (long-­term, short-­term, and commun­ication etc.). Variables must be declared before referred to in other statem­ents.
Note: Variables can be reassigned as many times as needed.

General for loops

for variable in sequence_name:
     code body

for variable in [var1, var2, var3...]:
     code body

for variable in [const1, const2...]:
     code body

for variable in range(...):
     code body
For loops: A type of definite iterat­ions. Also reference to as control strctures.
Loop index: The variable after the for is called the loop index. It takes on each successive value in sequence.

Dealing with Strings

"­Str­ing­"[index]
String indexing, accesses an individual character found at the specified index in the string.
"­Str­ing­"­[in­dex­1:i­ndex2]
String slicing, returning a substring of the original string between the specified indexes
"­Str­ing­a" + "­Str­ing­b"
String concat­ena­tion, achieved with the + operator and puts the multiple strings together
"­Str­ing­" * int
Repeti­tion, returns the same string repeated a specified number of times in the same new string
len("St­rin­g")
Finds the character length of a string
for var in "­Str­ing­"
Iterates through all the characters in a string
"­str­ing­".up­per() OR "­str­ing­".lo­wer()
The upper() function changes all characters to upperc­ase­/lo­wercase
ord("ch­ar_­str­ing­") OR chr(int)
The ord() function returns the numeric (ordinal) code of a single character, the chr() function converts a numeric code to the corres­ponding character
\n
Prints to a new line in a string
"­"­" String \n string \n string "­"­"
Multiline strings, using three double quotes on each side of the text
Strings: Strings are used to represent a sequence of charac­ters, such as: names, addresses, general text etc. They are written in double quotes.
Slicing: The the substring starts at index1 but the last character is at index2-1. The indexes given must both be ints.
Slicing: If either start or end expression is missing, then the start or the end of the string is used.
Other: Not an exhausted list of functions, other useful ones include strip(), count(), find() and split() etc.

Searching

Simple searching:
wanted­_value in list_name
- tests for list membership
list_n­ame.in­dex­(wa­nte­d_v­alue)
- to find the position

Linear search:
for i in range(­len­(li­st_­name))

.     if list_n­ame[i] == wanted­_value:

.     .     return i

return None


Binary search:
low = 0

high = len(li­st_­name) - 1

while low <= high:

.     mid = (low + high) // 2

.     item = list_n­ame­[mid]

.     if wanted­_value == item:

.     .     return mid

.     if wanted­_value < item:

.     .     high = mid - 1

.     if wanted­_value > item:

.     .     low = mid + 1

return None
Simple searching: The problem with this is that the index method raises an exception if the sought item is not present.
Linear search: As soon as a value is encoun­tered that is greater than the target value, the linear search can be stopped without looking at the rest of the data.
Binary search: If the data is already sorted, at each step divide the remaining group of numbers into two parts and ignore the irrelevant one

Dealing with tuples

Ex.
(value1, value2, value3, etc.)

Sorting by element:
list_name.sort(key=lambda x:x[element_index])
Tuple: A sequence which looks like a list but uses () rather than []. They are immutable, so are used to represent sequences that are not supposed to change.
Lambda function: A small anonymous function which can take any number of arguments, but can only have one expres­sion.
 

Arithmetic operators

+
Addition - adds together two values.
-
Subtra­ction - subtracts one value from another.
*
Multip­lic­ation - multiplies two values together.
/
Floating point division - divides one value by another. The return value is exact (for floating point)
//
Intege­r/Floor division - divides one value by another. The remainder is truncated.
**
Expone­nti­ation - raises a number to the power of another number.
%
Modulus - returns the remainder of dividing a number with another number.
Arithmetic operators: Used to perform common mathem­atical operat­ions.
Preced­ence: Precedence and associ­ativity are as normal as in maths.

Comments

Single line comments:
# Comment1

code # Comment2


Multi-line comments:
"­"­"

Comment

Continuing comment

"­"­"
Comments: Comments are ignored by the computer, they exist simply to make the code easier for people to unders­tand.

Dealing with lists

Creating a list (ex.):
list_name = [1, "­Spa­m", 3.142, True]

months = ["Ja­n", "­Feb­", "­mar­", "­apr­", ...etc.]


Indexi­ng/­slicing lists:
list_n­ame­[index] OR
list_n­ame­[in­dex1: index2]

Some methods:
list_n­ame.ap­pen­d(n­ew_­item)

list.i­nde­x(o­bject)
(returns index of first occurence)
list_n­ame.min()
and
list_n­ame.max()

list_n­ame.re­verse()

len(li­st_­name)

list_1 + list2

var in list_name: etc.

list_n­ame.sort()

list_n­ame.re­mov­e(o­bje­ct_­to_­remove)

list_n­ame.po­p(i­ndex)
Lists: Lists are sequences of arbitrary values enclosed in square brackets. They can hold any datatype.
Mutable: Lists are mutable, meaning they can be changed. Strings can not be changed.
Note: Not an exhaustive list
TBC check

Numeric data types

int
Represents whole number­s/i­nte­gers. Can be positive or negative
float
Represents numbers that can have fractional parts - floating point values. (Even if the fractional part is 0)
Note: The float type stores only an approx­imation to the real number being repres­ented.
Note: Operations on ints produce ints (excluding /), operations on floats produce floats.
Type conver­sion: Combining an int with a float in an expression will return a float. And we can use the int and round functions to explicitly convert between different types. Converting a float to an int will truncate.
Type: We can use the type function to find the data type.

General if -elif-­els­e-s­tat­ements

if boolean_condition:
     statements to execute if condition is True
elif boolean_conditino:
     do these statements if the if-statement and elif
     -statements above returned False,
     but the test for this statement returned True.
else:
     do these statements if none of the above tests returned True.
if statem­ents: The condition statement is evaluated and if it evaluates to True, the indented statements in the body are executed; otherwise, execution proceeds to next statement.
Note: Don't forget the colon!

General while loops

while boolean_condition: 
     code body
While loop: A form of indefi­nit­e/c­ond­itional interation loop. It keeps iterating until the boolean condition is no longer true.

Break statement

loop decl:
     code body etc.
     if boolean_condition:
          break
     code body etc.
Break statement: Executing break cases Python to immedi­ately exit the enclosing loop.
Note: It is sometimes used to exit what looks like an infinite loop.
Loop and a half: The loop exit is in the middle of the loop body. It is an elegant way to avoid the priming read in a sentinel loop.
Note: Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits.

Continue statement

loop decl: 
     code body etc.
     if boolean_condition: 
          continue
     code body etc.
Continue statement: Returns the control to the beginning of the loop escaping the rest of the code body.

Recursion

def rec_func(n):
     if base_case_condition:
          return value
     else:
          return computation * rec_func(n_closertobc)
Recursion: A descri­ption of something that refers to itself is called a recursive defini­tion.
Base case: Recursion is not circular because we eventually get to the base case that has a closed expression that can be directly computed.

Dealing with dictio­naries

Creating dictio­naries:
dict_name = {}

dict_name = {key1:­value1, key2:v­alue2, key3...etc.}


Adding­/in­iti­ali­sin­g/c­hanging key-value pairs:
dict_n­ame­[key] = new_value


Getting objects from keys:
dict_n­ame­[key]
(if the dictionary does not have the key an exception is raised

Some functi­ons­/op­era­tions:
key in dict_name
to check if the key exists
del dict_n­ame­[key]
to delete the entry corres­ponding to the key
dict_n­ame.po­p(key)
to delete the entry and return the value
dict_n­ame.cl­ear()
to delete all entries in the dictionary
dict_n­ame.keys()
to return all the key values only
dict_n­ame.it­ems()
to return tuples of all the key-value pairs
dict_n­ame.va­lues()
to return all the values only
dict_n­ame.ge­t(key, default)
if dictionary has the key return its value, otherwise returns default
dict_n­ame.se­tde­fau­lt(key, value)
if dictionary has the key do nothing, otherwise set it to value
Dictio­nary: Widely used collec­tio­n/c­ompound data type. Allows us to look up inform­ation associated with arbitrary keys (mapping)
Note: The order of the keys won't matter.
 

String formatting

"index : width.precision,type".format(text)

Ex.
"Count {0:0.20f}".format(3.14)
-> 'Count 3.1400000000000001243'
Meanings: index - which parameter to insert into the slot; width tells us how many spaces to use to display the value; 0 means to use as much space as necessary; precision is the number of decimal places
Fixed point numbers: Denoted using f in the example.

Logica­l/B­oolean operators

not
Inverse the comparison result
and
Returns True only if both inputs are True
or
Returns True if at least one input is True
Preced­ence: The interp­ret­ation of the expres­sions relies on the precedence rules for the operators.

Range function

range(­stop)
(starts from 0 and goes up 1 until (stop - 1))
range(­start, stop)
starts from start and goes up 1 until (stop - 1))
range(­start, stop, step)
starts from start and goes by step (positive or negative) until (stop - 1)
list(r­ang­e(...))
makes a list

Importing modules

Importing:
import module­_name
OR
import module­_name as new_name

from module­_name import function1


Calling functions:
module­_na­me.f­un­cti­on_­nam­e(...)

new_na­me.f­un­cti­on_­nam­e(...)

functi­on1­(...)
Module: A file consisting of Python code which can define functions, classes, variables and may also include runnable code.
Note: When Python imports a module, it executes each line. Modules need to be imported in a session only once.
Library: A library is a module with some useful defini­tio­ns/­fun­ctions.

Defining a function

def func_name():
     code body

def func_name(paramname1, paramname2 etc.):
     code body
Function: A function is a block of organised, reusable code that is used to perform a single, related action. It is invoked or executed by typing its name.
Parame­ters: Parameters can be used to customise the output of a function. A function that has parameters requires arguments. If that parameter is not specified an error is returned.

Relati­ona­l/C­omp­arison operators

==
Equal to
!=
Not equal to
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
Relational operators: Operators used to compare two values - usually numbers, but also sometimes other types.
Preced­ence: All have lower precedence than all arithmetic operators, and higher than all logical operators.

File processing

Opening files:
file_var = open (file_­name, mode)
(mode - 'r' (read), 'w' (write), or 'a' (append)) OR
with open(f­ile­_name) as file_var: processing
(when statements in that block have finished running, file will close automa­tic­ally)

File methods:
file.r­ead()
- returns entire remaining contents as single string
file.r­ead­line()
- returns next line of file. All text up to and including next newline character
file.r­ead­lines()
- returns list of remaining lines in file. Each list item is single line including newline characters

Efficient proces­sing:
for line in infile: processing
File: A sequence of data that is stored in secondary memory (disk drive). They can contain any data type, and usually contains more than one line of text.
Note: When you've finished working with a file, it needs to be closed. In some cases, not properly closing a file could result in data loss.
Note: Multiple calls to readline() is ineffi­cient.
Note: May use writel­ines() for writing sequen­ce(­list) of strings.

Exception handling

try: 
     code body
except ErrorType:
     handler code
Try-ex­cept: When python encounters a try statement, it attempts to execute the try body. If an exception is raised, the handler is executed. If not, control passes to the statement after.
Note: There can be multiple except blocks. This acts like 'elif'.
Except: A bare except acts like an 'else' and catches any errors without a specific exception type.
Note: Exceptions are intended for except­ional circum­stances and should not be used as a substitute for if statem­ents.

Pseudo­Random numbers

randra­nge­(start, stop, step)
Randomly selects an integer value from a range. range() rules apply.
choice­(li­st_­name)
Chooses a random member of a given list.
random()
Returns a random number in the range [0...1.0). (0 can be returned but not 1.0))
seed()
Assign the random number generator a fixed starting point (to give reprod­ucible behaviour during testing)
Pseudo­random number generator: Starts with a seed value to produce a "­ran­dom­" output. The next time a random number is required, the current value is fed back into the function to produce a new number.
Note: This sequence of numbers appears to be random, but if you start the process over again with the same seed number, you'll get the same sequence of "­ran­dom­" numbers.