By the end of this lesson, you will be able to:
🎯 Identify and use correct Python syntax
🎯 Create and assign values to variables
🎯 Distinguish between key Python data types
🎯 Use the type() function to check variable types
🎯 Write and run simple Python programs in a code editor or Google Colab
Python is a high-level, easy-to-read language, popular among beginners and professionals alike. In this lesson, you’ll learn the foundation of Python programming: how to write code correctly, store information using variables, and work with different types of data.
Python is known for its clean and simple syntax. That means fewer symbols and punctuation marks compared to many other programming languages like Java or C++.
Comments are completely ignored by the interpreter. They are meant for fellow programmers. In Python, there are two types of comments:
Single-line comment - use #
Multi-line comment - use either ''' or """
Python Code
#My first Python code
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
Open Google Colab, create a new notebook, and run the examples above in new code cells.
Indentation refers to the spaces at the beginning of line of code (use space bar or tab). Python uses indentation to indicate a block of code.
Python Code
if 5 > 3:
print("Five is greater than three")
if 5 > 3:
print("Five is greater than three")
if 10 > 3:
if 15 > 3:
print("All numbers are greater than 3")
Run the examples above in new code cells.
Backslash can be used to place long statements on multiple lines. Semicolon can be used to put multiple short statements on the same line.
Python Code
#This is a long statement broken into two lines by using a backslash
result = 1 + 2 + 3 + 4 + \
5 + 6 + 7 + 8 + 9
print(result)
#These are two short statements placed on the same line using a semicolon
name = "Aminah"; age = 30; print(name, age)
Run the examples above in new code cells.
Statements end at the end of the line. No semicolons used in the codes to indicate the end of the line.
Python Code
#No semicolon at the end of line
print("Hello")
Run the examples above in new code cells.
A variable is like a container that holds a value. Python has no command for declaring a variable.
Must start with a letter or underscore (_)
Cannot start with a number
Use lowercase letters and underscores (e.g., total_score)
Cannot use reserved Python keywords like if, print, True
Python Code
x = 3
y = "Hello"
print(x)
print(y)
#Good variable names
student_name = "Aida"
age = 15
#Bad variable names
2name = "Ali" # ❌ Invalid: starts with a number
class = "English" # ❌ Invalid: 'class' is a keyword
Run the examples above in new code cells.
Assigning a value to a variable is done using the assignment operator (=).
Assignments can be done on more than one variable "simultaneously" on the same line or assign the same value to multiple variable.
Python Code
#assign values to multiple variable
x, y, z = 5,10,15
print(x)
print(y)
print(z)
#assign the same value to multiple variable
a = b = c = 3
d = 6
print(a)
print(b)
print(c)
print(d)
Run the examples above in new code cells.
Arithmetic operations can be performed and directly assign the result to a variable. These operations are commonly used when you want to store or update values during a program's execution.
Python Code
# Addition (+)
x = 5
y = 10
print(x + y)
a = 3 + 6
print(a)
# Subtraction (-)
b = 5 - 2
print(b)
# Multiplication (*)
c = 2 * 4
print(c)
# Division (/)
d = 15 / 3
print(d)
# Modulus (%)
e = 7 % 3
print(e)
# Floor Division (//)
g = 7 // 3
print(g)
# Exponent (**)
f = 2 ** 4
print(f)
Run the examples above in new code cells.
Python automatically detects the type of value you assign to a variable.
Python supports integers (whole number), floats (decimal number), and complex numbers.
Python Code
x = 5 # int
y = 3.14 # float
z = 1 + 2j # complex
Run the examples above in new code cells.
Strings are sequences of characters. String variables can be declared either using single ' or double " quotes.
Python Code
name = "Alice"
print(name)
mystring1 = 'Hello world!'
mystring2 = "Hello world!"
print(mystring1)
print(mystring2)
Run the examples above in new code cells.
A Boolean data type in Python has only two possible values: True or False
These are often used in conditional statements, comparisons, and logic operations.
Python Code
x = True
y = False
print(y) # Output: False
is_sunny = True
is_raining = False
print(is_sunny) # Output: True
# +++ Python automatically returns a Boolean when you perform a comparison +++
# Equal (==)
result1 = 5 == 5
print(result1)
# Not Equal (!=)
result2 = 5 != 5
print(result2)
# Greater Than (>)
result3 = 5 > 3
print(result3)
# Less Than (<)
result4 = 5 < 3
print(result4)
# Greater Than or Equal To (>=)
result5 = 5 >= 3
print(result5)
# Less Than or Equal To (<=)
result6 = 5 <= 3
print(result6)
# +++ some functions return Boolean values +++
name = "Ali"
print(name.isalpha()) # True - only letters
number = "1234"
print(number.isdigit()) # True - only digits
Run the examples above in new code cells.
Function type() to get the data type of a variable.
Python Code
x = 3
y = 3.0
z = "Hello"
print(type(x))
print(type(y))
print(type(z))
Run the examples above in new code cells.
If you want to specify the data type of a variable, this can be done with casting. Casting means using constructor functions to change the data type of a variable.
Python Code
x = int(3.7) # Float to int
print(x) # Output: 3
y = int("10") # String to int
print(y) # Output: 10
# If the string cannot be converted to an integer (e.g., "ten"), it will raise an error
# int("ten") # ❌ This will cause an error
a = float(5) # Integer to float
print(a) # Output: 5.0
b = float("12.34") # String to float
print(b) # Output: 12.34
name = str(100)
print(name) # Output: "100"
print(type(name)) # Output: <class 'str'>
greeting = "Hello " + str(2025)
print(greeting) # Output: Hello 2025
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False (empty string)
print(bool("Hi")) # True (non-empty string)
Run the examples above in new code cells.
To prepare input from users
Python Code
age = int(input("Enter your age: ")) # Convert user input to int
To fix data format from APIs or files
Python Code
temperature = float("25.5") # Convert string from file to float
To force a specific format in calculations
Python Code
total = float(3) + 2.5
Run the examples above in new code cells.
Python Collection Data Types are used to group multiple items into a single variable. Each collection type has its own structure, behavior, and purpose.
Lists, tuples, sets, and dictionaries are built-in data types in Python. They are all collection data types that is used to store multiple values in a single variable.
A list is a mutable, ordered collection of items.
🔹 List Characteristics:
Defined using square brackets [ ]
Items are indexed starting at 0
Items have a fixed order
Items can be added, changed, or removed
Can store different data types together
Allows duplicates
Python Code
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: banana
Run the examples above in new code cells.
🔹 .appent() - adds an item to the end of list
Python Code
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add item
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Run the examples above in new code cells.
🔹 .insert(index,item) - inserts an item at a specific index
Python Code
fruits = ["apple", "banana", "cherry", "orange"]
fruits.insert(1,"grapes") # Insert item into index 1
print(fruits) # Output: ['apple', 'grapes', 'banana', 'cherry', 'orange']
Run the examples above in new code cells.
🔹 .extend(iterable) - adds multiple items from another interable (eg:list, tuple) to the end of the list
Python Code
fruits = ["apple", "banana", "cherry", "orange"]
fruits.insert(1,"grapes") # Insert item into index 1
print(fruits) # Output: ['apple', 'grapes', 'banana', 'cherry', 'orange']
fruits.extend(["papaya","watermelon"]) # Insert items at the end
print(fruits) # Output: ['apple', 'grapes', 'banana', 'cherry', 'orange', 'papaya', 'watermelon']
Run the examples above in new code cells.
🔹 .remove() - removes the first occurrence of the list
Python Code
fruits = ["apple", "banana", "cherry", "orange", "banana", "papaya", "watermelon"]
fruits.remove("banana") # removes first occurrence of item banana
print(fruits)
Run the examples above in new code cells.
🔹 .pop(index) - removes item at given index (default:last), returns the removed item, useful if want to use removed value
Python Code
fruits = ["apple", "banana", "cherry", "orange", "banana", "papaya", "watermelon"]
remove_item = fruit.pop(1)
print(remove_item)
print(fruits)
Run the examples above in new code cells.
🔹 del - deletes an item by index or a slice of items, does not return the value, can also delete entire lists or variables.
Python Code
fruits = ["apple", "banana", "cherry", "orange", "banana", "papaya", "watermelon"]
del fruits[0]
print(fruits)
del fruits[:] # deletes all item. Output: []
print(fruits)
del fruits # deletes the variable.
# Trying to print(fruits) after del fruits. Will raise an error because the variable is gone.
Run the examples above in new code cells.
🔹 .clear() - removes all items from the list or other collection (like set and dictionary)
Python Code
fruits = ["apple", "banana", "orange"]
fruits.clear()
print(fruits) # Output: []
Run the examples above in new code cells.
A tuple is like a list, but immutable (cannot be changed after creation).
🔹 Tuple Characteristics:
Defined using parentheses ()
Item have a fixed order
Cannot be modified after creation
Faster than lists
Allows duplicates
Python Code
dimensions = (10, 20)
print(dimensions[0]) # Output: 10
Run the examples above in new code cells.
In Python, cannot add or delete individual items from a tuple because tuples are immutable. You can only (1) reassign the whole tuple or (2) delete the entire tuple variable.
🔹 Reassign the whole tuple
Python Code
my_tuple = ("apple", "banana", "cherry")
new_tuple = my_tuple + ("orange",) # Adding item
print(new_tuple) # Output: ('apple', 'banana', 'cherry', 'orange')
Run the examples above in new code cells.
🔹 Delete the entire tuple variable
Python Code
my_tuple = (1, 2, 3)
del my_tuple
# print(my_tuple) # ❌ NameError: name 'my_tuple' is not defined
Run the examples above in new code cells.
A set is an unordered collection of unique items.
🔹 Set Characteristics:
Defined using curly braces {}
Items are unordered - no indexing
Can add / remove items
No duplicates (Useful for removing duplicates or checking membership)
Python Code
numbers = {1, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4} — duplicates removed
Run the examples above in new code cells.
🔹 .add(item) – Adds a single item to the set.
If the item already exists, it does nothing because sets do not allow duplicates.
Python Code
fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'orange'}
fruits.add("apple") # Won't add 'apple' again
print(fruits) # Output: {'apple', 'banana', 'orange'}
Run the examples above in new code cells.
🔹 .update(iterable) – Adds multiple items from an iterable (list, tuple, or another set).
New elements are added one by one, and duplicates are ignored.
Python Code
fruits = {"apple", "banana"}
fruits.update(["orange", "grape"])
print(fruits) # Output: {'apple', 'banana', 'orange', 'grape'}
fruits.update({"melon", "apple"})
print(fruits) # Output: {'apple', 'banana', 'orange', 'grape', 'melon'}
Run the examples above in new code cells.
🔹 .remove(item) – Removes an item from the set.
If the item is not found, it raises a KeyError.
Python Code
fruits = {"apple", "banana", "orange"}
fruits.remove("banana")
print(fruits) # {'apple', 'orange'}
# fruits.remove("grape") # KeyError: 'grape'
Run the examples above in new code cells.
🔹 .discard(item) – Removes an item, but does not raise an error if the item is not found.
Python Code
fruits = {"apple", "banana", "orange"}
fruits.discard("banana")
print(fruits) # Output: {'apple', 'orange'}
fruits.discard("grape") # No error even though 'grape' is not in the set
print(fruits) # Output: {'apple', 'orange'}
Run the examples above in new code cells.
🔹 .pop() – Removes and returns an arbitrary item from the set.
Since sets are unordered, there is no guarantee of which item will be removed.
Python Code
fruits = {"apple", "banana", "orange"}
removed_item = fruits.pop()
print(removed_item) # Random item, e.g., 'apple'
print(fruits) # Output: Remaining items
Run the examples above in new code cells.
🔹 clear() – Removes all items from the set.
Python Code
fruits = {"apple", "banana", "orange"}
fruits.clear()
print(fruits) # Output: set()
Run the examples above in new code cells.
🔹 del – Deletes the entire set.
Python Code
fruits = {"apple", "banana", "orange"}
del fruits
# print(fruits) # NameError: name 'fruits' is not defined
Run the examples above in new code cells.
A dictionary stores data in key-value pairs.
🔹 Dictionary Characteristics:
Defined using curly braces {} with key : value format
Keys must be unique
Ordered (as of Python 3.7+)
Can change or update values
Values can be of any data type
Useful for structured data (like JSON)
Python Code
# Example dictionary
student = {
"name": "Ali",
"age": 12,
"class": "6A"
}
print(student["name"]) # Output: Ali
Run the examples above in new code cells.
🔹 Using bracket notation (most common)
Python Code
student["school"] = "SK Kajang"
print(student) # Output: {'name': 'Ali', 'age': 12, 'class': '6A', 'school': 'SK Kajang'}
Run the examples above in new code cells.
🔹 .update() – Can add one or more items at once.
Python Code
student.update({"grade": "A"})
student.update({"hobby": "badminton", "height": 140})
print(student)
# Output: {'name': 'Ali', 'age': 12, 'class': '6A', 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton', 'height': 140}
Run the examples above in new code cells.
🔹 del keyword - Removes item by key.
Python Code
del student["class"]
print(student)
# Output: {'name': 'Ali', 'age': 12, 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton', 'height': 140}
Run the examples above in new code cells.
🔹 .pop(key) – Removes and returns the value.
Python Code
age = student.pop("age")
print(age) # 12
print(student)
# Output: {'name': 'Ali', 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton', 'height': 140}
Run the examples above in new code cells.
🔹 .popitem() – Removes and returns the last inserted item (Python 3.7+).
Python Code
last = student.popitem()
print(last) # Output: ('height', 140)
print(student) # Output: {'name': 'Ali', 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton'}
Run the examples above in new code cells.
🔹 .popitem() – Removes and returns the last inserted item (Python 3.7+).
Python Code
last = student.popitem()
print(last) # Output: ('height', 140)
print(student) # Output: {'name': 'Ali', 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton'}
Run the examples above in new code cells.
🔹 .clear() – Removes all items.
Python Code
student.clear()
print(student) # Output: {}
Run the examples above in new code cells.
🔹 del - Delete the whole dictionary.
Python Code
del student
# print(student) # ❌ NameError: name 'student' is not defined
Run the examples above in new code cells.
🧠 Answer these to test your understanding.
Which of the following is a valid variable name?
A) 3total
B) userName
C) def
D) print
What is the type of the following value: 42.0?
A) int
B) str
C) float
D) bool
What will this code output?
x = True
print(type(x))
A) <class 'bool'>
B) <class 'str'>
C) <class 'int'>
D) <class 'float'>
🔧 Instructions:
Open Google Colab.
Create a new notebook.
Practice the example codes in sections (1) Python Syntax, (2) Variables, (3) Data Types
Write a small program that:
Stores your name, age, and student status in variables
Prints all the values with a label
Displays the data type of each variable