0% found this document useful (0 votes)
6 views14 pages

ICAP Python Book

Chapter 9 of the document covers Python fundamentals, including variables, operators, data types, and composite data types such as lists, tuples, dictionaries, and sets. It explains variable naming rules, various types of operators (arithmetic, assignment, comparison, logical, membership, and identity), and provides examples of individual and composite data types. The chapter emphasizes the characteristics and operations of these data types, essential for effective programming in Python.

Uploaded by

mahmed900ahmed
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)
6 views14 pages

ICAP Python Book

Chapter 9 of the document covers Python fundamentals, including variables, operators, data types, and composite data types such as lists, tuples, dictionaries, and sets. It explains variable naming rules, various types of operators (arithmetic, assignment, comparison, logical, membership, and identity), and provides examples of individual and composite data types. The chapter emphasizes the characteristics and operations of these data types, essential for effective programming in Python.

Uploaded by

mahmed900ahmed
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

CHAPTER 1: ACCOUNTING BASICS PRC 1: FUNDAMENTALS OF ACCOUNTING

CHAPTER 9

PYTHON FUNDAMENTALS

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 147


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

9.1 Variables
A variable in Python is a symbolic name that refers to a value. Think of it as a container that stores data you can
use and manipulate later in your programme.
name = "Ali"
age = 25

Variable Naming Rules


• Must begin with a letter (A–Z or a–z) or an underscore (_)
• Cannot start with a digit
• Can include numbers, letters, and underscores
• Case-sensitive (age and Age are different)
• Avoid using reserved Python keywords (like for, if, class)

9.2 Python Operators


Operators in Python are special symbols or keywords used to perform operations on variables and values.
Python supports a rich set of operators which are broadly categorized into the following types:

9.2.1 Arithmetic Operators

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 10 - 4 6

* Multiplication 6*7 42

/ Division 15 / 2 7.5

// Floor Division 15 // 2 7

% Modulus 15 % 2 1

** Exponentiation 2 ** 3 8

9.2.2 Assignment Operators

Operator Description Example Equivalent To

= Assign x=5 -

+= Add and assign x += 3 x=x+3

-= Subtract and assign x -= 2 x=x-2

*= Multiply and assign x *= 4 x=x*4

/= Divide and assign x /= 5 x=x/5

%= Modulus and assign x %= 2 x=x%2

148 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

9.2.3 Comparison Operators

Operator Description Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 7>4 True

< Less than 4<3 False

>= Greater or equal 6 >= 6 True

<= Less or equal 2 <= 1 False

9.2.4 Logical Operators

Operator Description Example Result

and Logical AND x > 5 and x < 10 True if both conditions are true

or Logical OR x < 5 or x == 10 True if at least one condition is true

not Logical NOT not(x > 5) True if the condition is false

9.2.5 Membership Operators

Operator Description Example Result

in Value is present 'a' in 'apple' True

not in Value not present 'x' not in 'apple' True

9.2.6 Identity Operators

Operator Description Example Result

is Same object x is y True if x and y refer to the same object

is not Different object x is not y True if x and y refer to different objects

9.3 Individual Data Types


Python provides a wide range of built-in data types to represent different kinds of values. These data types are
fundamental to programming and are used to store, manipulate, and process information in your code.
Understanding how they work is essential to writing effective Python programmes.
Individual (primitive or atomic) data types, include Integers, float, strings, booleans.

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 149


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

9.3.1. Integers (int)


Used to represent whole numbers.
a=5
b = -12

9.3.2. Floating-Point Numbers (float)


Used to store decimal numbers.
pi = 3.14159
weight = -70.5

9.3.3. Strings (str)


Used to store text, enclosed in single or double quotes.
message = "Welcome to Python"
You can concatenate strings using +:
greeting = "Hello, " + "Faizan!"

9.3.4. Booleans (bool)


Can only be True or False. Often used in comparisons and conditionals.
is_admin = True
is_authenticated = False

9.3.5 Type Conversion (Type Casting)


You can convert one data type into another using built-in functions.
age = "25"
age_int = int(age) # Converts string to integer
price = float("19.99") # Converts string to float

9.4 Composite Data Types


