0% found this document useful (0 votes)
5 views11 pages

CS9618 Paper4 Python Reference

This document is a reference guide for A2 Computer Science 9618 Paper 4, focusing on Python programming. It covers built-in functions, string and list methods, file handling, exception handling, object-oriented programming keywords, and the random library. Each section includes syntax, descriptions, and examples for better understanding and application.

Uploaded by

zohibwhales43
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)
5 views11 pages

CS9618 Paper4 Python Reference

This document is a reference guide for A2 Computer Science 9618 Paper 4, focusing on Python programming. It covers built-in functions, string and list methods, file handling, exception handling, object-oriented programming keywords, and the random library. Each section includes syntax, descriptions, and examples for better understanding and application.

Uploaded by

zohibwhales43
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

A2 Computer Science 9618 — Paper 4 Python Reference Page 1

Built-In Functions & Libraries


Reference Guide
A2 Computer Science 9618 — Paper 4 (Python)

1. Built-In Functions
2. String Methods
3. List (Array) Methods
4. File Handling Functions & Methods
5. Exception Handling Keywords
6. OOP Keywords & Built-Ins
7. The random Library

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 2

1. Built-In Functions
Available in Python without importing any module.

Function Syntax Description Example

print() print(value, ..., end='\n') Outputs text or values to the print("Hello")


console

