0% found this document useful (0 votes)
2 views37 pages

Python Fundamentals - Lesson 4_ Getting Started With Python

This lesson introduces the basics of Python programming, covering syntax, variables, data types, and collection data types. Learners will gain skills in writing Python code, assigning values to variables, and understanding key data types like strings, integers, and lists. The lesson includes practical exercises to reinforce learning through hands-on coding in a code editor or Google Colab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Python Fundamentals - Lesson 4_ Getting Started With Python

This lesson introduces the basics of Python programming, covering syntax, variables, data types, and collection data types. Learners will gain skills in writing Python code, assigning values to variables, and understanding key data types like strings, integers, and lists. The lesson includes practical exercises to reinforce learning through hands-on coding in a code editor or Google Colab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

LESSON 4: GETTING STARTED

WITH PYTHON
LEARNING OBJECTIVES
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

LESSON OVERVIEW
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 SYNTAX
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++.

Key Rules of Python Syntax


1. Comments
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
"""

✅ Try It:
Open Google Colab, create a new notebook, and run the examples above in new code cells.
2. Indentation
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")

✅ Try It:
Run the examples above in new code cells.
3. Lines
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)

✅ Try It:
Run the examples above in new code cells.

4. Semicolons
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")

✅ Try It:
Run the examples above in new code cells.
VARIABLES
A variable is like a container that holds a value. Python has no command for declaring a variable.

Rules for Naming Variables


1. Must start with a letter or underscore (_)
2. Cannot start with a number
3. Use lowercase letters and underscores (e.g., total_score)
4. 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

✅ Try It:
Run the examples above in new code cells.

Value Assignment
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)

✅ Try It:

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)

✅ Try It:

Run the examples above in new code cells.

DATA TYPES
Python automatically detects the type of value you assign to a variable.

Basic Data Types


1. Numbers
Python supports integers (whole number), floats (decimal number), and complex numbers.

Python Code
x = 5 # int
y = 3.14 # float
z = 1 + 2j # complex

✅ Try It:

Run the examples above in new code cells.


2. String
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)

✅ Try It:

Run the examples above in new code cells.


3. Boolean
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

✅ Try It:

Run the examples above in new code cells.

Get the Data Type - type() Function


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))

✅ Try It:

Run the examples above in new code cells.

Specify Data Type - Casting


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)
print(bool( Hi )) # True (non empty string)

✅ Try It:

Run the examples above in new code cells.

Why use Casting?


1. To prepare input from users
Python Code
age = int(input("Enter your age: ")) # Convert user input to int

2. To fix data format from APIs or files


Python Code
temperature = float("25.5") # Convert string from file to float

3. To force a specific format in calculations


Python Code
total = float(3) + 2.5

✅ Try It:

Run the examples above in new code cells.

Collection Data Types


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.

1. List
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

✅ Try It:

Run the examples above in new code cells.


Insert Item(s) into a List
🔹 .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']

✅ Try It:

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']

✅ Try It:

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']

✅ Try It:

Run the examples above in new code cells.


Removing Items from a List
🔹 .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)

✅ Try It:

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)

✅ Try It:

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.

✅ Try It:

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: []

✅ Try It:

Run the examples above in new code cells.


2. Tuple
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

✅ Try It:

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')

✅ Try It:

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

✅ Try It:

Run the examples above in new code cells.


3. Set
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

✅ Try It:

Run the examples above in new code cells.


Insert Item(s) into a Set
🔹 .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'}

✅ Try It:

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'}


✅ Try It:

Run the examples above in new code cells.


Remove Item(s) into a Set
🔹 .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'

✅ Try It:

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'}

✅ Try It:

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

✅ Try It:

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()

✅ Try It:

Run the examples above in new code cells.

🔹 del – Deletes the entire set.


Python Code
f {" l " "b " " "}
fruits = {"apple", "banana", "orange"}
del fruits
# print(fruits) # NameError: name 'fruits' is not defined

✅ Try It:

Run the examples above in new code cells.


4. Dictionary
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

✅ Try It:

Run the examples above in new code cells.


Insert Item(s) into a Dictionary
🔹 Using bracket notation (most common)
Python Code
student["school"] = "SK Kajang"
print(student) # Output: {'name': 'Ali', 'age': 12, 'class': '6A', 'school': 'SK Kajang'}

✅ Try It:

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}

✅ Try It:

Run the examples above in new code cells.


Remove Item(s) into a Dictionary
🔹 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}

✅ Try It:

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}

✅ Try It:

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)
i t( t d t) # O t t {' ' 'Ali' ' h l' 'SK K j ' ' d ' 'A' 'h bb ' 'b d i t '}
print(student) # Output: {'name': 'Ali', 'school': 'SK Kajang', 'grade': 'A', 'hobby': 'badminton'}

✅ Try It:

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'}

✅ Try It:

Run the examples above in new code cells.

🔹 .clear() – Removes all items.


Python Code
student.clear()
print(student) # Output: {}

✅ Try It:

Run the examples above in new code cells.

🔹 del - Delete the whole dictionary.


Python Code
del student
del student
# print(student) # ❌ NameError: name 'student' is not defined

✅ Try It:

Run the examples above in new code cells.

SELF-CHECK QUIZ
🧠 Answer these to test your understanding.
1. Which of the following is a valid variable name?
A) 3total
B) userName
C) def
D) print

2. What is the type of the following value: 42.0?


A) int
B) str
C) float
D) bool

3. What will this code output?


x = True
print(type(x))

A) <class 'bool'>
B) <class 'str'>
C) <class 'int'>
D) <class 'float'>

HANDS-ON TASK
🔧 Instructions:
1. Open Google Colab.
2. Create a new notebook.
3. Practice the example codes in sections (1) Python Syntax, (2) Variables, (3) Data Types
4. 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

Copyright @ 2025 Prasanna Ramakrisnan. All Rights Reserved

You might also like