0% found this document useful (0 votes)
15 views52 pages

PDF Coding Contents

The document covers Python syntax rules, including indentation, comments, and line continuation, emphasizing their importance in the language. It explains variable declaration, naming conventions, dynamic typing, and primitive data types, along with type casting and conversion methods. Additionally, it discusses input/output functions and how to format and manipulate data in Python.

Uploaded by

Souvik Roy
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)
15 views52 pages

PDF Coding Contents

The document covers Python syntax rules, including indentation, comments, and line continuation, emphasizing their importance in the language. It explains variable declaration, naming conventions, dynamic typing, and primitive data types, along with type casting and conversion methods. Additionally, it discusses input/output functions and how to format and manipulate data in Python.

Uploaded by

Souvik Roy
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

Topic 1 - Syntax, Variables & Data Types,Type

Casting
Python Syntax Rules: Indentation,Comments, Line Continuation

Indentation -
In Python, indentation isn't just for readability, it's part of the language syntax. An incorrect
indentation will result in an IndentationError.

In [3]: # Incorrect indentation


if True:
print("Condition is wrong")

Cell In[3], line 3


print("Condition is wrong")
^
IndentationError: expected an indented block after 'if' statement on line 2

In [4]: # Correct indentation


if True:
print("Condition is True")
print("This is inside the if block")

Condition is True
This is inside the if block

Comments:
Type of Comments A. Single-line Comment – Marked with # symbol. B. Multi-line Comments – Python
does not have native multi-line comment syntax, but you can simulate it using triple quotes.

In [8]: # This is a single-line comment


print("Hello, my dear learners")

Hello, my dear learners

In [9]: """
This is a multi-line comment.
It can span multiple lines.
"""
print("Testing multiline comments")

Testing multiline comments

Line Continuation
Types of line continuation

1. Implicit - Occurs inside parentheses (), brackets [] or braces {}.


2. Explicit - Use the backslash \ to continue a line explicitly.

In [11]: # Implicit line continuation


numbers = [1, 2, 3,
4, 5, 6]
total = (1 + 2 + 3 +
4 + 5)
print("Numbers =", numbers)
print("Sum of numbers =", total)
Numbers = [1, 2, 3, 4, 5, 6]
Sum of numbers = 15

Variable
Example: Let’s declare three variables with three different type of values

In [12]: age = 100 # Creates an integer variable


salary = 9898.70 # Creates a floating point variable
name = "Mr. India" # Creates a string variable
print("Name:", name, "\nAge:", age, "\nSalary:", salary)

Name: Mr. India


Age: 100
Salary: 9898.7

Variable Naming Rules