input() input(prompt) Reads a line from the user name = input("Enter


(always returns a string) name: ")

int() int(value) Converts a value to an integer int("10") → 10


(type casting)

float() float(value) Converts a value to a float float("10.5") → 10.5


(decimal)

str() str(value) Converts a value to a string str(25) → "25"

len() len(sequence) Returns number of items in a len([1,2,3]) → 3


list, string, or sequence

range() range(start, stop, step) Generates a sequence of numbers range(5) → 0,1,2,3,4


used in loops

open() open(filename, mode) Opens a file and returns a file open("[Link]", 'r')
object

Notes on print()
print("Hello") # Basic output
print("Hello", "World") # Multiple values, separated by space
print(f"Sum is {x + y}") # f-string (formatted string literal)
print(x, end="--->")
print(x, end=",")

Notes on range()
range(5) # 0, 1, 2, 3, 4
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(10, 0, -1) # 10, 9, 8, ... 1

Notes on Type Casting


num = int("10") # String → Integer
num = float("10.67") # String → Float
text = str(25) # Integer → String
# Always needed when doing arithmetic on input() values
x = int(input("Enter: ")) # Read integer from user

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 3

2. String Methods
String methods are called on a string variable using dot notation: [Link]()

Method Syntax Description Example

strip() [Link](chars) Removes specified characters from "***Hi***".strip("*") →


both ends "Hi"

lstrip() [Link](chars) Removes characters from the left "***Hi***".lstrip("*") →


end only "Hi***"

rstrip() [Link](chars) Removes characters from the right "***Hi***".rstrip("*") →


end only "***Hi"

split() [Link](separator) Breaks a string into a list at "A,B,C".split(",") →


every separator ['A','B','C']

upper() [Link]() Converts all characters to "hello".upper() → "HELLO"


uppercase

lower() [Link]() Converts all characters to "HELLO".lower() → "hello"


lowercase

String Indexing & Slicing


Syntax: string[start : end : step]
text = "COMPUTER"
# Indexing
text[0] # 'C' (first character)
text[-1] # 'R' (last character)
# Slicing
text[0:3] # 'COM' (index 0,1,2 — end is excluded)
text[2:] # 'MPUTER' (from index 2 to end)
text[:4] # 'COMP' (from start to index 3)
text[::2] # 'CMUE' (every 2nd character)
text[::-1] # 'RETUPMOC' (reverse the string)
# Negative indexing
text[-4:] # 'UTER'
text[:-2] # 'COMPUT'
text[-3:-7:-1] # 'TUPM' (right to left using negative step)

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 4

3. List (Array) Methods


Lists are Python's implementation of arrays. Methods are called using dot notation.

Method Syntax Description Example

append() [Link](value) Adds an item to the end of the list [Link](5)


(used for dynamic arrays and trees)

pop() [Link](index) Removes and returns an item. Without [Link]() /


index, removes the last item [Link](2)

Creating Lists (Arrays)


# Static list
arr = [1, 2, 3, 4, 5]
# Empty list (dynamic)
arr = []
# List of zeros
arr = [0 for i in range(5)]
# 2D Array — list of lists
matrix = [[0 for cols in range(5)] for rows in range(3)]
# Accessing elements
arr[0] # First element
matrix[1][2] # Row 1, Column 2
# Iterating
for item in arr:
print(item)
for i in range(len(arr)):
print(arr[i])

append() and pop() — Stack & BST Use


# Used to simulate a Stack (LIFO)
stack = []
[Link](10) # Push
[Link]() # Pop (removes last item)
# Used in Binary Tree to add a new node
Binary_Tree.append([None, Data, None])

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 5

4. File Handling Functions & Methods

open() — File Modes


Mode Description

'r' Read — opens an existing file for reading (default)

'w' Write — creates a new file or overwrites existing file

'a' Append — adds data to the end of an existing file

'x' Create — creates a new file; raises error if file already exists

File Methods
Method Description Example

read() Reads the entire file as a single string [Link]()

readline() Reads one line at a time [Link]()

readlines() Reads all lines and returns them as a list [Link]()

write(text) Writes a string to the file [Link]("Hello\n")

close() Closes the file (important to free resources) [Link]()

Usage Examples
# Writing to a file
file = open("[Link]", 'w')
[Link]("Ahmed\n")
[Link]("Haroon\n")
[Link]()
# Reading the entire file
file = open("[Link]", 'r')
print([Link]())
[Link]()
# Reading line by line
file = open("[Link]", 'r')
print([Link]()) # reads first line
print([Link]()) # reads second line
[Link]()
# Reading all lines as a list
file = open("[Link]", 'r')
lines = [Link]() # returns ['Ahmed\n', 'Haroon\n', ...]
[Link]()
# Iterating over lines (when count is unknown)
file = open("[Link]", 'r')
for line in file:
print(line)
[Link]()
# Appending data (does NOT overwrite)

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 6

file = open("[Link]", 'a')


[Link]("Zohib\n")
[Link]()
# Recommended: with open (auto-closes the file)
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# File is automatically closed after the block

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 7

5. Exception Handling Keywords


Keyword Purpose

try Wraps the code that may raise an exception (Plan A)

except Handles a specific exception if it occurs (Plan B)

else Executes only if no exception was raised in the try block

finally Always executes, whether an exception occurred or not (cleanup)

raise Manually raises an exception

Common Exception Types


Exception When it occurs

ValueError Wrong data type given (e.g. int("hello"))

ZeroDivisionError Division by zero (e.g. 10 / 0)

FileNotFoundError File does not exist when opened with 'r'

IndexError Accessing an index that is out of range

Usage Examples
# Handling a single exception
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid integer.")
# Handling multiple exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
# Using else (runs only when no exception)
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered: {num}")
# Using finally (always runs — good for closing files)
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 8

finally:
[Link]()
print("File closed.")
# Using raise (manually trigger an exception)
num = int(input("Enter a number between 1 and 10: "))
if num < 1 or num > 10:
raise Exception("Number out of range!")

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 9

6. OOP Keywords & Built-Ins


Keyword / Built-In Purpose

class Defines a new class (blueprint for objects)

def __init__(self, …) Constructor — automatically called when an object is created

self Refers to the current instance of the class

super().__init__(…) Calls the parent class constructor (used in inheritance)

__doc__ Accesses the docstring of a function or class

global Declares that a variable inside a function refers to a global


variable

OOP Concepts — Full Example


# Defining a class
class Student:
def __init__(self, name, roll_no):
[Link] = name # public attribute
self.__marks = 0 # private attribute (encapsulation)
def get_marks(self): # getter
return self.__marks
def set_marks(self, m): # setter (with validation)
if m >= 0:
self.__marks = m
def display_info(self):
print(f"Name: {[Link]}")
# Creating an object
s1 = Student("Ali", "CS-101")
s1.display_info()
s1.set_marks(85)
print(s1.get_marks())
# Inheritance
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
class Student(Person): # Student inherits from Person
def __init__(self, name, age, roll_no):
super().__init__(name, age) # call parent constructor
self.roll_no = roll_no
# Docstring access
def square(x):
"""Returns the square of a number"""
return x ** 2
print(square.__doc__) # Returns the square of a number

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 10

7. The random Library


Must be imported before use: import random

Function Syntax Description Example

randint() [Link](a, b) Returns a random integer between a [Link](0, 12)


and b (both inclusive)

choice() [Link](sequence) Returns a random item from a list or [Link](["apple


sequence ","banana"])

random() [Link]() Returns a random float between 0.0 [Link]()


and 1.0

shuffle() [Link](list) Shuffles the list in place (modifies [Link](number


the original list) s)

Usage Example
import random
# Random integer (0 to 12 inclusive)
num = [Link](0, 12)
print(num)
# Random element from a list
fruits = ["apple", "banana", "mango", "orange"]
print([Link](fruits))
# Random float between 0 and 1
print([Link]())
# Shuffle a list in place
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)
# Generating a random array using list comprehension
my_arr = [[Link](1, 100) for _ in range(10)]

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618


A2 Computer Science 9618 — Paper 4 Python Reference Page 11

Quick Reference Summary


print() · input() · int() · float() · str() · len() ·
All Built-In Functions range() · open()

strip() · lstrip() · rstrip() · split() · upper() ·


All String Methods lower()

All List Methods append() · pop()

All File Methods read() · readline() · readlines() · write() · close()

ValueError · ZeroDivisionError · FileNotFoundError ·


All Exception Types IndexError

Libraries Used random → randint() · choice() · random() · shuffle()

Reference compiled from A2 Paper 4 Python lecture files — CIE 9618

You might also like