While individual data types like int, float, str, and bool store single values, composite data types allow you to
group and manage multiple values in a single variable. These are especially useful when you’re working with
collections of items—such as lists of names, pairs of coordinates, or mappings between keys and values.
Python offers four primary composite data types i.e. Lists, Tuples, Dictionaries and Sets.

9.4.1. Lists
A list in Python is a flexible, ordered collection of items that can store multiple values in a single variable. Lists
are mutable, meaning their contents can be changed after creation—you can add, remove, or modify elements.

150 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

Creating a List
Lists are created by placing items inside square brackets [], separated by commas:
fruits = ["apple", "banana", "mango"]
[Link]("grape")
print(fruits[0]) # Outputs: apple
Each element in a list is assigned an index, starting from 0. You can access items using these indexes:
print(fruits[0]) # Output: apple

Key Characteristics of Lists


• Ordered: Elements maintain the order in which they were added.
• Mutable: Items can be modified after the list is created.
• Allows Duplicates: Lists can contain repeated values.
• Supports Heterogeneous Data: A list can contain different data types.
mixed_list = [1, "hello", 3.14, True]

Common List Operations


fruits = ["apple", "banana", "mango"]
• Adding an element to the list
[Link]("grape")
• Inserting at a specific index
[Link](1, "orange") # ['apple', 'orange', 'banana', 'mango', 'grape']
• Updating an element
fruits[2] = "kiwi" # Replace 'banana' with 'kiwi'
• Removing an element by value
[Link]("mango")
• Removing an element by index
del fruits[0] # Removes 'apple'
• Length of list
print(len(fruits))
• Checking for membership
print("grape" in fruits) # Output: True

List Slicing
Slicing allows you to extract a specific portion (or "sublist") from a list by specifying a range of indexes. The
general syntax for slicing is:
list[start:stop:step]
Where:
• start is the index where the slice begins (inclusive).

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 151


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

• stop is the index where the slice ends (exclusive).


• step is the interval between elements.
If start or stop are omitted, Python uses default values:
• Default start = 0
• Default stop = end of list
• Default step = 1
You can access portions of a list using slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[-2:]) # Output: [40, 50]

Useful List Methods

Method Description Example

.append(x) Adds item x to the end of the list [Link]("melon")

.insert(i, x) Inserts item x at index i [Link](2, "pear")

.remove(x) Removes the first occurrence of x [Link]("apple")

.pop(i) Removes and returns the item at index i [Link](1)

.index(x) Returns the index of the first occurrence of x [Link]("banana")

.count(x) Counts occurrences of x in the list [Link]("banana")

.sort() Sorts the list in ascending order [Link]()

.reverse() Reverses the list in place [Link]()

.clear() Removes all items from the list [Link]()

2. Tuples
A tuple in Python is an ordered collection of items, just like a list, but with one key difference: tuples are
immutable. Once a tuple is created, its contents cannot be changed—no adding, removing, or modifying of
elements is allowed.
Creating a Tuple
Tuples are defined using parentheses () instead of square brackets.
dimensions = (1920, 1080)
print(dimensions[1]) # Output: 1080

152 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

You can also create a tuple without parentheses (using commas alone), though it's recommended to use
parentheses for clarity:
coordinates = 34.05, -118.25
To create a tuple with just one item, include a trailing comma:
single_item = (5,) # This is a tuple
not_a_tuple = (5) # This is just an integer

Key Characteristics of Tuples


• Ordered: Items maintain their original order.
• Immutable: Items cannot be added, removed, or altered.
• Allows duplicates: Tuples can contain repeated values.
• Heterogeneous: Can store different data types in one tuple.
info = ("Ali", 30, True)

Accessing Tuple Elements


Just like lists, tuple elements are accessed using indexing:
colors = ("red", "green", "blue")
print(colors[0]) # Output: red

You can also use slicing:


print(colors[1:]) # Output: ('green', 'blue')

Tuple Unpacking
Tuple unpacking allows you to assign each element of a tuple to a separate variable in one line:
person = ("Aqsa", 25, "Engineer")
name, age, profession = person
print(name) # Output: Aqsa

Why Use Tuples Instead of Lists?


