COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
LEARN TO CODE     >     PYTHON     >    QUICK REFERENCE
Picture
PYTHON | QUICK REFERENCE
This section gives a quick reference to popular Python commands
CLICK  + TO EXPAND EACH SECTION ⬇
SECTION 1 | BASIC SYNTAX
ELEMENT
DESCRIPTION
Variables
Variables are containers for storing data values. Remember the rules for creating variables.
VARIABLE NAMING RULES
✘ Cannot start the name with a number
​✘ Cannot contain spaces
​✘ Cannot use command words such as print, python, turtle, exit, for, while and many more...
VARIABLE NAMING CONVENTIONS
✓Should start with a lowercase letter
✓If more than one word used the first letter uppercase of proceeding words or use _ to join words
​✓Names should be meaningful to the content of the variable​

firstName = "John"
age = 25
​input()
The input() function allows you to prompt the user for input.

​user_name = input("Enter your name: ")
​Single Line Comments
 Used to add comments to your code that Python will ignore during execution.
​# This is a single-line comment
Multi Line Comments
Python does not have a specific syntax for multi-line comments, but you can use triple quotes.
'''
This is a multi-line comment.
Python will ignore this during execution.
'''
print()
The print() function outputs text or variables to the console.

​print("Hello, World!")
Strings
​ Strings are sequences of characters, enclosed in either single or double quotes.

greeting = ("Hello")
Concatenate with +
Concatenate strings and variables using the + sign joins them together as one value.

message = ("Hello " + name)
Concatenate with ,
Using a comma in the print() function to join strings and variables.

print("Hello", name)​
Concatenate with f{}
Using the f method to ​format strings allow you to embed expressions inside string literals.

​message = (f"My name is {name} and I am {age} years old.")
SECTION 2 | DATA TYPES
ELEMENT
DESCRIPTION
string
Strings are sequences of characters, enclosed in either single or double quotes.

greeting = ("Hello")
age = ("10") #Remember if you put a number in speech-marks Python will treat it as a string/text

integer - int
int - ​this is a integer number (no decimal places)

​num = (10)

float
​float - the is a number with decimal places

​num = (10.55)

boolean
Boolean represents one of two values: True or False.
​
is_student = True
has_graduated = False
SECTION 3 | OPERATORS
Picture
​ARITHMETIC OPERATORS
Picture
COMPARISON OPERATORS
Picture
ASSIGNING OPERATORS
Picture
LOGIC OPERATORS
SECTION 4 | IF STATEMENTS
ELEMENT
DESCRIPTION
EXAMPLE
if
Used to perform different actions based on different conditions. if: Executes a block of code if the specified condition is true.
​if age > 18:
    print("You are an adult.")
elif
​Executes a block of code if the previous conditions were not true, but the current condition is true.
if age < 13:
    print("You are a child.")
elif age < 18:
    print("You are a teenager.")
else
​ Executes a block of code if no conditions are true.
​if age < 18:
    print("You are not an adult.")
else:
    print("You are an adult.")
indentation
In Python, indentation is used to define code blocks. Unlike many other programming languages that use braces {} or other symbols to define code blocks, Python uses whitespace (tabs).

Purpose: Indentation allows Python to determine which statements belong to a particular code block, such as those inside a loop or a conditional statement. This makes the code more readable and enforces a consistent structure.
age = int(input("how old are you: "))
​​if age > 18:
    print("You are an adult.")
​name = input("What is your name")

#In this example only the print statement is inside the if statement
SECTION 5 | LOOPS
ELEMENT
DESCRIPTION
EXAMPLE
for value in
Iterates over a sequence (like a list, tuple, or string) and executes a block of code for each item in the sequence.
​for fruit in ["apple", "banana"]:
    print(fruit)
for num in range
​The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (also by default), and stops before a specified number.
for num in range(5):
    print(num)  # Outputs: 0, 1, 2, 3, 4
​Specifying Start and Stop
Generates a sequence of numbers starting from the first specified number up to (but not including) the second specified number.
for i in range(2, 5):
    print(i)  # Outputs: 2, 3, 4
Specifying Step
Adds a third argument to specify the increment.
​for i in range(0, 10, 2):
    print(i)  # Outputs: 0, 2, 4, 6, 8