1. A variable name must start with a letter or the underscore character.
2. A variable name can’t start with a number or a special character like $, (, * % etc.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
4. Python variable names are case-sensitive which means Name and NAME are two different
variables.
5. Python reserved keywords cannot be used naming the variable

In [14]: # Invalid Variable Names

1counter = 100
$_count = 100
zara-salary = 100000

Cell In[14], line 3


1counter = 100
^
SyntaxError: invalid decimal literal

In [17]: # Valid Variable Names

counter = 100
_count = 100
name1 = "Byomkesh"
name2 = "Feluda"
Age = 20
emp_salary = 100000
print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (emp_salary)

100
100
Byomkesh
Feluda
20
100000

In [19]: # Multiple Assignments in a Single Line (Different Values)


a, b, c = 1, 2, 3
print(a, b, c)

1 2 3
In [20]: # Assigning the Same Value to Multiple Variables
x = y = z = 100
print(x, y, z)

100 100 100

In [21]: # Reassign Variable

print(name1)
name3 = name1
print(name3)

Byomkesh
Byomkesh

In [22]: x, y = 1, 2, 3 # Too many values to unpack

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[22], line 1
----> 1 x, y = 1, 2, 3

ValueError: too many values to unpack (expected 2)

In [23]: x, y = 100 # Not iterable

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[23], line 1
----> 1 x, y = 100

TypeError: cannot unpack non-iterable int object

Dynamic Typing
Python is dynamically typed, meaning:

1. The type is associated with the object, not the variable.


2. A variable can point to different types of data during execution

In [29]: # Datatype of a variable can be checked using type() function.


x = 42 # int
print(type(x))

x = "Answer" # str
print(type(x))

x = True # bool
print(type(x)) # The arrow points to this line

<class 'int'>
<class 'str'>
<class 'bool'>

Dynamic Typing
Memory Model: Variables as References:

1. Variables are labels, not containers.


2. They point to objects in memory.
3. Multiple variables can reference the same object

In [30]: a = [1, 2, 3, 12] # creating a list


b = a
[Link](4) # Adding new value at the end of the existing list
print(a)

# Checking the object id


print(id(a))
print(id(b))

[1, 2, 3, 12, 4]
2084257900160
2084257900160

Primitive Data Types: int, float, str, bool

In Python data types are individual class of each type and the defined variables are their instances or
objects

1. int — Integer numbers


2. float — Decimal (floating-point) numbers
3. str — Textual data
4. bool — Boolean logic (True/False)

1. Int – Integer type

In [31]: # Interger type


a = 42
b = -19
c = 0

print(a, b, c)

42 -19 0

In [32]: # Python allows arbitrary large integer


big = 9999999999999999999999999999999
print("value =", big)

value = 9999999999999999999999999999999

2. Float - Floating-Point Type

In [35]: # Floating-point type


x = 3.14159
y = -0.01
z = 2.5e3 # Equivalent to 2500.0
print(x, y, z)

3.14159 -0.01 2500.0

In [36]: # Precision Limitation


print(0.1 + 0.2)

0.30000000000000004

3. str – String Type

In [37]: # String type


name = "IIT Bombay"
code = 'CS101'
print(name, code)

# Multiline strings use triple quotes


msg = """Welcome to
Python programming.""" # Arrow points to the closing triple quotes
print(msg)
IIT Bombay CS101
Welcome to
Python programming.

In [38]: # String operations


greeting = "Hello"
print(greeting + " World") # Concatenation
print(greeting * 3) # Repetition
print(len(greeting)) # Length of variable
print(greeting[1]) # Indexing start from 0

Hello World
HelloHelloHello
5
e

Strings are Immutable

1. It means that once a string is created, it cannot be changed (modified) in place.


2. Instead of altering the original string, any operation that seems to "change" a string will actually
return a new string object.

In [39]: # String is immutable


s = "data"
s[0] = 'D'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[39], line 3
1 # String is immutable
2 s = "data"
----> 3 s[0] = 'D'

TypeError: 'str' object does not support item assignment

In [40]: # To change create a new string


s = "Data" + s[1:]
print(s)

Dataata

4. bool – Boolean Type

The bool type has two values: True and False. These are special keywords in Python (capitalized), and
they’re subclasses of int:

In [41]: # Boolean type


print(True == 1) # True
print(False == 0) # True

True
True

In [42]: # Check bool value


a = 5 > 3 # True
b = 10 == 20 # False

print(a)
print(b)

True
False

type() and isinstance() functions

Type() Function
1. Returns the data type (or class type) of the object.
2. Useful for understanding and verifying how Python sees your data.

Limitation of type()

1. It checks for exact type match.


2. It does not support inheritance checks, so it's not ideal for polymorphic comparisons

In [43]: # type() function


a = 10
b = 3.14
c = "IIT"
d = True

print(type(a)) # <class 'int'>


print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'bool'>

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

type() and isinstance()

1. Checks whether an object is an instance of a particular class or a tuple of classes.


2. Returns True if the object is an instance of the class else False.
3. isinstance() supports multiple types using a tuple.
4. It's polymorphic-aware, unlike type()

In [1]: # isinstance() function

x = 5

print(isinstance(x, int)) # True


print(isinstance(x, float)) # False
print(isinstance(x, (int, float))) # True

True
False
True

Input()
The input() function is used to receive input from the user via the keyboard at runtime.

In [2]: # Example 1: Basic input


name = input("Enter your name: ")
print("Welcome,", name)

Welcome, Souvik

Sample I/O

In [3]: x = float(input("Enter number 1:"))


y = float(input("Enter number 2:"))
print("Sum:", x + y)

Sum: 76.1

In [4]: # print() Function - Displaying Output


# print() sends output to the standard output stream (usually your screen).
# It supports multiple arguments, and optional formatting using sep and end.

print("IIT", "Bombay", sep="-", end="|||\n")

IIT-Bombay|||

Sample I/O
Python supports formatted output via:

1. Concatenation (+)
2. f-strings (Python 3.6+)
3. .format() method

In [5]: # f-string
name = "Mrinal"
score = 99.5
print(f"Hello, {name}! Your score is {score:.2f}")

Hello, Mrinal! Your score is 99.50

Sample I/O
Combining input() and print() in Interactive Programs

In [6]: # Combining input() and print() in Interactive Programs

name = input("Enter your name: ")


roll = int(input("Enter your roll number: "))
marks = float(input("Enter your marks: "))

print(f"\nStudent: {name}")
print(f"Roll No: {roll}")
print(f"Marks: {marks:.2f}")

Student: Souvik
Roll No: 901
Marks: 85.00

Type Conversion: int(), float(), str(), list()


Type Casting: Example 01: Converting to int

In [7]: # Converting to int

# From float
print(int(3.9)) # 3 (decimal part truncated)

# From string
print(int("42"))
print(int("42.5")) # ValueError (invalid literal)

# From bool
print(int(True)) # 1
print(int(False)) # 0

3
42
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[7], line 8
6 # From string
7 print(int("42"))
----> 8 print(int("42.5")) # ValueError (invalid literal)
10 # From bool
11 print(int(True)) # 1

ValueError: invalid literal for int() with base 10: '42.5'

Type Casting
Example 02: Converting to float

In [8]: # Converting to float

# From int
print(float(5)) # 5.0

# From string
print(float("3.14")) # 3.14

# From bool
print(float(True)) # 1.0
print(float(False)) # 0.0

5.0
3.14
1.0
0.0

Type Casting
Example 03: Converting to str

In [9]: # Converting to str

# From int
print(str(101)) # '101'

# From float
print(str(3.1415)) # '3.1415'

# From bool
print(str(True)) # 'True'

101
3.1415
True

Type Casting
Example 04: Converting to bool

In [10]: # Converting to bool

# From int
print(bool(0)) # False
print(bool(42)) # True

# From float
print(bool(0.0)) # False
print(bool(-1.5)) # True

# From string
print(bool("")) # False (empty string)
print(bool("IIT")) # True

# From collections (advanced preview)


print(bool([])) # False
print(bool([1, 2])) # True

False
True
False
True
False
True
False
True

Type Casting
Example 05: Converting to list

The list() function is used to convert an iterable (like a string, tuple, set, etc.) into a list.

1. String to list - each character in the string becomes an element in the list.
2. Tuple to list - Converts the tuple to a list with the same elements.
3. Set to list - Converts set to list. But note: Sets are unordered, so order may not be preserved.
4. Range to list - The range object is an iterable and can be easily converted to a list

In [11]: # String to list


text = "hello"
result = list(text)
print(result) # ['h', 'e', 'l', 'l', 'o']

# Tuple to list
t = (1, 2, 3)
result = list(t)
print(result) # [1, 2, 3]

# Set to list
s = {10, 20, 30}
result = list(s)
print(result) # [10, 20, 30] (order may vary)

# Range to list
r = range(5)
result = list(r)
print(result) # [0, 1, 2, 3, 4]

['h', 'e', 'l', 'l', 'o']


[1, 2, 3]
[10, 20, 30]
[0, 1, 2, 3, 4]

Implicit vs Explicit Casting


Implicit type casting - Python automatically converts one data type to another when no data loss or
conflict occurs

In [12]: # Implicit type casting

a = 5 # int
b = 2.0 # float

result = a + b
print(result)
print(type(result))
7.0
<class 'float'>

Explicit type casting - You, the programmer, manually convert the data type using built-in functions,
like int(), float(), str(), bool(), list()

In [13]: # Explicit type casting


x = "100"
y = int(x) # Explicit cast from str to int

print(y + 5)
print(type(y))

105
<class 'int'>

Topic 2 - Built-in Functions & Control Structures

A. Common Built-in Functions


1. print() formatting Agenda
2. if, elif, else statements
3. Nested conditions
4. for loops with range()
5. while loops and loop control: break, continue, pass
6. else clause with loops

Built-in function?

1. A built-in function is a function that is already provided by Python, so you can use it directly
without writing any code to define it or importing any library.
2. Think of them as ready-made tools in Python's toolbox

Key points

1. No need to define or import them — they are ready to use.


2. Help you perform common tasks quickly, like type conversion, rounding, or length checking.
3. There are over 70 built-in functions in Python, but you only need a few to start

Some built-in function : len(), max(), min(), sum(), sorted(), round(), abs()

len() – Get length

Returns the number of items in an object (like a string, list, tuple, etc.).

In [16]: # len()
a = (len("Python")) # 6
b = (len(str(12345))) # 5 -> after converting int to str
print(a)
print(b)

6
5

max() — Find the Maximum

Returns the largest value among inputs or from an iterable.


In [17]: # max()
a = max("abc123") # 'c'
b = max(str(2183)) # '8' -> characters compared as strings
print(a)
print(b)

c
8

min() — Find the Minimum

Returns the smallest value among inputs or from an iterable.

In [18]: # min()
a = min("a1b2") # '1' -> lowest Unicode
b = min(str(340)) # '0' -> among '3', '4', '0'
print(a)
print(b)

1
0

sum() — Add All Elements

Returns the sum of numbers in a list, tuple, or other iterable.

Note:

2. Works only on numeric data.


3. Optional second argument: starting value.

In [19]: # sum()
a = sum([10, 20, 30])
b = sum((1.5, 2.5, 3))
c = sum(range(1, 5))
d = sum([1, 2, 3], 10)
print(a)
print(b)
print(c)
print(d)

60
7.0
10
16

sorted() — Sort Values

Returns a new list containing sorted elements from the iterable.

Note:

1. Returns a new list (original stays unchanged).


2. Use reverse=True for descending order.

In [20]: # sorted()
a = sorted([3, 1, 4, 2])
b = sorted(["banana", "apple"])
c = sorted("code")
d = sorted([5, 2, 9], reverse=True)
print(a)
print(b)
print(c)
print(d)
[1, 2, 3, 4]
['apple', 'banana']
['c', 'd', 'e', 'o']
[9, 5, 2]

round() — Round Numbers

Rounds a float to the nearest integer or to a specific number of decimal places.

Note:

1. Python uses round half to even strategy (round(2.5) → 2).

In [21]: # round()
a = round(3.75)
b = round(float("7.3"))
c = round(5.6789, 2)
print(a)
print(b)
print(c)

4
7
5.68

abs() — Absolute Value

Returns the positive version of a number, ignoring the sign.

Note:

1. Useful in distance, difference, or loss calculations.

In [22]: # abs()
a = abs(-10)
b = abs(float("-5.3"))
c = abs(bool(-1))
print(a)
print(b)
print(c)

10
5.3
1

B. print() formatting: f-strings, .format()

Why important?
1. When building programs, we often need to display information to the user in a clean, readable,
and meaningful way.
2. Whether it's for debugging, reporting results, or displaying data—how we print matters.

Formatting
Syntax

f"text {expression}“

1. You prefix the string with f or F and put Python expressions inside curly braces {}.

Example 01
In [23]: # f-string
name = "Mrinal"
score = 85
print(f"Hello, {name}! You scored {score} marks.")

Hello, Mrinal! You scored 85 marks.

Example 02
1. Using with type casting

In [24]: # formatf-string with type casting


marks = "90"
print(f"Marks as integer: {int(marks)}")
print(f"Marks as float: {float(marks)}")

Marks as integer: 90
Marks as float: 90.0

Example 03
1. f-string with Boolean

In [25]: # f-string with boolean


x = 0
print(f"Is x non-zero? {bool(x)}")

Is x non-zero? False

Example 04
1. Formatting numbers

In [28]: # Formatting numbers


pi = 3.1415926535
print(f"Rounded PI: {round(pi, 2)}")
print(f"PI with 2 decimals: {pi:.2f}")

Rounded PI: 3.14


PI with 2 decimals: 3.14

Formatting
Syntax

1. "some text {}".format(value)


2. You use {} as placeholders and pass the values to .format()

Example 01

In [29]: # .format() Method


name = "Mrinal"
marks = 92
print("Student: {} | Marks: {}".format(name, marks))

Student: Mrinal | Marks: 92

Example 02
Using Index or Names

In [30]: # Using index or names


print("Hello {0}, you scored {1}".format("Alice", 88))
print("Hello {name}, score: {score}".format(name="Bob", score=77))
Hello Alice, you scored 88
Hello Bob, score: 77

Example 03
Formatting with Type Conversion

In [31]: # Formatting with type conversion


X = "100"
print("As integer: {}".format(int(X)))
print("As float: {:.2f}".format(float(X)))

As integer: 100
As float: 100.00

C. if, elif, else statements

Control Structures
1. Control Structures are the building blocks that control the flow of execution of a Python program.
2. They allow the program to make decisions, repeat actions, and branch into different paths

Why are control structures needed?


Programs aren't just about executing instructions in a straight line. Real-world tasks require:

1. Decision Making Example: If the user is logged in, show their dashboard; otherwise, show login
page.
2. Repetition/Looping Example: Go through a list of students and print their grades.
3. Skipping or Breaking Out of Loops Example: Stop processing if an error occurs. Without control
structures program would only run top-to-bottom — no intelligence, no flexibility.

Types of Control Structures in Python


Type:

Decision Making

Structure:

if:, elif:, else:

Purpose:

Execute code based on conditions

Type:

Looping

Structure:

for:, while:

Purpose:

Repeat code blocks

Type:

Loop Control

Structure:
break:, continue:, pass:

Purpose:

Modify behaviour inside loops

Real life Analogy


Think of control structures like road signs on a highway:

1. if is like a traffic signal — go if green, stop if red. Modify behaviour inside loops
2. for/while is like a roundabout — go around repeatedly until you exit. Private and Confidential
3. break is like emergency brakes — stop the loop immediately

Without control structure


Explanation:

1. This program always prints the same messages — regardless of who runs it or what data is
provided.
2. There is no logic or decision-making.
3. This approach is called linear execution — each line runs in order, no matter what

In [32]: # Without control structures


print("Welcome")
print("You are eligible")
print("Thank you")

Welcome
You are eligible
Thank you

Explanation
a. Dynamic Input:

1. input() takes the value as a string, and int() converts it to an integer.

b. Decision Making (if-else):

1. The if block checks: Is the age 18 or more?


2. If yes, it prints eligibility.
3. If no, it goes to the else block and prints the Private and Confidential © Career247 opposite
message.

In [33]: # With control structures


# It changes based on input, thanks to control structures.
age = int(input("Enter your age: "))

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible.")

You are not eligible.

if, elif, else Statements


1. if — to test a condition
2. elif — to test multiple condition
3. else — to catch anything not caught by the previous conditions
In [39]: if condition1:
# Run this block if condition1 is True
elif condition2:
# Run this block if condition1 is False and condition2 is True
elif condition3:
# Run this block if all above are False and condition3 is True
elif condition4:
...
elif condition5:
...
else:
# If none of the above conditions are True, run this

Cell In[39], line 3


elif condition2:
^
IndentationError: expected an indented block after 'if' statement on line 1

1. if condition1 : FAlSE ……
2. elif condition2 : FALSE …….
3. elif condition3 : TRUE (condition stop here) …….
4. elif condition4 : …….
5. else Final condition:

In [34]: # Understanding the Grading System


marks = 75

if marks >= 90:


print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C") # This one matches
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")

Grade: C

Overlapping Ranges (with a mistake)


The elif temperature > 25 is never reached, because temperature > 20 is already True.

In [ ]: # Example: Overlapping ranges (with a mistake!)


temperature = 30

# Logical error: the order of conditions affects the result!


if temperature > 20:
print("It's warm")
elif temperature > 25:
print("It's hot")
else:
print("It's cold")

Fix:
Check higher conditions first

In [38]: # Fix: Check higher conditions first


temperature = 30
if temperature > 25:
print("It's hot")
elif temperature > 20:
print("It's warm")
else:
print("It's cold")

It's hot

D. Nested conditions

What are Nested Conditions?


1. A nested condition occurs when one conditional block contains another conditional.
2. This allows us to make multi-level decisions, like asking more detailed questions after a broader
check.

In [40]: if condition1:
if condition2:
# Execute this block if both condition1 and condition2 are True
else:
# Executes if condition1 is True but condition2 is False
else:
# Executes if condition1 is False

Cell In[40], line 4


else:
^
IndentationError: expected an indented block after 'if' statement on line 2

Example 01:
Find weather condition based on temperature & humidity

Explanation
1. First, check temperature.
2. If that passes, then check humidity.
3. This allows multi-level decision making, like layered filters.

In [41]: # Find weather condition based on temperature & humidity


temperature = 30
humidity = 70

if temperature > 25:


if humidity > 60:
print("It's hot and humid.") # Both conditions met
else:
print("It's hot but dry.")
else:
print("The temperature is moderate.")

It's hot and humid.

Example 02: Login Simulation


Explanation:

1. This structure simulates how login systems validate user credentials in two steps:
2. Check if the username is valid
3. If yes, then check if the password matches
Why use Nested Conditions?
Explanation:

1. This structure simulates how login systems validate user credentials in two steps:
2. Check if the username is valid
3. If yes, then check if the password matches

In [44]: # Login Simulation


username = "admin"
password = "123204"

if username == "admin":
if password == "1234":
print("Access granted!")
else:
print("Wrong password!") # Password mismatch
else:
print("Username not found!") # Username doesn't exist

Wrong password!

Example 03: Vehicle Recommendation System

In [45]: budget = 2 # 1 = Low, 2 = Medium, 3 = High


fuel_type = "Electric" # Options: Petrol, Diesel, Electric

if budget == 1:
print("Recommended: Used hatchback (Petrol).")

elif budget == 2:
# Nested decision based on fuel preference
if fuel_type == "Petrol":
print("Recommended: Mid-range sedan (Petrol).")
elif fuel_type == "Diesel":
print("Recommended: Mid-range SUV (Diesel).")
else:
print("Recommended: Electric hatchback.")

elif budget == 3:
print("Recommended: Premium electric SUV or sedan.")

else:
print("Invalid budget input. Please enter 1, 2, or 3.")

Recommended: Electric hatchback.

E. for loops with range()


range() Function:

1. range() is a built-in Python function that returns a sequence of numbers, commonly used in loops
—especially with for loops—to repeat a block of code a fixed number of times.
2. It does not create a list directly , but an iterable range object that produces numbers one by one
as needed.

for loop:
1. In Python, the for loop is used to iterate over a sequence (like a list, string, or range).
2. When combined with the range() function, it allows repetition of tasks a specific number of times.
for Loop Flow
The for loop in Python is used to iterate over a sequence (like a list, string, tuple, or a range() object).
The loop continues until all elements in the sequence are processed.

Start with a Sequence

1. Python first creates or gets access to a sequence of items.

Check: Last item reached?

1. Python internally keeps a loop index (or iterator).


2. It checks whether the iterator has reached the end of the sequence.
3. This is a True/False decision point.

Then It Loops Back:

1. After the current item is processed, Python goes back to check if there's another item.
2. his continues until the last item is reached.

If True:

1. All items have been processed.


2. Python exits the loop and moves on to the next statement after the loop block.

In [48]: # for variable in range(start, stop, step)

Example 01

In [49]: # Print 0 to 5
for i in range(6):
print(i)

0
1
2
3
4
5

Example 02

In [50]: # Print between 5 and 10


for i in range(5, 11):
print(i)

5
6
7
8
9
10

Example 03

In [51]: # Print even numbers between 1 and 11 in descending order


for i in range(10, 0, -2):
print(i)
10
8
6
4
2

The object range(start, stop, step) does not generate all numbers at once. It creates a lazy iterable,
saving memory — especially useful when looping over large ranges. You can convert it to a list like
this:

In [52]: list(range(1, 6)) # [1, 2, 3, 4, 5]

Out[52]: [1, 2, 3, 4, 5]

F. while loops and loop control: break, continue, pass


while loop
1. A while loop keeps executing a block of code as long as a condition is True.
2. It is used when the number of iterations is not known in advance.

Note:
1. The condition is evaluated before each iteration.
2. If True, the block runs; else, the loop stops.

Note:
1. The condition is evaluated before each iteration.
2. If the condition is True, the block runs.
3. When the condition becomes False, the loop stops.

Key use cases


1. Repeating a task until user gives valid input.
2. Running a process until a specific condition occurs (e.g., file download complete).
3. Infinite loops with manual breaks.

Comparison
1. Keyword: while:
2. Use: Repeat based on condition
3. Exits Loop?: No
4. Skips Iteration?:No
5. Placeholder?:NO

1. Keyword: break:
2. Use: Force exit
3. Exits Loop?: Yes
4. Skips Iteration?:No
5. Placeholder?:No

1. Keyword: continue:
2. Use: Skip iteration
3. Exits Loop?: No
4. Skips Iteration?:Yes
5. Placeholder?:No

1. Keyword: pass:
2. Use: Do nothing (placeholder)
3. Exits Loop?: No
4. Skips Iteration?:No
5. Placeholder?:Yes

Example 01
Explanation:

1. The loop checks if count <= 5


2. After printing, count is incremented.
3. Once count becomes 6, the condition fails and loop exits.

In [ ]: # Ask user until correct password is entered


password = "python123"
while password != "python123":
password = input("Enter password: ")
print("Access granted.")

Example 02
A True condition without any loop counter update makes it infinite.

Loop that never stops unless manually broken

1. while True:
2. print("Running endlessly...") # never run this code or it will break the python file

In [53]: # Print numbers from 1 to 5


count = 1
while count <= 5:
print(count)
count += 1

1
2
3
4
5

Example 03
Notes:

1. This loop may run forever if the user never types the correct password. Private and Confidential
© Career247
2. In a real system, you'd also add attempt limits or security measures (like lockout after 3 tries).

In [2]: # Ask user until correct password is entered


password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted.")

Access granted.

Example 01
This loop will exit when the loop counter variable reaches 5 because of the break.

In [3]: # break - stop at a condition


i = 1
while i <= 10:
if i == 5:
break
print(i)
i += 1

1
2
3
4

Example 02
index: 0, 1, 2, 3

nums[index]: 1,3, 5, 8

Even?: x,x, x, yes

Action: Continue, Continue, Continue, Print & break loop

In [4]: # Search Until Found


nums = [1, 3, 5, 8, 9]
index = 0

while index < len(nums):


if nums[index] % 2 == 0:
print("Even number found:", nums[index])
break
index += 1

Even number found: 8

Break Statement inside while

Example 03

Explanations:

1. Nested Loops Structure The outer loop runs with i from 0 to 2, and for each i, the inner loop runs
j from 0 to 2.
2. Break When i == j Inside the inner loop, if the condition i == j is met, the break exits only the
inner loop (not the outer loop).
3. Print Only When i != j The print(f"i={i}, j={j}") happens only when i != j, so the output skips
printing when i equals j, and continues to the next i.

In [5]: # break inside nested while


i = 0
while i < 3:
j = 0
while j < 3:
if i == j:
break
print(f"i={i}, j={j}")
j += 1
i += 1

i=1, j=0
i=2, j=0
i=2, j=1
continue Statement

Example 01
This skip the remaining part of the while loop when ‘i;’ is odd.

In [6]: # Skip Odd Numbers


i = 0
while i < 10:
i += 1
if i % 2 != 0:
continue
print(i)

2
4
6
8
10

Example 02
1. Program will exit if the user input ‘exit’
2. If no name is given, then remaining part of the while loop will be ignored.

In [7]: # Manual exit


while True:
name = input("Enter name (type 'exit' to stop):")
if name == "exit":
break
if name == "":
continue # skip empty inputs
print("Hello", name)

Hello Souvik
Hello Roy
Hello Souvik Roy

Pass Statement
1. pass is a placeholder used when a statement is required syntactically but no action is needed.
2. It’s often used while defining loops or functions that are yet to be implemented.

Example 01
Trying to skip syntax error

In [8]: # Pass - to avoid syntax errors


x = -5
if x > 0:
pass # Placeholder
else:
print("Negative")

Negative

Example 02
Can be used when planning the code structure

In [ ]: # Pass - during code planning


while True:
# TODO: implement login later
pass

G. else Clause with Loops


else:
1. In Python, both for and while loops can have an else clause attached.
2. This is unique to Python compared to many other programming languages.

How It Works?

1. The else block is executed only if the loop completes normally, without encountering a break.
2. If a break is used to exit the loop early, the else block is skipped.

Example 01

Explanation
1. The loop iterates through all numbers looking for 5.
2. Since 5 is not found, break is never triggered.
3. The else block runs and prints "Not found".

In [1]: # for loop with else (Search & Not Found)


# Search for a number in the list
nums = [2, 4, 6, 8]
target = 5

for num in nums:


if num == target:
print("Found!")
break
else:
print("Not found!") # Runs because loop didn't break

Not found!

Example 02

Explanation
1. The loop runs while i < 4 and never hits the break.
2. The condition i == 5 is never True.
3. Hence, else runs and prints "Completed search".

In [ ]: # while loop with else (Count Until Condition fails)


i = 1
while i <= 3:
print("Count:", i)
i += 1
else:
print("Counting done!") # Runs after while condition becomes False

Example 03

Explanation
1. Loop breaks early when i == 3. Since break was triggered, else is skipped.
2. Nothing from the else block is printed.
In [9]: # Skipped else Due to break
i = 0
while i < 5:
if i == 3:
break
print(i)
i += 1
else:
print("Loop ended naturally")

0
1
2

PYTHON: Strings, Lists and Tuples

01. String Indexing


Creating String Variables
1. String variables are variables that hold zero or more characters such as letters, numbers, spaces,
commas and many more
2. Use type(variable_name) to check the data type of a variable

In [1]: # declare a string variable


product = "louis vuitton"
# print the string variable
print(product)
# check the data type of the variable
type(product)

louis vuitton
Out[1]: str

Using Index Position To Slice A String

string_variable[positive index position]

In [3]: # declare a string variable


product = "louis vuitton"
# use an index position to extract a letter
# 0 gives us the 1st character
product[0]

Out[3]: 'l'

In [4]: # use an index position to extract a letter


# 6 gives us the 7th character
product[6]

Out[4]: 'v'

string_variable[negative index position]

In [5]: # declare a string variable


product = "louis vuitton"
# use an index position to extract a letter
# -1 gives us the last character
product[-1]
Out[5]: 'n'

In [6]: # use an index position to extract a letter


# -2 gives us the 2nd last character
product[-2]

Out[6]: 'o'

string_variable[start index : stop index]

In [7]: # declare a string variable


product = "louis vuitton"

# start index as 0, end index as 5


# This will return the characters starting at index position 0
# till the index position 5-1 i.e. 4
product[0:5]

Out[7]: 'louis'

In [8]: # start index as 6, end index as 11


# This will return the characters starting at index position 6
# till the index position 11-1 i.e. 10
product[6:11]
'vuitt'

Out[8]: 'vuitt'

string_variable[start index : stop index] Negative

In [9]: # declare a string variable


product = "louis vuitton"

# start index as -5, end index as -1


# this will return the characters starting at index position -5
# till the index position -1-1 i.e. -2
product[-5:-1]
'itto'

Out[9]: 'itto'

In [10]: # start index as -13, end index as -8


# this will return the characters starting at index position -13
# till the index position -8-1 i.e. -9
product[-13:-8]

Out[10]: 'louis'

string_variable[ : stop index]

In [11]: # start index as blank end index as 5


# This will return the characters starting at index position 0
# till the index position 5-1 i.e. 4
product[:5]

Out[11]: 'louis'

string_variable[start index : ]

In [12]: # declare a string variable


product = "louis vuitton"

# start index as 6, end index as blank


# This will return the characters starting at index position 6
# till the last index position
product[6:]

Out[12]: 'vuitton'

In [ ]: ##### string_variable[start index : stop index : step]

In [13]: # declare a string variable


product = "louis vuitton"

# start index as 0, end index as 15, step as 1


# This will return the characters starting at index position 0
# till the index position 15-1 i.e. 14
# jump by 1 steps (default).
product[0:15:1]

Out[13]: 'louis vuitton'

In [14]: # start index as 0, end index as 15, step as 2


# This will return the characters starting at index position 0
# till the index position 15-1 i.e. 14
# jump by 2 steps
product[0:15:2]

Out[14]: 'lusvitn'

02. Built-in Functions


A Few Built-in Functions for Strings

In [15]: # declare a string


text = "Corporate Bonds"

# print the variable


print(text)

Corporate Bonds

In [16]: # check the data type of the variable


type(text)

Out[16]: str

In [17]: # check how many characters are present in the string


len(text)

Out[17]: 15

02. String Methods


Built-in Functions & Methods
1. A function is a set of instructions. Python has many built-in functions like print(), type(), int(), str()
and many more.
2. A method is very much like a function. The difference is that a method is associated with an
object, like string, list, tuple, dictionary and other type of objects.

String Method: islower()


In [18]: # declare a string
text = "liquidity risk"

# check if the text is in lowercase


[Link]()

Out[18]: True

In [19]: # declare a string


text = "Liquidity Risk"

# check if the text is in lowercase


[Link]()

Out[19]: False

String Method: isupper()

In [20]: # declare a string


text = "LIQUIDITY RISK"
# check if the text is in lowercase
[Link]()

Out[20]: False

In [21]: # declare a string


text = "liquidity risk"

# check if the text is in uppercase


[Link]()

Out[21]: False

In [22]: # declare a string


text = "Liquidity Risk"

# check if the text is in uppercase


[Link]()

Out[22]: False

In [23]: # declare a string


text = "LIQUIDITY RISK"

# check if the text is in uppercase


[Link]()

Out[23]: True

String method: istitle()

In [24]: # declare a string


text = "corporate bonds are issued by companies"

# check if the text is in titlecase


[Link]()

Out[24]: False

In [25]: # declare a string


text = "Corporate bonds are issued by companies"
# check if the text is in titlecase
[Link]()

Out[25]: False

In [26]: # declare a string


text = "Corporate Bonds Are Issued By Companies"

# check if the text is in titlecase


[Link]()

Out[26]: True

String Method: isalnum()

In [27]: # declare a string


text = "Boeing747"

# check if the characters are alphanumeric


[Link]()

Out[27]: True

In [28]: # declare a string


zipcode = "310120"

# check if the characters are alphanumeric


[Link]()

Out[28]: True

In [29]: # declare a string


housenumber = "#11-217"

# check if the characters are alphanumeric


[Link]()

Out[29]: False

String Method: isalpha()

In [30]: # declare a string


text = "TreasureBills"

# check if the characters are ahphabets


[Link]()

Out[30]: True

In [31]: # declare a string


text = "Treasure Bills"

# check if the characters are ahphabets


[Link]()

Out[31]: False

In [32]: # declare a string


text = "Treasure-Bills"

# check if the characters are ahphabets


[Link]()
Out[32]: False

String method: isdigit()

In [33]: # declare a string


text = "zipcode 310120"

# check if the characters are digits


[Link]()

Out[33]: False

In [34]: # declare a string


text = "310120"

# check if the characters are digits


[Link]()

Out[34]: True

In [35]: # declare a string


text = "310-120"

# check if the characters are digits


[Link]()

Out[35]: False

String Method: split()

In [36]: # declare a string


text = "Never invest emergency savings in the stock market"

# split the string into words


# default separator is a whitespace
# so it splits wherever it encounters a whitespace
[Link]()

Out[36]: ['Never', 'invest', 'emergency', 'savings', 'in', 'the', 'stock', 'market']

String Method: upper()

1. Converts a string into upper case

In [37]: # declare a string


text = "exchange traded funds"

# convert the string into uppercase


[Link]()

Out[37]: 'EXCHANGE TRADED FUNDS'

In [39]: # Did the text variable change?


print(text)

exchange traded funds

String Method: lower()

In [40]: # declare a string


text = "EXCHANGE TRADED FUNDS"
# convert the string into lowercase
[Link]()

Out[40]: 'exchange traded funds'

In [42]: # Did the text variable change?


print(text)

EXCHANGE TRADED FUNDS

String Method: title()

In [43]: # declare a string


text = "exchange TRADED fund"

# convert the string into lowercase


[Link]()

Out[43]: 'Exchange Traded Fund'

In [44]: # Did the text variable change?


print(text)

exchange TRADED fund

String Method: capitalize()

In [46]: # declare a string


text = "exchange traded fund"

# capitalize the sentence


[Link]()

Out[46]: 'Exchange traded fund'

String Method: swapcase()

In [47]: # declare a string


text = "exchange TRADED fund"

# swap case
[Link]()

Out[47]: 'EXCHANGE traded FUND'

String Method: replace()

In [48]: # declare a string


text = "callable bonds, puttable bonds and perpetual bonds"

# replace the word bonds with instruments


[Link]("bonds", "instruments")

Out[48]: 'callable instruments, puttable instruments and perpetual instruments'

In [49]: # declare a string


text = "callable bonds, puttable bonds and perpetual bonds"

# replace the 1st two occurence of the word bonds with instruments
[Link]("bonds", "instruments", 2)

Out[49]: 'callable instruments, puttable instruments and perpetual bonds'

String Method: format()


1. Formats the specified value(s) and insert them inside the string's placeholders. A placeholder is
defined using curly brackets: {}

In [50]: # Declare a string with placeholder


# Fill in the placeholder
# The 1st placeholder is filled with "Klaus"
# The 2nd placeholder is filled with "36"
text = "His name is {}. He is {}".format("Klaus",36)

# print the text variable


print(text)

His name is Klaus. He is 36

String Method: format()

1. Using named values to fill in the placeholder

In [51]: # Declare a string with placeholder


# Fill in the placeholder
# The 1st placeholder is filled with named variable, name
# The 2nd placeholder is filled with named variable, age
text = "His name is {name}. He is {age}".format(age=36, name="Klaus")

# print the text variable


print(text)

His name is Klaus. He is 36

String Method: reverse()

1. Returns the index of first occurrence of the substring, if found. Else returns -1.

In [52]: # declare a variable


quote = "Irrational lenders come and go -- mostly they go!"

# find a word With NO start and end Argument


[Link]("lenders")

Out[52]: 11

In [53]: # find a word With NO start and end Argument


[Link]("heavenly")

Out[53]: -1

In [54]: # find a word With start Argument


# In this case "mostly" is searched in "go -- mostly they go!"
[Link]("mostly", 28)

Out[54]: 34

In [55]: # find a word With start Argument


# In this case "mostly" is searched in "they go"
[Link]("mostly", 41)

Out[55]: -1

04. List Creation


List

1. Container or collection object


2. Homogeneous or Heterogeneous sequence of elements
3. Can have duplicate values
4. Are mutable
5. Created using [] parenthesis; Elements are separated by comma
6. Indexed & sliced using []

List

1. A few of the operations supported by list:


2. Loops & conditional statements
3. Membership operators - in, not in
4. Concatenation
5. Built-in functions like print(), type(), min(), max(), len()
6. Indexing and slicing using []
7. Append elements

Creating a homogeneous list

In [56]: # Creating a homogeneous list


customers_age = [23, 34, 19, 56, 45, 37, 39]

# print the list


print(customers_age)

[23, 34, 19, 56, 45, 37, 39]

In [58]: # check the type of the object


type(customers_age)

Out[58]: list

Creating a heterogeneous list

In [59]: # Creating a heterogeneous list


financial_instruments = ["CPF", "Bonds", "Equities", 2300, 3400, 1700]

# print the list


print(financial_instruments)

['CPF', 'Bonds', 'Equities', 2300, 3400, 1700]

In [60]: # check the type of the object


type(financial_instruments)

Out[60]: list

05. List Indexing

Indexing and Slicing

Using Index Position To Slice A List

list_variable[positive index position]

In [ ]: # Create a list
stock_prices = [23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43]

# use an index position to extract an element from the list


# 0 gives us the 1st element
stock_prices[0]

In [62]: # use an index position to extract an element from the list


# 3 gives us the 4th element
stock_prices[3]

Out[62]: 28

list_variable[negative index position]

In [63]: # use an index position to extract an element from the list


# -1 gives us the 1st last element
stock_prices[-1]

Out[63]: 43

In [64]: # use an index position to extract an element from the list


# -2 gives us the 2nd last element
stock_prices[-2]

Out[64]: 19

list_variable[start index : stop index]

In [65]: # Create a list


stock_prices = [23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43]

# start index as 0, end index as 5


# This will return the elements starting at index position 0
# till the index position 5-1 i.e. 4
stock_prices[0:5]

Out[65]: [23, 24, 27, 28, 32]

In [66]: # start index as 6, end index as 11


# This will return the elements starting at index position 6
# till the index position 11-1 i.e. 10
stock_prices[6:11]

Out[66]: [24, 46, 43, 31, 42]

list_variable[ : stop index]

In [67]: # start index as blank, end index as 5


# This will return the elements starting at index position 0
# till the index position 5-1 i.e. 4
stock_prices[:5]

Out[67]: [23, 24, 27, 28, 32]

list_variable[start index : ]

In [68]: # Create a list


stock_prices = [23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43]

# start index as 6, end index as blank


# This will return the elements starting at index position 6
# till the last index position
stock_prices[6:]

Out[68]: [24, 46, 43, 31, 42, 72, 82, 32, 19, 43]
list_variable[start index : stop index] Negative

In [69]: # Create a list


stock_prices = [23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43]

# start index as -5, end index as -1


# this will return the elements starting at index position -5
# till the index position -1-1 i.e. -2
stock_prices[-5:-1]

Out[69]: [72, 82, 32, 19]

In [70]: # start index as -13, end index as -8


# this will return the elements starting at index position -13
# till the index position -8-1 i.e. -9
stock_prices[-13:-8]

Out[70]: [28, 32, 22, 24, 46]

[Link] Operations
Concatenate Lists

In [71]: # create two lists


prices_yesterday = [23, 45, 11, 98]
prices_today = [49, 66, 45]

# concatenate two lists


prices_combined = prices_yesterday + prices_today

# print the list


print(prices_combined)

[23, 45, 11, 98, 49, 66, 45]

Repeating Lists

In [72]: # create a list


stocks = ["AAPL", "ULVR", "BMW"]

# number of times you wish to repeat the list


n = 3

# repeat the list elements n times using * operator


stocks * n

Out[72]: ['AAPL', 'ULVR', 'BMW', 'AAPL', 'ULVR', 'BMW', 'AAPL', 'ULVR', 'BMW']

Check Elements In A List

In [73]: # create a tuple


stocks = ("AAPL", "ULVR", "BMW")

# check existence of ULVR in the list


"ULVR" in stocks

Out[73]: True

In [74]: # check existence of MSFT in the tuple


"MSFT" not in stocks

Out[74]: True
List Of Lists

Creating nested lists

In [75]: # Creating lists


customer_1 = ["Jack", 23]
customer_2 = ["Tommy", 27]
customer_3 = ["Macy", 24]
customer_4 = ["Jennie", 19]

# Creating list of lists


customers = [customer_1, customer_2, customer_3, customer_4]

# print the list


print(customers)

[['Jack', 23], ['Tommy', 27], ['Macy', 24], ['Jennie', 19]]

In [76]: # extract the 2nd element from the list


print(customers[1])

['Tommy', 27]

In [77]: # extract the 1st element from the 2nd element from the list
print(customers[1][0])

Tommy

List Of Tuples

Creating tuples inside a list

In [78]: # Creating tuples


customer_1 = ("Jack", 23)
customer_2 = ("Tommy", 27)
customer_3 = ("Macy", 24)
customer_4 = ("Jennie", 19)

# Creating list of tuples


customers = [customer_1, customer_2, customer_3, customer_4]

# print the list


print(customers)

[('Jack', 23), ('Tommy', 27), ('Macy', 24), ('Jennie', 19)]

In [79]: # extract the 2nd element from the list


print(customers[1])

('Tommy', 27)

In [80]: # extract the 1st element from the 2nd element from the list
print(customers[1][0])

Tommy

Iterating Through A List

Iterating through the elements of a list

In [81]: # Create a list


stocks = ["AAPL", "ULVR", "BMW"]

# using for loop iterate through each element


# print each element at each iteration
for i in stocks:
print(i)
AAPL
ULVR
BMW

Iterating Through A List Of Tuples

Iterating through the list

In [83]: # Creating tuples


emp_1, emp_2, emp_3, emp_4 = ("Tom", 23), ("Rom", 27), ("Pom", 24), ("Som", 19)

# Creating list of tuples


employees = [emp_1, emp_2, emp_3, emp_4]

# print the list


print(employees)

[('Tom', 23), ('Rom', 27), ('Pom', 24), ('Som', 19)]

In [84]: # using for loop iterate through each element


# print each element at each iteration
for i in employees:
print(i)

('Tom', 23)
('Rom', 27)
('Pom', 24)
('Som', 19)

07. Built-in Functions


len()

In [85]: # create a list


stocks = ["AAPL", "ULVR", "BMW"]

# count the number of elements


len(stocks)

Out[85]: 3

In [86]: # create a list


stock_prices = (23, 24, 27, 28, 32, 22)

# count the number of elements


len(stock_prices)

Out[86]: 6

max()

In [87]: # create a list


stock_prices = [23, 24, 27, 28, 32, 22]

# find the max value in the list


max(stock_prices)

Out[87]: 32

In [88]: # create a list


stocks = ["ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw"]

# find the max value in the list


max(stocks)
Out[88]: 'ulvr'

min()

In [89]: # create a list


stock_prices = [23, 24, 27, 28, 32, 22]

# find the min value in the list


min(stock_prices)

Out[89]: 22

In [90]: # create a list


stocks = ["ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw"]

# find the min value in the list


min(stocks)

Out[90]: 'AAPL'

max() and min()

The max() & min() cannot be used on a heterogeneous list

In [91]: # Creating a heterogeneous list


financial_instruments = ["CPF", "Bonds", "Equities", 2300, 3400, 1700]

# find the max value in the list


max(financial_instruments)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[91], line 5
2 financial_instruments = ["CPF", "Bonds", "Equities", 2300, 3400, 1700]
4 # find the max value in the list
----> 5 max(financial_instruments)

TypeError: '>' not supported between instances of 'int' and 'str'

sorted()

Use the sorted() function to sort a list

In [1]: # create a list


stock_prices = [23, 24, 27, 28, 32, 22]

# sort the list


sorted(stock_prices)

Out[1]: [22, 23, 24, 27, 28, 32]

In [2]: # create a list


stocks = ["ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw"]

# sort the list


sorted(stocks)

Out[2]: ['AAPL', 'BMW', 'ULVR', 'aapl', 'bmw', 'ulvr']

sorted()

The sorted() cannot be used on a heterogeneous list


In [3]: # Creating a heterogeneous list
financial_instruments = ["CPF", "Bonds", "Equities", 2300, 3400, 1700]

# sort the list


sorted(financial_instruments)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 5
2 financial_instruments = ["CPF", "Bonds", "Equities", 2300, 3400, 1700]
4 # sort the list
----> 5 sorted(financial_instruments)

TypeError: '<' not supported between instances of 'int' and 'str'

The del Keyword

Use the del keyword to delete any object. In this example, we delete a list object.

In [4]: # create a list


stocks = ["ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw"]

# print the list


print(stocks)

['ULVR', 'BMW', 'aapl', 'AAPL', 'ulvr', 'bmw']

In [5]: # delete the list


del stocks

# try printing the list


print(stocks)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[5], line 5
2 del stocks
4 # try printing the list
----> 5 print(stocks)

NameError: name 'stocks' is not defined

The del Keyword

Use the del keyword to delete a few elements from a list

In [6]: # create a list


stock_prices = [23, 24, 27, 28, 32, 22]

# delete a few elements from a list


del stock_prices[1:4]

# print the list


stock_prices

Out[6]: [23, 32, 22]

The del Keyword

Since a tuple is immutable, an element cannot be deleted from it

In [8]: # create a tuple


stock_prices = (23, 24, 27, 28, 32, 22)
# delete a few elements from a tuple
del stock_prices[1:4]

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 5
2 stock_prices = (23, 24, 27, 28, 32, 22)
4 # delete a few elements from a tuple
----> 5 del stock_prices[1:4]

TypeError: 'tuple' object does not support item deletion

08. List Methods


Extending a List

Extends the current list by adding all items of the the specified list (passed as an argument) to the end

In [9]: prices_a = [10, 20, 30]


prices_b = [40, 50, 60]

# list concatenation using extend() method


# here price_b is passed as a parameter to
# the extend method
prices_a.extend(prices_b)
print(prices_a)

[10, 20, 30, 40, 50, 60]

Difference Between List Concatenation and extend() Method

Extends the current list by adding all items of the the specified list (passed as an argument) to the end

In [10]: prices_a = [10, 20, 30]


prices_b = [40, 50, 60]
prices_c = [70, 80, 90, 100]

# list concatenation using + operator


concat_prices = prices_a + prices_b + prices_c
print(concat_prices)

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

In [11]: # list concatenation using extend() method


# here price_b is passed as a parameter to
# the extend method
prices_c.extend(prices_b)

print(prices_c)

[70, 80, 90, 100, 40, 50, 60]

Count the Number of Occurrences

Returns the number of times a value appears in the list

In [2]: stocks = ['AAPL', 'AAPL', 'MSFT', 'GOOL', 'AAPL']

# count the occurence of AAPL


[Link]('AAPL')

Out[2]: 3

In [1]: market_cap = [121, 232, 456, 121, 178, 121, 121]


# count the occurence of 121
market_cap.count('AAPL')

Out[1]: 0

Append An Element At The End

Adds an element at the end of an existing list. Updates the existing list.

In [14]: # create a blank list


inflations = []

# append an element to the blank list


[Link](8.5)

# print the inflations variable


print(inflations)

[8.5]

In [15]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# append an element to the list


mortage_payment.append(9000)

# print the mortage_payment variable


print(mortage_payment)

[4500, 3400, 7650, 1200, 9000]

Insert An Element At A Specified Location

Adds an element at a specified index location of an existing list. Updates the existing list.

In [16]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# insert 9000 at index position 2


mortage_payment.insert(2, 9000)

# print the mortage_payment variable


print(mortage_payment)

[4500, 3400, 9000, 7650, 1200]

Locate The Index Position Of A Value

Returns the index position of an existing value in a list

In [18]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# find the index position of 3400


mortage_payment.index(3400)

Out[18]: 1

Sort a list

The sort() method sorts the elements of a list and overwrites the original list

In [19]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# call the sort() method


mortage_payment.sort()

# print the mortage_payment variable


print(mortage_payment)

[1200, 3400, 4500, 7650]

Sort a list

The sort() cannot be used on a heterogeneous list

In [17]: # defining a list


list_with_mixed_Datatypes = [12.34, "Cereals", "USA", 34, "China", 34.5]

# sort
list_with_mixed_Datatypes.sort()

# printd the sorted list


list_with_mixed_Datatypes

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[17], line 5
2 list_with_mixed_Datatypes = [12.34, "Cereals", "USA", 34, "China", 34.5]
4 # sort
----> 5 list_with_mixed_Datatypes.sort()
7 # printd the sorted list
8 list_with_mixed_Datatypes

TypeError: '<' not supported between instances of 'str' and 'float'

Reverse The Order Of The Values

Reverses the order of the elements in a list. NOTE: Not same as sorting.

In [18]: # create a list of values


sectors = ['Tech', 'Energy', 'Consumer Durables', 'Healthcare']

# reverse the contents of a list


[Link]()

# print the sectors variable


print(sectors)

['Healthcare', 'Consumer Durables', 'Energy', 'Tech']

Copying A List

In [19]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# copy the list using = operator


new_list = mortage_payment.copy()

# print both the lists


print(mortage_payment)
print(new_list)

[4500, 3400, 7650, 1200]


[4500, 3400, 7650, 1200]

Copy a list using = operator and append an element to any list

In [20]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# copy the list using = operator


new_list = mortage_payment

# print both the lists


print(mortage_payment)
print(new_list)

# Add an element to mortage_payment


mortage_payment.append(9999)

# print both the lists


print(mortage_payment)
print(new_list)

[4500, 3400, 7650, 1200]


[4500, 3400, 7650, 1200]
[4500, 3400, 7650, 1200, 9999]
[4500, 3400, 7650, 1200, 9999]

Remove A Value From A List

Removes a value from a list by passing the value as a parameters

In [21]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# Remove an element by value


mortage_payment.remove(3400)

# print the mortage_payment variable


print(mortage_payment)

[4500, 7650, 1200]

Remove A Value From A List

Removes a value from a list by passing the index position as a parameters

In [22]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# Remove an element by index position


mortage_payment.pop(1)

# print the mortage_payment variable


print(mortage_payment)

[4500, 7650, 1200]

Clear A List

Removes all elements from a list

In [23]: # create a list of values


mortage_payment = [4500, 3400, 7650, 1200]

# clear the list


mortage_payment.clear()

# print the mortage_payment variable


print(mortage_payment)

[]

[Link] Comprehensions
What Is A List Comprehension?
1. A list comprehension provides a concise way to create a list from another iterable
2. A list comprehension consist of [ ] containing the expression
3. Condition and loop can be used in a list comprehension
4. The result from a list comprehension is always a list

Problem Statement:

Q1. Add 7% GST to each value in the prices list and return the resulting values in a list prices= [10,
20, 30, 40, 50]

For loop solution

In [24]: prices = [10, 20, 30, 40, 50]

# delcare a blank list


outcome = []

# Iterate through the values of the list


for i in prices:
# add 7% to the value
value = i + (0.07 * i)

# append the value to the resultant list


[Link](value)

# print the resultant list


print(outcome)

[10.7, 21.4, 32.1, 42.8, 53.5]

List comprehension solution

In [25]: prices = [10, 20, 30, 40, 50]

# list comprehension
outcome = [(i + (0.07*i)) for i in prices]

# print the resultant list


print(outcome)

[10.7, 21.4, 32.1, 42.8, 53.5]

Q2. Square the even numbers from the quantity list quantity= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

For loop solution

In [26]: quantity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# delcare a blank list


outcome = []

# Iterate through the values of the list


for i in quantity:
# square the values if the value is even
if(i%2==0):
value = i**2
# append the value to the resultant list
[Link](value)

# print the resultant list


print(outcome)
[4, 16, 36, 64, 100]

List comprehension solution

In [27]: quantity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# list comprehension
outcome = [(i + (0.07*i)) for i in prices]

# print the resultant list


print(outcome)

[10.7, 21.4, 32.1, 42.8, 53.5]

Q3. Extract all the numbers from the string using list comprehension string = “Current assets is
worth 2450000 and current liabilities stands at 1230000”

For loop solution

In [28]: string = "Current assets is worth 2450000 \


and current liabilities stands at 1230000"

# split the string into words


list_of_words = [Link]()

# create a blank list


values = []

# Iterate through the list of words


for i in list_of_words:
# check if the word consists of digits only
if([Link]() == True):
# add the item to the values list
# convert to int before appending
[Link](int(i))

# print the resultant list


print(values)

[2450000, 1230000]

List comprehension solution

In [29]: string = "Current assets is worth 2450000 \


and current liabilities stands at 1230000"

# list comprehension
values = [int(i) for i in [Link]() if [Link]() == True]

# print the resultant list


print(values)

[2450000, 1230000]

Q4. Print the ROI for the items in the list as follows: 10% for term deposits, 5% for government
bonds and 15% for treasury bills.

For loop solution

In [31]: investments = \
['Term Dep', 'GSecBonds', 'TBills', 'TBills', 'GSecBonds']

# create a blank list


roi = []

# iterate through the list of investment items


for i in investments:
if(i == 'Term Dep'):
[Link](10)
elif(i == 'GSecBonds'):
[Link](5)
else:
[Link](15)

# print the resultant list


print(roi)

[10, 5, 15, 15, 5]

List comprehension solution

In [32]: investments = \
['Term Dep', 'GSecBonds', 'TBills', 'TBills', 'GSecBonds']

# list comprehension
roi = [10 if i == 'Term Dep' else 5 if i == 'GSecBonds' \
else 15 for i in investments]

# print the resultant list


print(roi)

[10, 5, 15, 15, 5]

10. Tuples Creation


Tuple

1. Container or collection object


2. Homogeneous or Heterogeneous sequence of elements
3. Can have duplicate values
4. Are immutable
5. Created using () parenthesis; Elements are separated by comma
6. Indexed & sliced using []

A few of the operations supported by tuple:

1. Loops & conditional statements


2. Membership operators - in, not in
3. Concatenation
4. Built-in functions like print(), type(), min(), max(), len()
5. Indexing and slicing using []

Creating a homogeneous tuple

In [35]: # Creating a homogeneous tuple


customers_age = (23, 34, 19, 56, 45, 37, 39)

# print the tuple


print(customers_age)

(23, 34, 19, 56, 45, 37, 39)

In [36]: # check the type of the object


type(customers_age)

Out[36]: tuple

Creating a heterogeneous tuple


In [38]: # Creating a heterogeneous tuple
financial_instruments = ("CPF", "Bonds", "Equities", 2300, 3400, 1700)

# print the tuple


print(financial_instruments)

('CPF', 'Bonds', 'Equities', 2300, 3400, 1700)

In [39]: # check the type of the object


type(financial_instruments)

Out[39]: tuple

It is NOT mandatory to use () parentheses to create a tuple

In [40]: # tuples can be created without using a round bracket


financial_instruments = "CPF", "Bonds", "Equities", 2300, 3400, 1700

# check the type of the object


type(financial_instruments)

Out[40]: tuple

11. Tuple Indexing


Using Index Position To Slice A Tuple

tuple_variable[positive index position]

In [ ]: # Create a tuple
stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# use an index position to extract an element from the tuple


# 0 gives us the 1st element
stock_prices[0]

In [42]: # use an index position to extract an element from the tuple


# 3 gives us the 4th element
stock_prices[3]

Out[42]: 28

tuple_variable[negative index position]

In [43]: # Create a tuple


stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# use an index position to extract an element from the tuple


# -1 gives us the last element
stock_prices[-1]

Out[43]: 43

In [44]: # use an index position to extract an element from the tuple


# -2 gives us the 2nd last element
stock_prices[-2]

Out[44]: 19

tuple_variable[start index : stop index]


In [45]: # Create a tuple
stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# start index as 0, end index as 5


# This will return the elements starting at index position 0
# till the index position 5-1 i.e. 4
stock_prices[0:5]

Out[45]: (23, 24, 27, 28, 32)

In [46]: # start index as 6, end index as 11


# This will return the elements starting at index position 6
# till the index position 11-1 i.e. 10
stock_prices[6:11]

Out[46]: (24, 46, 43, 31, 42)

tuple_variable[ : stop index]

In [47]: # Create a tuple


stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# start index as blank, end index as 5


# This will return the elements starting at index position 0
# till the index position 5-1 i.e. 4
stock_prices[:5]

Out[47]: (23, 24, 27, 28, 32)

tuple_variable[start index : stop index] Negetive

In [48]: # Create a tuple


stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# start index as -5, end index as -1


# this will return the elements starting at index position -5
# till the index position -1-1 i.e. -2
stock_prices[-5:-1]

Out[48]: (72, 82, 32, 19)

In [49]: # start index as -13, end index as -8


# this will return the elements starting at index position -13
# till the index position -8-1 i.e. -9
stock_prices[-13:-8]

Out[49]: (28, 32, 22, 24, 46)

tuple_variable[start index : ]

In [50]: # Create a tuple


stock_prices = (23, 24, 27, 28, 32, 22, 24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

# start index as 6, end index as blank


# This will return the elements starting at index position 6
# till the last index position
stock_prices[6:]

Out[50]: (24, 46, 43, 31, 42, 72, 82, 32, 19, 43)

12. Tuples Operations


Concatenating two tuples

In [51]: # create two tuples


prices_yesterday = (23, 45, 11, 98)
prices_today = (49, 66, 45)

# concatenate two tuples


prices_combined = prices_yesterday + prices_today

# print the tuple


print(prices_combined)

(23, 45, 11, 98, 49, 66, 45)

Creating nested tuples

In [52]: # Creating tuples


customer_1 = ("Jack", 23)
customer_2 = ("Tommy", 27)
customer_3 = ("Macy", 24)
customer_4 = ("Jennie", 19)

# Creating tuples of tuples


customers = (customer_1, customer_2, customer_3, customer_4)

# print the tuple


print(customers)

(('Jack', 23), ('Tommy', 27), ('Macy', 24), ('Jennie', 19))

In [53]: # extract the 2nd element from the tuple


customers[1]

Out[53]: ('Tommy', 27)

In [54]: # extract the 1st element from the 2nd element from the tuple
customers[1][0]

Out[54]: 'Tommy'

Repeating the tuple elements

In [55]: # create a tuple


stocks = ("AAPL", "ULVR", "BMW")

# number of times you wish to repeat the tuple


n = 3

# repeat the tuple elements n times using * operator


stocks * n

Out[55]: ('AAPL', 'ULVR', 'BMW', 'AAPL', 'ULVR', 'BMW', 'AAPL', 'ULVR', 'BMW')

Checking existence of an element using membership operators

In [56]: # create a tuple


stocks = ("AAPL", "ULVR", "BMW")

# check existence of ULVR in the tuple


"ULVR" in stocks

Out[56]: True

In [57]: # check existence of ULVR in the tuple


"ULVR" not in stocks
# False

# check existence of MSFT in the tuple


"MSFT" in stocks

Out[57]: False

In [58]: # check existence of MSFT in the tuple


"MSFT" not in stocks

Out[58]: True

Iterating through the elements of a tuple

In [59]: # create a tuple


stocks = ("AAPL", "ULVR", "BMW")

# using for loop iterate through each element


# print each element at each iteration
for i in stocks:
print(i)

AAPL
ULVR
BMW

13. Built-in Functions


len()

In [65]: # create a tuple


stocks = ("AAPL", "ULVR", "BMW")

# count the number of elements


len(stocks)

Out[65]: 3

max()

In [3]: # create a tuple


stock_prices = (23, 24, 27, 28, 32, 22)

# find the max value in the tuple


max(stock_prices)

Out[3]: 32

In [4]: # create a tuple


stocks = ("ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw")

# find the max value in the tuple


max(stocks)

Out[4]: 'ulvr'

min()

In [7]: # create a tuple


stock_prices = (23, 24, 27, 28, 32, 22)
# find the min value in the tuple
min(stock_prices)

Out[7]: 22

In [6]: # create a tuple


stocks = ("ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw")

# find the min value in the tuple


min(stocks)

Out[6]: 'AAPL'

The max() & min() cannot be used on a heterogeneous tuple

In [8]: # Creating a heterogeneous tuple


financial_instruments = ("CPF", "Bonds", "Equities", 2300, 3400, 1700)

# find the min value in the tuple


min(financial_instruments)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 5
2 financial_instruments = ("CPF", "Bonds", "Equities", 2300, 3400, 1700)
4 # find the min value in the tuple
----> 5 min(financial_instruments)

TypeError: '<' not supported between instances of 'int' and 'str'

The sorted() cannot be used on a heterogeneous tuple

In [9]: # Creating a heterogeneous tuple


financial_instruments = ("CPF", "Bonds", "Equities", 2300, 3400, 1700)
# sort the tuple
sorted(financial_instruments)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[9], line 4
2 financial_instruments = ("CPF", "Bonds", "Equities", 2300, 3400, 1700)
3 # sort the tuple
----> 4 sorted(financial_instruments)

TypeError: '<' not supported between instances of 'int' and 'str'

sorted()

In [10]: # create a tuple


stock_prices = (23, 24, 27, 28, 32, 22)

# sort the tuple


sorted(stock_prices)

Out[10]: [22, 23, 24, 27, 28, 32]

In [11]: # create a tuple


stocks = ("ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw")

# sort the tuple


sorted(stocks)

Out[11]: ['AAPL', 'BMW', 'ULVR', 'aapl', 'bmw', 'ulvr']


In [12]: # create a tuple
stocks = ("ULVR", "BMW", "aapl", "AAPL", "ulvr", "bmw")

# print the tuple


print(stocks)

('ULVR', 'BMW', 'aapl', 'AAPL', 'ulvr', 'bmw')

Use the del keyword to delete a tuple object

In [13]: # delete the tuple


del stocks

# try printing the tuple


print(stocks)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 5
2 del stocks
4 # try printing the tuple
----> 5 print(stocks)

NameError: name 'stocks' is not defined

Since a tuple is immutable, an element cannot be deleted from it

In [14]: # create a tuple


stock_prices = (23, 24, 27, 28, 32, 22)

# delete a few elements from a tuple


del stock_prices[1:4]

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[14], line 5
2 stock_prices = (23, 24, 27, 28, 32, 22)
4 # delete a few elements from a tuple
----> 5 del stock_prices[1:4]

TypeError: 'tuple' object does not support item deletion

In [ ]:

You might also like