Cambridge Court High School
Chapter: Revision of basic python
Notes
Feature of python / Reasons of python popularity:
Python is a versatile programming language known for its simplicity, readability, and flexibility. Here are some
of its key features:
1. Simple and Easy to Learn: Python has a simple and straightforward syntax, making it easy for
beginners to learn and understand.
2. Expressive Language: Python allows developers to write clear and concise code, enhancing readability
and reducing the cost of program maintenance.
3. Interpreted and Interactive: Python is an interpreted language, meaning code execution occurs line by
line. It also supports interactive mode, allowing programmers to experiment with code snippets and
execute them instantly.
4. High-Level Language: Python is a high-level language, which means it abstracts low-level details like
memory management and provides constructs that are closer to human language, making it easier to
write code.
5. Dynamic Typing: Python uses dynamic typing, allowing variables to be assigned without specifying
their type explicitly. Variable types are inferred at runtime, making code writing faster and more
flexible.
6. Strongly Typed: Despite dynamic typing, Python is strongly typed, meaning it performs type checking
at runtime, ensuring type safety and preventing certain types of errors.
7. Object-Oriented: Python supports object-oriented programming (OOP) concepts such as classes,
objects, inheritance, and polymorphism, facilitating modular and reusable code.
8. Extensive Standard Library: Python comes with a vast standard library that provides numerous
modules and packages for various tasks, ranging from file I/O to web development, making
development faster and more efficient.
9. Third-Party Libraries: Python has a rich ecosystem of third-party libraries and frameworks, such as
NumPy, pandas, Django, Flask, TensorFlow, and PyTorch, which extend its capabilities for specific
domains like data science, web development, machine learning, and more.
10. Cross-Platform: Python is platform-independent, meaning it can run on various operating systems like
Windows, macOS, and Linux without requiring any modifications to the code.
11. Community Support: Python has a large and active community of developers who contribute to its
growth and development. This community provides extensive documentation, tutorials, forums, and
resources, making it easier for programmers to learn and troubleshoot issues.
Python Tokens:
In Python, a token is the smallest unit of a program, which is meaningful to the Python interpreter. Tokens are
the building blocks of a Python program and include identifiers, keywords, literals, operators, and punctuation
symbols. Here's a breakdown of different types of Python tokens:
1. Identifiers: Identifiers are names given to entities like variables, functions, classes, etc. They consist of
a sequence of letters (both uppercase and lowercase), digits, and underscores, but must start with a letter
or an underscore. Example: variable_name, function_name, Class_Name.
2. Keywords: Keywords are reserved words that have special meanings and purposes in Python. These
words cannot be used as identifiers. Examples: if, else, for, while, def, class, import, return, etc.
3. Literals:
o Numeric Literals: These are numerical values represented directly in the code. Examples: 42,
3.14, 1000, 0b1101 (binary), 0o755 (octal), 0xFF (hexadecimal).
o String Literals: These are sequences of characters enclosed within single, double, or triple
quotes. Examples: 'hello', "world", '''multiline string''', """another multiline string""".
o Boolean Literals: These are the two constant values True and False.
4. Operators: Operators are symbols that perform operations on operands. Python supports various types
of operators:
o Arithmetic Operators: +, -, *, /, // (floor division), % (modulo), ** (exponentiation).
o Comparison Operators: ==, !=, <, >, <=, >=.
o Assignment Operators: =, +=, -=, *=, /=, //=, %= etc.
o Logical Operators: and, or, not.
o Bitwise Operators: &, |, ^, ~, <<, >>.
o Membership Operators: in, not in.
o Identity Operators: is, is not.
5. Punctuation Symbols: These include various symbols used for syntax and structure in Python code.
Examples: (), [], {}, :, ,, ;, ., @, ..., etc.
6. Comments: Comments are used for documentation and explanation purposes and are ignored by the
Python interpreter. They start with the # symbol and continue until the end of the line.
These tokens collectively form a Python program, and understanding them is crucial for writing and interpreting
Python code correctly.
Rules to create a valid variable/Identifier:
1. Starts with a Letter or Underscore
2. Can Contain Letters, Digits, and Underscores
3. Case-Sensitive
4. Cannot be a Keyword
5. Cannot Contain Spaces or Special Characters
6. Length(There is no limit on the length of an identifier, but it's recommended to keep them reasonably
short and meaningful for readability.)
7. Cannot Begin with a Digit
Conditional Statements:
In simpler terms, a conditional statement provides a way to make decisions in a program. It evaluates a condition
or expression and performs actions based on whether the condition is true or false.
Conditional statements are crucial for controlling the flow of execution in a program, allowing it to respond
dynamically to different situations. They enable the program to choose between alternative courses of action
based on the state of the program's variables, user input, or other factors.
In most programming languages, including Python, conditional statements typically involve keywords like if,
elif (else if), and else. These keywords are used to define the conditions and the corresponding actions to be
taken based on those conditions.
The differences between if-else, if-if-else, and if-elif-else conditional constructs lie in how they
handle multiple conditions and the order in which those conditions are evaluated. Here's a breakdown of each:
1. if-else:
o In a simple if-else construct, there are only two possible outcomes: the condition being true or
false.
o If the condition specified in the if statement evaluates to true, the code block under the if
statement is executed. Otherwise, the code block under the else statement is executed.
o This construct is suitable for scenarios where there are only two mutually exclusive possibilities.
Example:
x = 10
if x > 0:
print("x is positive")
else:
print("x is non-positive")
2. if-if-else:
o In an if-if-else construct, multiple if statements are used to test different conditions
sequentially.
o Each if statement is independent of the others, meaning that even if one condition is true, the
subsequent if statements will still be evaluated.
o If none of the conditions are true, the code block under the else statement is executed.
Example:
x = 10
if x > 0:
print("x is positive")
if x % 2 == 0:
print("x is even")
else:
print("x is neither positive nor even")
3. if-elif-else:
o In an if-elif-else construct, elif (short for "else if") statements are used to test multiple
conditions sequentially.
o Each elif statement is evaluated only if the previous conditions are false. If any of the
conditions are true, the corresponding code block is executed, and the subsequent elif and else
statements are skipped.
o If none of the conditions are true, the code block under the else statement is executed.
Example:
x = 10
if x > 0:
print("x is positive")
elif x % 2 == 0:
print("x is even")
else:
print("x is neither positive nor even")
In summary:
• Use if-else when dealing with only two mutually exclusive possibilities.
• Use if-if-else when you want to independently test multiple conditions regardless of the outcomes of
previous conditions.
• Use if-elif-else when you want to test multiple conditions sequentially, with only one block of code
being executed based on the first true condition encountered.
Loops in Python:
In Python, loops are used to execute a block of code repeatedly until a certain condition is met. There are two
main types of loops in Python: for loops and while loops.
• for Loops:
o for loops are typically used when you know in advance how many times you want to execute a
block of code.
o They iterate over a sequence (such as a list, tuple, string, or range) and execute the block of code
for each element in the sequence.
Example:
for item in sequence:
# Code block to execute for each item in the sequence
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
❖ while Loops:
1. while loops are used when you want to execute a block of code repeatedly as long as a specified
condition is true.
2. They continue iterating until the condition becomes false.
while condition:
# Code block to execute as long as the condition is true
Example:
i=1
while i <= 5:
print(i)
i += 1
Both for and while loops can be combined with other control flow statements like break and continue to alter
their behavior within the loop.
Additionally, Python also supports nested loops, where one loop is placed inside another loop. This allows for
more complex iterations, such as iterating over nested lists or performing matrix operations.
Loops are essential for automating repetitive tasks, iterating over data structures, and implementing iterative
algorithms. They provide a powerful mechanism for controlling the flow of execution in Python programs.
List:
In Python, a list is a data structure that is used to store a collection of items. Lists are mutable, ordered, and can
contain elements of different data types. Here are some key concepts related to lists in Python:
1. Creation of Lists: Lists are created by enclosing comma-separated elements within square brackets [ ].
Elements can be of any data type, and they can be added, removed, or modified after the list is created.
Example:
my_list = [1, 2, 3, 4, 5]
2. Accessing Elements: Individual elements in a list can be accessed using indexing. Python uses zero-
based indexing, meaning the first element has an index of 0, the second element has an index of 1, and
so on. Negative indexing is also supported, where -1 refers to the last element, -2 refers to the second
last element, and so on.
Example:
• my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 50
• Slicing Lists: Python allows you to create sublists (slices) from a list using slice notation. Slice notation
specifies a range of indices to extract elements from the list.
Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
Iteration over list:
Iterating over a list in Python means accessing each element of the list one by one and performing some
operation on it. There are several ways to iterate over a list:
1. Using a for Loop: The most common method to iterate over a list is by using a for loop. In each
iteration of the loop, the loop variable takes on the value of each element in the list.
Example:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Output:
• 1
2
3
4
5
2. Using a While Loop with Indexing: You can also iterate over a list using a while loop along with
indexing. This approach allows more control over the iteration process.
Example:
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Output:
1
2
3
4
5
Function related list:
In Python, there are several built-in functions related to lists that allow you to perform various operations on
lists efficiently. Here are some of the most commonly used functions:
1. append():
o Adds an element to the end of the list.
Example:
• my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2. extend():
• Extends the list by appending elements from another iterable (such as another list).
Example:
• my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
3. insert():
• Inserts an element at the specified index.
Example:
• my_list = [1, 2, 3]
my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3]
4. remove():
• Removes the first occurrence of a specified value from the list.
Example:
• my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
5. pop():
• Removes and returns the element at the specified index. If no index is specified, removes and returns the
last element.
Example:
• my_list = [1, 2, 3]
popped_element = my_list.pop(1)
print(popped_element) # Output: 2
print(my_list) # Output: [1, 3]
6. index():
• Returns the index of the first occurrence of a specified value in the list.
Example:
my_list = [10, 20, 30, 20]
index = my_list.index(20)
print(index) # Output: 1
7. count():
• Returns the number of occurrences of a specified value in the list.
Example:
my_list = [1, 2, 3, 2, 2]
count = my_list.count(2)
print(count) # Output: 3
8. sort():
• Sorts the elements of the list in ascending order. (In-place operation)
Example:
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
9. reverse():
• Reverses the order of the elements in the list. (In-place operation)
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
10. len():
• Returns the number of elements in the list.
Example:
my_list = [1, 2, 3, 4]
length = len(my_list)
print(length) # Output: 4
These are just a few of the functions available for working with lists in Python. They provide powerful tools for
manipulating lists and are frequently used in Python programming.
Difference between append and extend function ()
Feature append() extend()
Adds multiple elements (from an iterable) to the
Purpose Adds a single element to the end of the list
end of the list
Syntax list.append(element) list.extend(iterable)
Input Accepts a single element Accepts an iterable (e.g., list, tuple, string)
Modification Modifies the list in-place Modifies the list in-place
Number of
Adds one element to the list Adds multiple elements to the list
Elements
python my_list = [1, 2, 3]
python my_list = [1, 2, 3]
Example my_list.extend([4, 5, 6])
my_list.append(4) print(my_list)
print(my_list)
Tuple:
In Python, a tuple is a data structure that is used to store an ordered collection of elements. Tuples are similar to
lists, but they are immutable, meaning that once a tuple is created, its elements cannot be changed, added, or
removed. Here are some key concepts related to tuples in Python:
1. Creation of Tuples: Tuples are created by enclosing comma-separated elements within parentheses ().
Example:
my_tuple = (1, 2, 3, 4, 5)
Tuples can also be created without parentheses, using a comma-separated list of elements.
my_tuple = 1, 2, 3, 4, 5
An empty tuple can be created using empty parentheses.
Example:
• empty_tuple = ()
2. Accessing Elements: Individual elements in a tuple can be accessed using indexing, similar to lists.
Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 50
Tuple elements can also be accessed using slicing.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
3. Immutability: Tuples are immutable, meaning that once a tuple is created, its elements cannot be
changed, added, or removed. However, the tuple itself can be reassigned to a new value.
Example:
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # Error: 'tuple' object does not support item assignment
4. Tuple Functions/Methods: Tuples have a few built-in methods, such as count() and index(), which
can be used to perform operations on tuples.
Example:
my_tuple = (1, 2, 2, 3, 3, 3)
count = my_tuple.count(3)
print(count) # Output: 3
Tuples provide a lightweight and efficient way to store and access collections of data when immutability is
desired. While they lack some of the flexibility of lists, their immutability makes them suitable for certain use
cases where data integrity or performance is important.
String:
In Python, a string is a sequence of characters enclosed within either single quotes ' ' or double quotes " ".
Strings are immutable, meaning they cannot be changed after they are created. Here are some key concepts
related to strings in Python:
1. Creation of Strings: Strings can be created using either single quotes or double quotes.
Example:
my_string1 = 'Hello, world!'
my_string2 = "Python is awesome"
Triple quotes (''' ''' or """ """) can be used to create multiline strings.
Example:
multiline_string = '''This is a
multiline
string'''
2. Accessing Characters: Individual characters in a string can be accessed using indexing. Python uses
zero-based indexing, where the first character has an index of 0.
Example:
my_string = 'Hello, world!'
print(my_string[0]) # Output: 'H'
print(my_string[-1]) # Output: '!'
Strings can also be sliced to extract substrings.
Example:
my_string = 'Hello, world!'
print(my_string[1:5]) # Output: 'ello'
3. String Concatenation: Strings can be concatenated using the + operator.
Example:
string1 = 'Hello'
string2 = 'World'
concatenated_string = string1 + ' ' + string2
print(concatenated_string) # Output: 'Hello World'
4. Function related to String
In Python, there are several built-in functions and methods that are commonly used for working with strings.
These functions and methods provide various operations for string manipulation, formatting, searching, and
more. Here are some of the most commonly used ones:
1. len():
• Returns the length of a string (number of characters).
Example:
my_string = "Hello, World!"
length = len(my_string)
print(length) # Output: 13
2. capitalize() and title():
• capitalize(): Converts the first character of the string to uppercase.
• title(): Converts the first character of each word in the string to uppercase.
Example:
my_string = "hello, world!"
capitalized_string = my_string.capitalize()
titled_string = my_string.title()
print(capitalized_string) # Output: "Hello, world!"
print(titled_string) # Output: "Hello, World!"
3. upper() and lower():
upper(): Converts all characters in the string to uppercase.
lower(): Converts all characters in the string to lowercase.
Example:
my_string = "Hello, World!"
uppercase_string = my_string.upper()
lowercase_string = my_string.lower()
print(uppercase_string) # Output: "HELLO, WORLD!"
print(lowercase_string) # Output: "hello, world!"
4. strip(), lstrip(), and rstrip():
• strip(): Removes leading and trailing whitespace characters from the string.
• lstrip(): Removes leading whitespace characters from the string.
• rstrip(): Removes trailing whitespace characters from the string.
Example:
my_string = " Hello, World! "
stripped_string = my_string.strip()
left_stripped_string = my_string.lstrip()
right_stripped_string = my_string.rstrip()
print(stripped_string) # Output: "Hello, World!"
print(left_stripped_string) # Output: "Hello, World! "
print(right_stripped_string) # Output: " Hello, World!"
5. split() and join():
• split(): Splits the string into a list of substrings based on a delimiter.
• join(): Concatenates the elements of a list into a single string, using the specified separator.
Example:
my_string = "apple,banana,orange"
split_list = my_string.split(",")
joined_string = "-".join(split_list)
print(split_list) # Output: ['apple', 'banana', 'orange']
print(joined_string) # Output: "apple-banana-orange"
6. find() and index():
• find(): Returns the index of the first occurrence of a substring in the string (or -1 if not found).
• index(): Returns the index of the first occurrence of a substring in the string (or raises a ValueError if
not found).
Example:
my_string = "hello, world!"
index = my_string.find("world")
print(index) # Output: 7
7. Partition() method in Python is a string method that divides a string into three parts based on the
occurrence of a specified separator. It returns a tuple containing the part before the separator, the separator
itself, and the part after the separator. If the separator is not found, it returns the original string followed
by two empty strings.
Here's the syntax of the partition() method:
string.partition(separator)
• string: The original string on which the partition() method is called.
• separator: The substring used to partition the string.
The method returns a tuple containing:
• The part of the string before the separator.
• The separator itself.
• The part of the string after the separator.
Here's an example of using the partition() method:
my_string = "apple,banana,orange"
partitioned_result = my_string.partition(",")
print(partitioned_result)
Output:
arduino
('apple', ',', 'banana,orange')
Difference between split and partition function
Feature split() partition()
Partitions a string into three parts based on a
Purpose Splits a string into a list of substrings
separator
Syntax string.split(separator) string.partition(separator)
Return Value Returns a list of substrings Returns a tuple containing three parts of the string
Divides the string at the first occurrence of the
Separator Can specify any separator
separator
Splits the string at every occurrence of the Divides the string at the first occurrence of the
Behavior
separator separator
Default Uses whitespace characters if no separator
N/A (always requires a separator)
Separator is specified
Feature split() partition()
Number of Always returns three parts: part before separator,
Number of parts in the result list is not fixed
Parts separator itself, part after separator
Modification
Original string remains unchanged Original string remains unchanged
of Input
python my_string = python my_string = "apple,banana,orange"
"apple,banana,orange" split_result partitioned_result =
Example = my_string.split(",") my_string.partition(",")
print(split_result) print(partitioned_result)
Dictionary:
In Python, a dictionary is a built-in data type used to store collections of data in the form of key-value pairs.
Dictionaries are unordered, mutable, and can contain elements of any data type. Here's a detailed explanation of
dictionaries in Python:
Creation of Dictionaries: Dictionaries are created using curly braces {} and key-value pairs separated by
colons: Each key-value pair represents an entry in the dictionary.
Example:
my_dict = {"name": "John", "age": 30, "city": "New York"}
Dictionaries can also be created using the dict() constructor by passing key-value pairs as arguments.
Example:
my_dict = dict(name="John", age=30, city="New York")
Accessing Elements: Individual elements in a dictionary can be accessed using square brackets [] with the key.
Example:
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict["name"]) # Output: John
If the key does not exist in the dictionary, it raises a KeyError exception. To avoid this, you can use the get()
method, which returns None or a default value if the key is not found.
Example:
print(my_dict.get("gender")) # Output: None
print(my_dict.get("gender", "Male")) # Output: Male (default value)
Functions related to dictionary
In Python, dictionaries are a powerful data structure that offers various built-in methods to perform operations
such as adding, removing, accessing keys and values, and more. Here are some of the most commonly used
functions and methods related to dictionaries:
1. dict():
o Constructor function used to create a new dictionary.
Example:
my_dict = dict()
2. len():
• Returns the number of items (key-value pairs) in the dictionary.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
length = len(my_dict)
3. keys():
• Returns a view object that displays a list of all the keys in the dictionary.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
keys = my_dict.keys()
4. values():
• Returns a view object that displays a list of all the values in the dictionary.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
values = my_dict.values()
5. items():
• Returns a view object that displays a list of tuples, each tuple containing a key-value pair.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
items = my_dict.items()
6. get():
• Returns the value associated with the specified key. If the key is not found, it returns a default
value (or None if not specified).
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
value = my_dict.get("b")
7. pop():
• Removes and returns the value associated with the specified key.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
value = my_dict.pop("b")
8. popitem():
• Removes and returns the last inserted key-value pair as a tuple.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
key_value_pair = my_dict.popitem()
9. update():
• Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-
value pairs.
Example:
my_dict1 = {"a": 1, "b": 2}
my_dict2 = {"c": 3, "d": 4}
my_dict1.update(my_dict2)
10. clear():
• Removes all items from the dictionary.
Example:
my_dict = {"a": 1, "b": 2, "c": 3}
my_dict.clear()
These are just a few examples of the many functions and methods available for working with dictionaries in
Python. They provide powerful tools for manipulating dictionary data and are frequently used in Python
programming.