• Immutability: Protects data from being changed accidentally.
• Performance: Slightly faster than lists due to their fixed size.
• Safe Keys: Can be used as keys in dictionaries (only if the tuple contains hashable items).

3. Dictionaries
A dictionary is a built-in Python data type used to store key-value pairs. Unlike lists or tuples, which store data
as ordered sequences, dictionaries use keys to access values. This makes dictionaries ideal for working with
structured or labeled data, such as student records, configuration settings, or product details.

Creating a Dictionary
Dictionaries are defined using curly braces {} with each key-value pair separated by a colon (:):
student = { "name": "Ali", "age": 22}
print(student["name"]) # Output: Ali

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 153


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

Key Features of Dictionaries


• Mutable: You can add, update, or remove key-value pairs after creation.
• Keys must be unique: Duplicate keys are not allowed.
• Keys must be immutable types: Such as strings, numbers, or tuples.

Accessing and Modifying Values


student["age"] = 23 # Update value
student["grade"] = "A" # Add a new key-value pair
print(student["grade"]) # Output: A
Accessing a key that doesn’t exist will raise a KeyError. Use .get() for safe access:
print([Link]("email", "Not available")) # Output: Not available

Common Dictionary Methods


info = {"name": "Aqsa", "city": "Lahore", "age": 28}
print([Link]()) # dict_keys(['name', 'city', 'age'])
print([Link]()) # dict_values(['Aqsa', 'Lahore', 28])
print([Link]()) # dict_items([('name', 'Aqsa'), ('city', 'Lahore'), ('age', 28)])

Deleting Items from a Dictionary


del info["city"] # Removes the key 'city'
[Link]("age") # Removes 'age' and returns its value
[Link]() # Removes all items

Formatted String Literals


f-strings (formatted string literals) allow you to embed dictionary values directly into strings for clean, readable
output.
 Example:
student = {"name": "Fatima", "score": 95}
print(f"{student['name']} scored {student['score']}%")

Output:
Fatima scored 95%

Use Cases for Dictionaries


• Representing records (student, employee, product)
• Mapping values to keys (translations, configuration settings)
• Storing JSON-like structured data
• Fast lookup by custom identifiers

154 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

4. Sets
A set in Python is an unordered collection of unique elements. It is similar to a list or tuple but does not allow
duplicate values. Sets are especially useful when you want to eliminate repeated data or perform set-based
mathematical operations like union, intersection, and difference.
unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # Outputs: {1, 2, 3}

Creating a Set
Sets are defined using curly braces {} or by using the built-in set() function:
unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # Output: {1, 2, 3}
As shown above, duplicate 2 is automatically removed.
You can also create an empty set like this:
empty_set = set()
Note: Using {} creates an empty dictionary, not a set.

Key Characteristics of Sets


• Unordered: No indexing or ordering of elements
• Unindexed: Cannot access elements by position (e.g., my_set[0] will raise an error)
• Mutable: You can add or remove items, but elements themselves must be immutable (e.g., numbers, strings,
tuples)
• No duplicates: Only unique values are stored

Common Set Operations

Adding and Removing Items


colors = {"red", "green"}
[Link]("blue") # Adds 'blue'
[Link]("green") # Removes 'green' (no error if not found)

Set Length and Membership


print(len(colors)) # Output: 2
print("blue" in colors) # Output: True

Mathematical Set Operations


A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print([Link](B)) # {1, 2, 3, 4, 5, 6}
print([Link](B)) # {3, 4}
print([Link](B)) # {1, 2}
print(A.symmetric_difference(B)) # {1, 2, 5, 6}

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 155


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

Useful Set Methods

Method Description Example


.add(x) Adds element x to the set (no duplicates) [Link](5)
.remove(x) Removes x; raises KeyError if missing [Link](3)
.discard(x) Removes x if present (no error if missing) [Link](4)
.pop() Removes & returns a random element x = [Link]()
.clear() Removes all elements from the set [Link]()
.copy() Returns a shallow copy of the set new_set = [Link]()

 Example Use Case


Suppose you have a list with duplicate entries and want only the unique values:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}

