ALGORITHMIC THINKING WITH PYTHON Mod 3
ALGORITHMIC THINKING WITH PYTHON Mod 3
PYTHON
Rensi Sam Mathew
Syllabus- Module 3
SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop,range, while loop.
Sequence data types in Python - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).
RECURSION:- Recursion Defined, Reasons for using Recursion, The Call Stack,
Recursion and the Stack, Avoiding Circularity in Recursion, Sample problems -
Finding the nth Fibonacci number, greatest common divisor of two positive integers
the factorial of a positive integer, adding two positive integers, the sum of digits of a
positive number **.
* The idea should be introduced and demonstrated using Merge sort, the problem of returning the top three integers from a list of
n>=3 integers as examples. (Not to be limited to these two exercises. More can be worked out if time permits).
** Not to be limited to these exercises. More can be worked out if time permits.
SELECTION AND ITERATION USING PYTHON
Page 3
if and if-else Statements
The body of the if must be indented and every line in this section of code must be
indented the same number of spaces. By convention, four space indentation
is used in Python. Most Python code editors automatically indent code after if-statements
if and if-else Statements
► Example
number = 10
The keyword else should be on its own line and at the same
if number > 0: indentation level as the if statement it belongs to. The else must be
followed by a colon (:). Any code inside the else block should be
print('Positive number') indented by the same amount.
else:
print('Negative number')
print('This statement is always executed')
Multi-Way if Statements
Multi-Way if Statements
if <condition1>:
#block 1 In Python, the elif keyword is used to implement the "else if"
elif <condition2>: statement. It allows you to check multiple conditions after an
if statement, and it stands for "else if."
#block 2
else:
#block 3
Multi-Way if Statements
► Example
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Exercises
► Write a Python program that prompts the user to enter a number and
checks if the number is even or odd. If the number is even, print "The
number is even." If the number is odd, print "The number is odd."
Exercises
► Write a Python program that takes two numbers as input from the user and
prints the larger of the two numbers. If both numbers are equal, print "The
numbers are equal."
Page 11
Exercises
► Write a Python program that takes a student's marks as input and prints
their grade based on the following criteria:
► Marks >= 90: A
► Marks 80–89: B
► Marks 70–79: C
► Marks 60–69: D
► Write a Python program that takes a single character as input from the user
and checks if it is a vowel or a consonant. If the input is not an alphabetic
character, print "Invalid input."
Exercises
► Write a Python program that takes a year as input and checks if the year is a
leap year.
► If the year is divisible by 400, it is a leap year.
► If the year is divisible by 100 but not 400, it is not a leap year.
► Python’s for loop, the control statement that most easily supports
definite iteration.
for <variable> in range(<an integer expression>): Loop header
<statement-1>.
.
Loop body
.
<statement-n> The colon (:) ends the loop header
Python range() Function
► The range() function returns a sequence of numbers, mainly used when working
with for loops.
# Solution
for i in range(6): # range(6) generates numbers from 0 to 5
print(i)
# Solution
for i in range(3,20,2): #range(start, stop, step)
print(i)
Loops that Count Down
while <condition>:
<sequence of statements>
Count Control with a while Loop
► The break statement is used to immediately exit a loop, even if the loop condition
is still true.
► When a break is encountered inside a loop, the control jumps out of the loop and
the program continues with the next statement following the loop.
# Example: Find the first number greater than 5 and stop the loop
for num in range(10):
if num > 5:
print(f"First number greater than 5 is: {num}")
break # Exit the loop when the first number greater than 5 is found
► The continue statement in Python is used to skip the rest of the code inside the
current loop iteration and move on to the next iteration of the loop.
► Unlike break, which exits the loop completely, continue only skips the current
iteration and allows the loop to proceed.
# Example: Skip printing even numbers and only print odd numbers
Enter a number 10
10 is positive.
Output This message will always print after the condition checks.
Enter a number0
This message will always print after the condition checks.
Difference between pass and continue
► Functionality
► pass: Does nothing; serves as a placeholder.
► continue: Skips to the next iteration of the loop.
► Use Case
► pass: Useful when you need a block of code but haven't implemented it yet.
► continue: Useful when you want to ignore certain conditions within a loop and
proceed with the next iteration.
► Behaviour
► pass: The program continues executing subsequent lines of code.
► continue: The program jumps to the next iteration of the loop, skipping the remaining code in
the current iteration.
Exercises
► Write a Python program to calculate the sum of the first N natural numbers
using a for loop. The user will input N.
Exercises
► Write a Python program that takes a number as input from the user and
finds the factorial of that number using a while loop.
Random Numbers
Page 35
LIST
List
A list is an ordered collection of values, with each value being identified by a
unique index.
They are mutable ie. the list can be modified by reassigning the elements.
Lists are defined using square bracket [ ], with each element separated by a
comma.
Create List
1. Empty List : an empty list can be created using empty square bracket [ ]
variable empty_list
eg:
>> a= list(range(6)
>> b= list(range(11,15))
>> c = list(range(20,30,3)
List Operations
1. Accessing Elements
- use zero-based indexing :index starts with zero
- negative indices count from the end of the string
- Eg : a= [ 11, 22, 33, 44, 55]
0 1 2 3 4
-5 -4 -3 -2 -1
List Operations
2. Slicing :extract a subset of elements
>> a[1:3]
output
[ 88, 77]
>> a[:2]
output
[99, 88]
>>a[2:]
output
a = [ 99, 88, 77, 66, 55] a = [ 99, 88, 77, 66, 55]
for i in a: i=0
print(a[i])
i=i+1
Modifying Lists
a[3]= 100
a= [99,88,77,100,55]
a[-1]=0
a= [99,88,77,100,0]
Adding new elements
Concatenation + operator
a = [99,88,77,66,55]
new_list = a +[11,22,33]
print(new_list)
new_list =[ 99,88,77,66,55,11,22,33]
append method : add a single element
a=[99,88,77,66,55]
a.append(11)
print(a)
output
a=[99,88,77,66,55,11]
extend method : add multiple elements
a=[99,88,77,66,55]
a.extend([11,22])
print(a)
output
a=[99,88,77,66,55,11,22]
insert method : insert at a specific location
a=[99,88,77,66,55]
a.insert(1,10)
print(a)
output
a=[99,10, 88,77,66,55]
repetition method : using * operator
a=[99,88,77,66,55]
b=a*3
print(b)
output
output output
True False
output output
False True
Comparison Operator
a. Equality (==), Inequality (!=) b. Inequality (!=)
a=[1, 2, 3] a=[1, 2, 3]
b=[1, 2, 3] b=[1, 2, 3]
c=[1, 2] c=[1, 2]
print(a==b) print(a!=c)
output output
True True
Comparison Operators
c. Less than (<) c. Less than (<)
a=[1, 2, 3] a=[1, 2, 3]
b=[1, 2, 4] b=[1, 2, 4]
c=[1, 2] c=[1, 2]
output output
True True
Comparison Operators
d. Greater than (>) c. Greater than (>)
a=[1, 2, 3] a=[1, 2, 3]
b=[1, 2, 4] b=[1, 2, 4]
c=[1, 2] c=[1, 2]
output output
True False
Comparison Operators
e. Less than or equal to ( < = ) e. Less than or equal to (<=)
a=[1, 2, 3] a=[1, 2, 3]
b=[1, 2, 4] b=[1, 2, 4]
c=[1, 2] c=[1, 2]
output output
True True
Comparison Operators
f. Greater than (>) f. Greater than (>)
a=[1, 2, 3] a=[1, 2, 3]
b=[1, 2, 3] b=[1, 2, 4]
c=[1, 2] c=[1, 2]
output output
True False
Method Description
index() Returns the index of the first occurrence of the specified value.
extend() Extends the list by appending elements from another iterable (list, tuple,
etc.).
remove() Removes the first occurrence of the specified value from the list.
pop() Removes and returns the element at a specified index (default is the last
element).
count() Returns the number of times a specified value appears in the list.
sort() Sorts the list in ascending order (can be customized to sort in descending
order).
index() ►Returns the index of the first numbers = [10, 20, 30, 40,
occurrence of a specified value. 50]
print(numbers.index(30))
►Syntax: list.index(value) # Output: 2
►Raises: ValueError if the specified
value is not found.
append() ►Adds an element at the end of the list. numbers = [10, 20, 30]
# Adds 40 to the end of
►Syntax : list.append(value)
the list
numbers.append(40)
print(numbers)
# Output: [10, 20, 30, 40]
pop() ►Removes and returns numbers = [10, 20, 30, 40, 50]
the element at # Remove and return the element at
a specified position. index 1
removed_element = numbers.pop(1)
►If no index is provided,
print(removed_element)
removes and returns the
# Output: 20 print(numbers)
last element.
# Output: [10, 30, 40, 50]
►Syntax: # Remove and return the last
list.pop(index) element
(index removed_element = numbers.pop()
is optional) print(removed_element)
# Output: 50 print(numbers) #
Output: [10, 30, 40]
Method Description Example
sort() ►Sorts the list in numbers = [50, 10, 40, 30, 20]
ascending order by # Sorts in ascending
default (can be order
customized to sort in numbers.sort()
descending order). print(numbers)
# Output: [10, 20, 30, 40, 50]
►Syntax :
# Sort in descending order
list.sort(reverse=Fal
numbers.sort(reverse=True)
se) print(numbers)
# Output: [50, 40, 30, 20, 10]
Method Description Example
reverse() ►Reverses the elements of numbers = [10, 20, 30, 40, 50]
the list in place. # Reverses the list
numbers.reverse()
►Syntax :
print(numbers)
list.reverse()
# Output: [50, 40, 30, 20, 10]
Operators
1. + operator : concatenation
eg:
>> list1= [ “Apple”, “Orange”, “Lemon”]
>> list2=[“Grape”, “Guava”, “Plum”]
>> list3 = list1+list2
>> print(list3)
output
[ “Apple”, “Orange”, “Lemon”, “Grape”, “Guava”, “Plum”]
Operators
2. * operator : repetition
Eg:
>> list1= [ “Apple”, “Orange”, “Lemon”]
>> list2=list1*3
print(list2)
output
[ “Apple”, “Orange”, “Lemon”, “Apple”, “Orange”, “Lemon”,“Apple”, “Orange”,
“Lemon”]
Deleting elements in a list
1. remove() 4. clear()
2. pop()
eg:
3. del
>>list1= [ “Apple”, “Orange”, “Lemon”]
eg:
>>list1.clear()
>>list1= [ “Apple”, “Orange”, “Lemon”]
>>print(list1)
>>del list1[1]
output
>>print(list1)
list1=[]
output
list1=[“Apple”, “Lemon”]
List Aliasing : assign List Cloning : separate copy
org_list=[1,2,3] org_list=[1,2,3]
alias_list = org_list alias_list = org_list[:]
alias_list[0]=10
alias_list[0]=10
print(org_list)
print(org_list)
print(alias_list)
print(alias_list)
output
output
[10,2,3]
[10,2,3] [1,2,3]
[10,2,3]
STRING
Create String
1. Single quoted string
eg:
my_string =”Hello”
print(my_string[1:3])
output
el
Slicing
syntax string[start:end:step]
eg:
Formatting String
● %operator
● str.format()
● f-string
Converting strings↔lists
1.convert list to string 2. convert string to list
s=’hello’ list1=[‘h’, ‘e’, ‘l’, ’l’, ’o’]
list1=list(s) s=’’.join(list1)
print(list1) print(s)
output output
[‘h’, ‘e’, ‘l’, ’l’, ’o’] hello
Method Description Example
► https://www.freecodecamp.org/news/python-range-function-example/
► https://www.w3schools.com/python/ref_func_range.asp
Page 78