while
​Executes a block of code as long as the specified condition is true.
​count = 0
while count < 5:
    print(count)
    count += 1
break
Used to change the behavior of loops during their execution.
break: Exits the loop and continues executing the code after the loop.
for number in range(10):
    if number == 5:
        break
    print(number)
continue
Skips the current iteration of the loop and continues with the next iteration.
​for number in range(5):
    if number == 2:
        continue
    print(number)
pass
 A null operation; nothing happens when it's executed. It's used as a placeholder.
​for letter in "Python":
    if letter == "h":
        pass
    print(letter)
SECTION 6 | ARRAYS
DESCRIPTION
EXAMPLE
append()
 Adds an element to the end of the list.​
​fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) 
​# Outputs: ['apple', 'banana', 'cherry']
remove()
Removes the first occurrence of the specified value from the list.
​fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # Outputs: ['apple', 'cherry']
​pop()
Removes the element at the specified position, or the last element if no index is specified.
​fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)  # Outputs: ['apple', 'cherry']
​extend()
​Adds elements from another list (or any iterable) to the end of the current list.
fruits = ["apple", "banana"]
fruits.extend(["cherry", "date"])
print(fruits) 
​# Outputs: ['apple', 'banana', 'cherry', 'date']
​count()
​Returns the number of times the specified value appears in the list.
​numbers = [1, 2, 3, 2, 4, 2]
count = numbers.count(2)
print(count)  # Outputs: 3
​index()
Returns the index of the first occurrence of the specified value.
​fruits = ["apple", "banana", "cherry"]
idx = fruits.index("banana")
print(idx)  # Outputs: 1
​sort()
​Sorts the list in ascending order by default.
​numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)  # Outputs: [1, 2, 3, 4]
​reverse()
​Reverses the order of the list.
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) 
​# Outputs: ['cherry', 'banana', 'apple']
copy()
​Returns a copy of the list.
​newList = myList.copy()
clear()
​Removes all the elements from the list
listName.clear()
​set()
​Remove duplicates from a list
​myList2 = set(myList1)
SECTION 7 | 2D ARRAYS
ELEMENT
DESCRIPTION
EXAMPLE
Accessing Elements
Access elements using row and column indices.
​matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2])  # Outputs: 6
​Appending Rows
​Add a new row to the 2D list.
matrix = [[1, 2, 3], [4, 5, 6]]
matrix.append([7, 8, 9])
print(matrix) 
​# Outputs: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
​Appending Columns
​Add a new column to the 2D list.
matrix = [[1, 2], [4, 5], [7, 8]]
for row in matrix:
    row.append(0) # Appending 0 to each row
print(matrix) 
# Outputs: [[1, 2, 0], [4, 5, 0], [7, 8, 0]]
​Removing Rows
​Remove a row from the 2D list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix.pop(1)
print(matrix) 
​# Outputs: [[1, 2, 3], [7, 8, 9]]
​Flattening a 2D List
​Convert a 2D list into a 1D list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) 
​# Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9]
SECTION 8 | FUNCTIONS
ELEMENT
DESCRIPTION
EXAMPLE
Defining Functions
​Functions are blocks of reusable code. They are defined using the def keyword.
​def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Outputs: Hello, Alice!
​Positional Arguments
​Functions can take arguments (inputs) and return values (outputs).

Positional Arguments: Arguments passed in order.
​def add(x, y):
    return x + y
Keyword Arguments
Keyword Arguments are ​Arguments passed by name.
​def print_info(name, age):
    print(f"Name: {name}, Age: {age}")

print_info(age=30, name="John")
​Default Arguments
Default Arguments are Arguments with default values.
​def greet(name="Guest"):
    return f"Hello, {name}!"

print(greet())  # Outputs: Hello, Guest!
​Return Values
​Use the return keyword to send a result back
​def square(num):
    return num * num

result = square(4)  # result is 16
*args
​*args allows you to pass a variable number of positional arguments to a function. Inside the function, args is a tuple containing all passed arguments.
def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3, 4))  # Outputs: 10
​*kwargs
**kwargs allows you to pass a variable number of keyword arguments to a function. Inside the function, kwargs is a dictionary containing all passed keyword arguments.
def print_data(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_data(name="John", age=30, country="USA")
# Outputs:
# name: John
# age: 30
# country: USA
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.