9.5 Loops
Loops are programming constructs that allow you to repeat a block of code multiple times until a certain
condition is met. They help automate repetitive tasks, making code more efficient and concise. Loops are used
to:
• Avoid writing the same code repeatedly.
• Process lists, strings, or other sequences easily.
• Control programme flow based on dynamic conditions.

Types of Loops in Python


1. for Loop
• Used for iterating over a sequence (lists, tuples, strings, ranges, etc.).
• Runs a fixed number of times (determined by the sequence length).
 Examples

a. Iterate through a list:


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

156 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

b. Using range()
for i in range(3): # 0, 1, 2
print(i)

Output:
0
1
2
While Loop
• Repeats as long as a condition is True.
• Useful when the number of iterations is unknown beforehand.
while Loop
 Example
count = 0
while count < 3:
print(count)
count += 1 # Increment to avoid infinite loop

Output:
0
1
2

Loop Control Statements


break
• Exits the loop immediately.
for i in range(5):
if i == 3:
break
print(i) # Output: 0, 1, 2
continue
• Skips the current iteration and continues to the next.
for i in range(5):
if i == 2:
continue
print(i) # Output: 0, 1, 3, 4

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 157


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

else with Loops


• Runs only if the loop completes without hitting a break.
for i in range(3):
print(i)
else:
print("Loop finished!") # Executes after normal completion

9.6 Functions
Functions in Python are self-contained blocks of reusable code designed to perform a specific task. They help
in organising code into logical segments, making programmes more modular, readable, and maintainable.
Instead of writing the same code repeatedly, you can define a function once and call it whenever needed, reducing
redundancy and improving efficiency.

Key Features of Functions


Reusability – Write once, use multiple times.
Modularity – Break complex problems into smaller, manageable parts.
Abstraction – Hide implementation details, exposing only what’s necessary.
Parameterization – Accept inputs (arguments) and return outputs.
Scope Control – Variables inside functions are local by default, preventing unintended side effects.

Types of Functions
Built-in Functions – Predefined in Python (e.g., print(), len()).
User-defined Functions – Created by developers (e.g., def greet():).
Lambda Functions – Small anonymous functions (e.g., lambda x: x * 2).

1. Defining & Calling Functions


def function_name(parameters):
"""Docstring (optional)"""
# Function body
return value # Optional
 Example
def greet(name):
print(f"Hello, {name}!")
greet("Ibrahim") # Output: Hello, Ibrahim!

2. Return Values
Functions can return results using return.
def square(x):
return x * x
result = square(5)
print(result) # Output: 25

158 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN


HANDS-ON COURSE ON AI & DATA ANALYTICS CHAPTER 9: PYTHON FUNDAMENTALS

Multiple Returns
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 2])
print(low, high) # Output: 1 4

3. Default Parameters
Set default values for parameters.
 Example
def greet(name="Guest"):
print(f"Hello, {name}")
greet() # Output: Hello, Guest
greet("Raahim") # Output: Hello, Raahim

4. Lambda (Anonymous) Functions


Lambda functions, also known as anonymous functions, are small, single-expression functions defined using
the lambda keyword. Unlike regular functions declared with def, lambdas are concise, inline, and typically
used for short, one-time operations where a full function definition would be unnecessary. They can take any
number of arguments but must evaluate and return exactly one expression.

Key Characteristics
• No Name: Lambdas are anonymous (unnamed) and often used where functions are required temporarily.
• Single Expression: Limited to one line of logic—no multiline statements or complex operations.
• Functional Programming: Commonly used with map(), filter(), sorted(), and other higher-order functions.
lambda arguments: expression
 Example
add = lambda a, b: a + b
print(add(2, 3)) # Output: 5
numbers = [1, 2, 3]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9]

5. *args and **kwargs


In Python, *args and **kwargs are special syntaxes used to pass a variable number of arguments to functions,
making them flexible and adaptable.
*args (Variable-length positional arguments)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3)) # Output: 6

THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN 159


CHAPTER 9: PYTHON FUNDAMENTALS HANDS-ON COURSE ON AI & DATA ANALYTICS

**kwargs (Variable-length keyword arguments)


def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Ibrahim", age=25))
# Output:
# name: Ibrahim
# age: 25

160 THE INSTITUTE OF CHARTERED ACCOUNTANTS OF PAKISTAN

You might also like