O-Level Computing Theory
O-Level Computing Theory
This document follows the structure of the Singapore–Cambridge General Certificate of Education Ordinary Level (2022)
Syllabus coded 7155 using content from the Third Version Textbook.
This document is neither standalone nor a replacement for the textbook but is complementary alongside it. Please refer to
the textbook for a thorough breakdown and teaching of a topic.
Table of Contents
By Module By Chapter
8 Number Systems 1 3
9 Logic Circuits 2 15
10 Spreadsheets 1 29
11 Networking 2 16
Anki Flashcards are available!
(alongside these notes)
https://github.com/markjoshwel/compcards
Module 1 – Data and Information
Module 1 Data Management Example:
Data and Information Excel Types and Functions Overview 102 (100) 101 (10) 100 (1)
This module is about the handling and processing of data in See the “Additional Materials” Unit at the back of
computer systems, and the need to be ethical when dealing these notes for the cheat sheet! 4 2 0
with data. Students should be able to identify di erent
types of data, understand and explain what the data is for, 400 20 0
and explain how the data is represented or organised for Data Representation
processing and output with reference to a given problem. 420
Students will be more aware of ethical issues with respect Definitions
to data, including the privacy of data. 1. Denary Number System
Used for:
Number system that is made up of 10 unique digits
1. IPv4 Addresses
2. Binary Number System 2. ASCII Codes
Number system that is made up of 2 unique digits
4
Module 1 – Data and Information
5
Module 1 – Data and Information
27. Intellectual Property 36. Proprietary Software 44. Virus
Creations of the mind that have value but can exist Commercial software for which most of the legal A computer program that attaches itself to a
purely as data with no physical form protections under copyright are retained normally harmless program and modifies it. When
the modified program is run by a user, the virus
28. Copyright Infringement 37. Shareware attaches copies of itself to any other programs it
Use or distribution of copyrighted work without the Demonstration software that is distributed for free can find, thus “infecting” them
permission of the copyright owner but for a specific evaluation period only
45. Worm
29. Plagiarism 38. Crack A computer program that runs automatically and
Passing o someone else’s original work as one’s Program that modifies proprietary software so that attempts to spread by sending copies of itself to
own the software cannot detect that it is being used other computers. Unlike a virus, a worm does not
illegally need to attach itself to an existing program
30. Licence
O cial description of activities that are authorised 39. Cookie Further information about aforementioned privacy
or forbidden by the owner of intellectual property A small file used by websites to store personal and security threats are listed in the “Types of and
information on a user’s web browser Measures Against Privacy and Security Threats”
31. Software piracy sub-unit of this unit.
Crime of copying, distributing and/or using 40. Pharming
proprietary software in a manner that is not The interception of requests sent from a computer Unauthorised Access
permitted by its licence to a legitimate website and redirection to a fake Situation where data owned by someone is used by
website to steal personal data or credit card someone else, such as an intruder, without
32. Free and Open-Source Software (FOSS) details permission
Software where users are given freedom to change,
copy, study and share the software and its source 41. Phishing Can occur due to:
code The use of emails and fake websites that appear to
be from reputable companies in order to steal 1. Poor authentication
33. Public Domain Software personal information such as passwords and credit 2. Poor access control or authorisation
Software where the legal protections that are card numbers from users 3. Poor understanding of privacy policies
typically granted to intellectual property have
either expired, been surrendered or are simply 42. Spyware May result in:
inapplicable A hidden program that secretly collects personal - Stolen passwords or bank account
information about its users and transmits this information used to steal money and commit
34. Freeware information to attackers without the users’ fraud
Proprietary software that is available for use at no knowledge - Intruders publicising private information
cost leading to unwanted attention or bullying
43. Trojan horse
35. Open Courseware A computer program that pretends to be a
Higher-education course materials such as videos harmless file or useful application
and notes created by universities and distributed
for free on the Internet
6
Module 1 – Data and Information
7
Module 1 – Data and Information
9
Module 1 – Data and Information
- Most email services have a filter feature that social networking sites to promote content the classroom. The open sharing of
allows users to block specific senders or to that the reader is likely to be interested in information on the Internet has made
only allow emails from specific senders since most sites promote content based on education accessible to all, even learners
through. how much they can elicit responses and not from disadvantaged backgrounds. AI has also
by their level of accuracy. made it possible to provide personalised
learning and testing for thousands of
Manage Cookies
Economic Impact students without the need for excessive
manual e ort.
- Delete cookies - The rise of smartphones has led to an
- Prevent cookies from being created by increased focus on mobile devices and mobile - On the negative side, technology has made it
untrusted websites applications in the computing industry. more challenging for educators as students’
- Disable cookies attention spans are getting shorter due to the
- Allow only selected websites to use cookies - The rise of social media has led to the technology and social media that they are
increased use of social media for marketing used to today.
Ethical, Social and Economical Issues purposes and has helped businesses to better
understand buying habits and consumer Economic Impact
- Communication needs by analysing social media posts.
- Education - The rise of open courseware has led to a
- Finance - Improvements in communications technology large number of for-profit and non-profit
- Healthcare have also reduced business costs through the organisations that o er customised lessons
- Transportation use of cheap and e ective video conferencing on a variety of topics for self-study online.
- Entertainment calls in place of face-to-face meetings.
- Many educational institutions have also
Ethical Issues invested heavily in the materials and
Communication
infrastructure needed to conduct lessons
- Should some kinds of false information on over the Internet.
Social Impact the Internet be blocked or would this be
taking censorship too far? - Some traditional educators find that they
- On the positive side, the Internet has enabled need to retrain and pick up new skills to
diverse cultures to interact and share ideas - Is it right to collect and analyse social media better utilise these new technologies for
with each other. Social networking sites have posts in ways that the original authors may education.
also allowed users to remain connected with not have intended?
friends, family and colleagues even over long Ethical Issues
distances. AI has also made it possible for
Education
anyone to automatically transcribe and - Should students be allowed to use mobile
translate speech into di erent languages with phones in school?
remarkable speed and accuracy. Social Impact
- Can education technology ever be more
- On the negative side, some people use the - On the positive side, technology has provided e ective than a good teacher?
Internet to reinforce their existing opinions or better videos, simulations and collaboration
to spread rumours and misinformation. This is tools for lessons to be more engaging and
worsened by the use of AI by some news and relevant to students, both inside and outside
10
Module 1 – Data and Information
microseconds. This has led to the rise of healthcare impersonal and mistrust the
Finance
algorithmic trading, which is the study and ability of machines to provide proper
refinement of algorithms to make trading healthcare. Other patients may misuse
Social Impact decisions at speeds not possible by a normal information from the Internet and make
human being. potentially dangerous decisions based on
- On the positive side, the rise of financial incorrect diagnoses. Patients may also be
technology has enabled consumers to spend, - Many banks also use AI to analyse transaction uncomfortable with the collection of medical
borrow, invest and save money through data and automatically identify unusual data necessary to improve the performance
low-cost and easy-to-use mobile and web spending patterns or money transfers. This of healthcare-related AI.
applications. There is no longer a need to helps them to automatically detect and
perform such transactions in person. prevent instances of financial fraud without Economic Impact
Individuals have also become better-educated the need for manual intervention.
on how to make smart financial decisions - Technology has created new areas of growth
using information that is freely available on Ethical Issues in the healthcare industry, such as the
the Internet. In retail, many consumers also provision of telemedicine solutions to existing
enjoy the convenience of making payments - Should financial technology be limited to healthcare businesses. In particular, many of
via biometric authentication (e.g., face or protect more vulnerable users? these solutions provide a way for patients to
fingerprint recognition) which is only possible securely transfer potentially sensitive medical
with the use of AI. - Is it safe or acceptable to have financial information over the Internet.
markets controlled by secret algorithms
- On the negative side, threats to the privacy instead of humans? - There is also an increased focus on
and security of data as well as the ease of automating healthcare processes through the
obtaining false information on the Internet use of robots to dispense medicine and other
Healthcare
have made some people more vulnerable to more menial tasks. This may in turn cause
financial scams and other get-rich-quick such jobs to disappear from the job market.
schemes. Social Impact
- The rise of 3D-printing technology has also
Economic Impact - On the positive side, technology has enabled opened up new opportunities in the building
telemedicine, which is the use of video and customisation of prosthetic limbs,
- Financial technology is currently an area of conferencing and other technology, for hearing aids and dental fixtures.
growth in the financial industry. Numerous doctors to provide medical consultations and
companies have started to make financial diagnoses over the Internet or applications on Ethical Issues
services more e cient for both individuals mobile devices. This gives patients who are
and businesses. These companies typically located in remote places or have limited - Is it acceptable for robots to replace humans
use technology and software to reduce the mobility better access to healthcare. By in providing certain kinds of healthcare?
time, cost and e ort needed for payments, analysing medical data, AI can automatically
investments, fundraising, trading, and/or data identify warning signs of possible health - Is it acceptable to transfer private medical
analytics for both businesses and individuals. problems and provide doctors with more information over the Internet?
accurate diagnoses.
- With the evolution of technology, the time
needed to perform a financial trade has - On the negative side, some patients find the
decreased from seconds down to mere use of robots and other technology in
11
Module 1 – Data and Information
- Multiple new companies o er on-demand concern that such technology is causing
Transportation
rides via mobile applications. These people to become deficient in real-life social
developments have led to sweeping changes skills or abandon their responsibilities. AI has
Social Impact in the taxi service industry as well as also made it possible for anyone to create
employment opportunities for taxi drivers. doctored images and videos that appear
- On the positive side, transport has become remarkably convincing to the average viewer.
less stressful and more predictable for - Mapping technology is also another area of While such images and videos have been used
travellers due to the availability of detailed growth with an increased focus on making 3D mostly for entertainment, they can also be
maps as well as real-time information on bus maps and geospatial data more accessible used to cause public alarm or spread
frequencies, tra c congestion levels and damaging falsehoods.
and useful to travellers.
street-level photographs of neighbourhoods
around the world. All this information is also Economic Impact
Ethical Issues
available at a low cost through popular
mobile devices. Location data from such - Games, animation and media are areas of
- Is it acceptable for mapping companies to
mobile devices may also be collected by AI to strong growth in the entertainment industry
drive through neighbourhoods and take
improve the accuracy and relevance of any with new opportunities being opened up by
pictures to put them online?
map or tra c data that is displayed. the rise of high-quality virtual reality,
augmented reality and motion-tracking
- Is the sharing of personal transport
- On the negative side, some people are technology.
preferences worth the conveniences o ered
uncomfortable with how pictures and by AI?
information about themselves or their home - Many businesses are also using monitoring
may be used by mapping companies without technology and strategies from game design
their permission in order to build more Entertainment to provide rewards and incentives for
accurate maps for travellers. This is especially work-related achievements.
true with regards to the collection of location Social Impact
data from mobile devices as this data can Ethical Issues
reveal personal details such as home and - On the positive side, technology has enabled
work addresses that users may wish to keep more exciting and engaging forms of - Is it right for game companies to make money
private. entertainment. Many computer games have o addicted players?
active online communities and mobile games
Economic Impact have even managed to bring participants - Is it right for businesses to use technology to
together in the real world through in-game monitor employees more extensively?
- The rise of self-driving vehicles with the use incentives to meet or team up. AI has also
of AI to recognise and adapt to road made it possible to provide more accurate
recommendations for consumers based on
conditions is likely to open new areas of
collected data on their previous choices of
growth in the travel industry. Singapore is one
entertainment.
of the first countries where self-driving cars
are being tested, and if successful, the
- On the negative side, some people may be
technology will likely revolutionise the motor
addicted to computer games or social
industry. networking sites. There is an increasing
12
Module 2 – Systems and Communication
Module 2 Computer Architecture 9. Execute
Advantages Disadvantages
26. Input device 36. Logic Circuit Diagram
Hardware device that allows users to enter data Visual representation using symbols to show how Large storage capacity Easily damaged and will
and instructions into a computer the component logic gates are connected together of up to terabytes (TB) eventually break over
in a logic circuit of data time
27. Output device
Hardware device used to display, project or print
processed data from a computer
14
Module 2 – Systems and Communication
Large storage capacity Much more expensive Least portable, More portable Most portable
of up to terabytes (TB) than magnetic or optical due to spinning than magnetic, due to no Q = 1 If A OR B Q = 1 If A AND B
of data storage media components less portable moving parts
prone to than solid state A B Q
A B Q
mechanical storage media
Other Advantages and Disadvantages are seen in the
failure and due to 0 0 0 0 0 0
“Comparing Storage Mediums” Sub-unit of this Unit. damage scratches or
fingerprints 0 1 1 0 1 0
Comparing Storage Mediums
1 0 0 1 0 0
When deciding on the best type of storage media to
Durability
use, these factors should be considered: 1 1 1
1 1 1
Magnetic Optical Solid-state
- Capacity
- Speed Easily damaged Vulnerable to Not as NOT Gate NOR Gate
- Portability and will scratches and vulnerable to
- Durability eventually fingerprints drops,
- Cost break over mechanical
time shocks,
scratches or
Capacity fingerprints Q = 1 If NOT A Q = 1 if A NOR B
Q = 1 if NOT (A OR B)
Magnetic Optical Solid-state
Cost A Q A B Q
Large storage Large storage Large storage
capacity of up capacity of up capacity of up Magnetic Optical Solid-state 0 1 0 0 1
to terabytes to gigabytes to terabytes
(TB) of data (GB) of data (TB) of data Relatively More expensive Much more 0 1 0 1 0
cheaper than than magnetic, expensive than
optical and cheaper than magnetic or 1 0 1 0 0
solid-state solid-state optical storage
Speed storage media storage media media 1 0 1 1 0
15
Module 2 – Systems and Communication
4. Metropolitan Area Network (MAN) 13. Bandwidth
NAND Gate
Network of computing devices typically spanning The average number of bits of data that can be
across two or more buildings within the same transmitted from a source to a destination over
town or city the network in one second; is usually measured in
megabits per second (Mbps) or gigabits per second
5. Wide Area Network (WAN) (Gbps)
Q = 1 If A NAND B
Network of computing devices typically covering a
Q = 1 If NOT (A AND B)
large-scale geographical area, typically across 14. Port Number
multiple geographical locations Number that is used together with an IP address to
A B Q
uniquely identify a program that is running on a
0 0 1 6. Ethernet network
Most commonly used wired network protocol for
0 1 1 local and metropolitan area networks 15. Service Set Identifier (SSID)
A 32-byte string that identifies a wireless access
1 0 1 7. Network Protocol point (WAP) and all devices connected to it
Set of standards and rules that govern how two or
1 1 0
more devices communicate over a network 16. Packet (computing)
A unit of broken-up data containing a header with
Data Communications 8. Wired Network information about the source and destination
Network of devices connected by a physical addresses that are needed for transmission
Network Hardware, Organisation and medium, such as cables
Topologies 17. Network Interface Controller/Card (NIC)
9. Wireless Network A network interface controller/card (NIC) provides
Definitions Network of devices in which signals are the hardware interface to enable the transfer of
1. Computer Network transmitted without the use of a physical medium data between a device and a network. A NIC may
System of two or more computers that are connect to a network physically or wirelessly. Most
connected together by a transmission medium for 10. Client devices are equipped with a built-in NIC.
the exchange of data. Computer that initiates a connection to a server to
request for resources and services to perform 18. Hub/Network Hub
2. Transmission Medium operations Device that transmits received packets to all
Means of connecting two or more computers connected devices. Likewise, when a device
together, such as using copper cables, radio waves 11. Server responds, the response is sent to every device that
or light pulses, so that they may exchange data Computer that shares resources with and is connected to the hub.
and interact with each other responds to requests from devices and other
servers on the network
3. Local Area Network (LAN) 19. Switch/Network Switch
Network of computing devices connected within a 12. Wireless Access Point (WAP) Device that constructs a single network by
small geographical area, typically within the same Network hardware that provides a connection connecting multiple similar networks together. A
building, such as a home, school or o ce between wireless devices up to 100 metres away switch uses MAC addresses to keep track of the
and can connect to wired networks devices that are connected to it. This lets the
16
Module 2 – Systems and Communication
switch intelligently decide whether it should drop Advantages and Disadvantages of a - Maintenance Costs
or forward the packets that it receives. Computer Network There are also subsequent costs associated
Note: A switch that connects exactly two networks with administering and maintaining the
together is also called a network bridge. Advantages Disadvantages network.
- Initial Costs
Installing a network could be costly due to
the high setup and equipment costs.
17
Module 2 – Systems and Communication
3. Wide Area Network
Advantages Disadvantages client or server server
Examples: Country, The Internet
Properties: Client- - Centralised - Higher initial cost Hard- Each client is Each computer in
- Can be either private or public Server control of data and due to the need for ware connected to one the network can
- Can span long distances via resources a server Organi- or more dedicated serve as a client
long-range transmission media such sation servers and server at the
as telephone lines, fibre optic cables - Easy to schedule - Administrative same time
or satellite links. backups of all costs needed for
shared files at the maintenance of Band- Typically high but Varies depending
- Uses more expensive and high-speed
regular intervals server and clients width limited by the on how
technology than a LAN capability of the data needs to be
- Security may be server transmitted. The
Definitions for the networks are provided in the enhanced with the more computers
“Definitions” sub-unit of this Unit. use of specialised needed to handle
software or the request, the
Comparing Network Organisations operating system larger the
features that are bandwidth.
(Client-Server vs Peer-to-Peer) designed for
A client is a computer that initiates a connection to servers
Secu- High as access Low as security is
a server to request for resources and services to
Peer- - Cheaper to set - More e ort is rity rights can be handled by each
perform operations.
To- up as there is no required to access controlled centrally computer and not
Peer cost related to and back up at a server by a central server
A server is a computer that shares resources and dedicated servers resources as they
responds to requests from devices and other servers are stored locally
on the network. - Easy to set up as within each Setup High as the use of Low as basic
no specialised computer instead Cost specialised computers can act
Server-Provided Resources and Services: software or of centrally in a high-performance as servers to share
operating system server servers would resources
features are be needed
- Providing central storage of files
- Sharing hardware such as printers needed - Security is an
issue as access
- Controlling logins and network access Stor- Centralised and Decentralised and
rights are not
administered by a age carried out only at can be carried out
Client-Server Peer-to-Peer central server the server; usually by individual users
managed by a at each computer
network
administrator
Client-Server Peer-to-Peer
Func- Data and resources Data and resources Appli- Found in Found in homes or
tion are shared using are shared directly cation businesses or small businesses
one or more between organisations with where there are
dedicated servers; computers; each a large number of fewer users
each computer has computer acts as users
a distinct role: both a client and
18
Module 2 – Systems and Communication
- Easy and cheap to - A break anywhere - Can operate over - If a computer or cable - The load on each - Uses more cabling
install as it uses less along the bus may larger distances and in the network fails, the section of cabling is than other topologies
cabling than other disable the entire handle more data than a entire network may fail reduced as each and hence costs more
network designs network bus topology as the data cannot be computer uses a
passed on separate cable from the - If the central network
- Scalable as new - The size of the - Data packets that are rest hardware fails, the
computers can be easily network is limited by sent between two - Adding a new entire network fails
added the capacity and length computers will pass computer to the ring - If a fault occurs at a
of the bus through intermediate network would mean computer or cable, it is
- Can continue to computers, hence a that the whole easy to isolate the fault
operate even when one - A single bus is central server is not communication ring and do a replacement
of the computers breaks unsuitable for networks required to manage the needs to be temporarily without a ecting the
down with many computers; network interrupted rest of the network
performance slows
- Works well for small down as the number of
networks computers increases
20
Module 2 – Systems and Communication
Data can become lost or corrupted during - It is able to detect that an error has occurred
transmission. Data is seldom sent in a single stream but cannot determine where the error
but is instead broken up and sent in smaller packets. occurred.
This allows us to focus on detecting transmission
errors one packet at a time. - It is able to detect when an odd number of
bits have been corrupted but not an even
There are two basic error-checking methods to number of bits have been corrupted.
ensure that the data received at the destination is or
the same as that at the source: It is not able to detect bit transposition.
1. Parity check
Checksum
2. Checksum
A checksum is a calculated value that is used to
Parity Check determine the integrity of transmitted data. A
checksum serves as a unique identifier for the data
In parity check, an additional bit is either appended and is sent together with the data.
or prepended to a string of binary data for
transmission. 1. Before transmission, a checksum is
calculated.
This parity bit can be either 0 or 1, depending on
whether an odd or even parity system is used. Parity 2. The data and the checksum is sent together.
bits are the simplest method of error detection.
3. At the destination, the checksum is
In the odd parity system, the total number of 1 bits calculated and compared to the sent
in each packet (including the parity bit) should be checksum value.
odd.
4. If the checksums match, the data was
In the even parity system, the total number of 1 bits transmitted correctly. Else, an error has
in each packet (including the parity bit) should be occurred.
even.
Method to calculate a one byte checksum:
Odd Parity 010 1101 → 1010 1101
- If the sum of all bytes in the data is less than
Even Parity 010 1101 → 0010 1101 or equal to 255, the checksum is this value.
21
Module 3 – Abstraction and Algorithms
Module 3 Definitions 11. Trace table
2. Identifying patterns among two or more INPUT year FOR <variable> = <x> to <y>
solutions. INPUT age <code>
These patterns are clues that the solution can born = year - age NEXT <x>
be generalised to a single solution to solve OUTPUT born
multiple problems. Example
23
Module 3 – Abstraction and Algorithms
Terminator
Process
Decision
24
Module 4 – Programming
Module 4 Definitions 10. Concatenation
26
Module 4 – Programming
28
O-Level Computing Theory! – Additional Materials
Additional Materials
General Used for data with no specific type or data is not known ahead of time ABC
123
Currency Used for money, typically displayed with a currency symbol or two decimal places $420.00
Function Overview
Area Function Example
29
O-Level Computing Theory! – Additional Materials
30
O-Level Computing Theory! – Additional Materials
while <condition>:
<code>
31
O-Level Computing Theory! – Additional Materials
Returns string with all uppercase characters Removes element at index index from the list. Unused/unspecified values can be skipped, but
you must keep the colon!
s = "aaaaa!!" list = [1, 2, 3]
print(s.upper()) # ‘AAAAA!!’ list.pop(0) my_list[0:2] # ["someone", "in"]
print(list) # [2, 3] my_list[0:5:2] # ["someone", "early"]
.split(separator) my_list[::-1] # ["20s", "early", "in",
.count(element) "someone"]
Advanced – split a string using the separator.
separator defaults to an empty string, returning Counts total number of element in the list.
7. String Indexing and Slicing
a list of each character. If the separator
argument is given, the string will be split with the list = ["banana", "banana", "apple", "banana"]
given separator. list.count("banana") # 3 Indexing and slicing operations on strings are
identical to those on lists. A good way to visualise
s = "abcde" this is to see strings as a list of one-character
6. List Indexing and Slicing
s.split() # ["a", "b", "c", "d", "e"]
strings. (e.g. "hi" == ["h", "i"])
s.split("c") # ["ab", "de"]
Elements in a list start with the index 0, and
s = "Godot"
5. List Operators and Methods increase with each element in the list. Using print(s[0:3]) # ‘God’
negative numbers allows you to start counting print(s[0:3:2]) # `Gd`
backwards. print(s[::-1]) # ‘todoG’
in
my_list = [
Membership operator. Checks if an element is in "someone", # index 0 (-4) 8. Useful Built-in Functions
the list. "in", # index 1 (-3)
"early", # index 2 (-2) print(...)
my_list = [1, 2, 3] "20s", # index 3 (-1)
1 in my_list # True ]
Print variables and values out
4 in my_list # False
You can access an element in a list using its’
print("J’ai", 16, "age") # ‘J’ai 16 age’
.append(element) index.
input(...)
Appends element to the end of the list. print(my_list[0]) # ‘someone’
print(my_list[-1]) # ‘20s’
Prompt user for input
my_list = [1, 2, 3]
my_list.append(4) Accessing certain parts of a list is called “Slicing”.
song = input("What are you listening to? ")
print(my_list) # [1, 2, 3, 4] Three values can be used for slicing:
min(iterable)
- Start: Index to start the slice range
- Stop: Index after end of slice range. Finds and returns the smallest element in
Defaults to list length. iterable.
- Step: Get every nth element. Defaults to 1.
result = min([1, 200, 199]) # 1
32
O-Level Computing Theory! – Additional Materials
Finds and returns the biggest element in Round number to nearest ndigits (default 0; whole 0 potatoes
iterable. number) 1 milk
2 eggs
result = max([1, 200, 199]) # 200 print(round(0.96)) # 1
print(round(0.96, 1)) # 1.0 zip(
sum(iterable) iterable1,
abs(x) iterable2,
Returns sorted iterable. ...,
Return absolute value of number x strict=False
total = sum([7, 3, 8, 4]) # 22 )
print(abs(-9)) # 9
sorted(iterable) Advanced – Iterates through argued iterables and
ord(x) yields multiple values, one from each iterable.
Returns sorted iterable.
Returns ASCII/Unicode code point integer from In cases where the iterables are not of equal
sorted_list = sorted([7, 4, 5]) # [4, 5, 7] character x length, keyword argument strict should be set to
True, which will end when one of the iterables
len(iterable) print(ord("a")) # 97 reaches its’ end.
str_len = len("abcdef") # 6 Returns character as string from ASCII/Unicode stuff = ["potatoes", "milk", "eggs"]
list_len = len([1, 2, 3, 4]) # 4 code point integer i prices = [10.0, 6.0, 16.0]
for item, price in zip(stuff, prices):
range(...) print(chr(97)) # ‘a’ print(item, price)
Used in for loops. Just like slicing, start, stop and enumerate(iterable, start=0) Output:
step values can be used.
Advanced – Iterates through iterable, yielding 10.0 potatoes
for i in range(5): # start 6.0 milk
two values: index and value. Start index value can
print(i) # 0, 1, 2, 3, 4 16.0 eggs
be specified using start keyword argument.
for i in range(2, 5): # start, stop
print(i) # 2, 3, 4 Code:
for i in range(2, 5, 2): # start, stop, step stuff = ["potatoes", "milk", "eggs"]
print(i) # 2, 4 for i, v in enumerate(stuff):
print(i, v)
33
O-Level Computing Theory! – Additional Materials
9. random Module
import random
random.randint(start, stop)
import math
math.ceil(x)
math.floor(x)
math.pow(x, y)
math.sqrt(x)
math.trunc(x)
34