0% found this document useful (0 votes)
128 views

ALGORITHMIC THINKING WITH PYTHON Mod 3

Uploaded by

rensi
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)
128 views

ALGORITHMIC THINKING WITH PYTHON Mod 3

Uploaded by

rensi
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
You are on page 1/ 78

ALGORITHMIC THINKING WITH

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).

DECOMPOSITION AND MODULARIZATION* :- Problem decomposition


as a strategy for solving complex problems, Modularization, Motivation for
modularization, Defining and using functions in Python, Functions with
multiple return values.

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 syntax of if statement in Python is:


if <condition>:
# body of if statement
► Example
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.') Following the logical condition, a colon : is required.

print(‘Statements outside if')

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

► An if statement can have an optional else clause.


► The syntax of if...else statement is:
if <condition>:
# block of code if condition is True
else:
# block of code if condition is False
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

► The process of testing several conditions and responding accordingly can be


described in code by a multi-way selection statement.

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

► Marks < 60: F


Exercises

► 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.

► If the year is divisible by 4 but not 100, it is a leap year.


Exercises

► Write a Python program that checks the strength of a password entered by


the user. The program should categorize the password as:
► "Weak" if it is less than 6 characters.

► "Medium" if it is between 6 and 10 characters.

► "Strong" if it is more than 10 characters.


Repetition statements

► There are two types of loops—those that repeat an action a predefined


number of times (definite iteration) and those that perform the action
until the program determines that it needs to stop (indefinite
iteration).

► 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.

► The range() function can be represented in three different ways, or you


can think of them as three range() parameters:
► range(stop_value): starting from 0 by default, and increments by 1 (by default) upto
stop_value

► range(start_value, stop_value): This generates thesequence based on the start and


stop value increments by 1 (by default).

► range(start_value, stop_value, step_size): It generates the sequence by


incrementing the start value using the step size until it reaches the stop value.
Python range() Function

► Create a sequence of numbers from 0 to 5, and print each item in the


sequence:

# Solution
for i in range(6): # range(6) generates numbers from 0 to 5
print(i)

► Create a sequence of numbers from 3 to 5, and print each item in


the sequence:
# Solution
for i in range(3,6): # range(3, 6) generates numbers from 3 to 5
print(i)
Python range() Function

► Create a sequence of numbers from 3 to 19, but increment by 2


instead of 1:

# Solution
for i in range(3,20,2): #range(start, stop, step)
print(i)
Loops that Count Down

► When the step argument is a negative number, the range function


generates a sequence of numbers from the first argument down to the
second argument plus 1

>>> for count in range(10, 0, -1):


print(count, end = " ")
10 9 8 7 6 5 4 3 2 1
Exercises

► Write the outputs of the following loops:


• for count in range(5):
print(count + 1, end = " ")

• for count in range(1, 4):


print(count, end = " ")

• for count in range(1, 6, 2):


print(count, end = " ")

• for count in range(6, 1, –1):


print(count, end = " ")
Conditional Iteration: The while Loop

► The Structure and behaviour of a while Loop

while <condition>:
<sequence of statements>
Count Control with a while Loop

# Summation with a for loop # Summation with a while loop


theSum = 0 theSum = 0
for count in range(1, 100001): count = 1
theSum += count while count <= 100000:
print(theSum) theSum += count
count += 1
print(theSum)
Loop control statements

► Python provides three loop control statements that control the


flow of execution in a loop.
► break statement
► continue statement
► pass statement
Loop control statements - break

► 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

Output: First number greater than 5 is: 6


Loop control statements - continue

► 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

for num in range(1, 10):


if num % 2 == 0:
continue # Skip the rest of the loop for even numbers
print(num)
Loop control statements - pass

► The pass statement in Python is a placeholder used when a statement is


required syntactically, but no action is needed.
► It allows you to write empty blocks of code without causing an error.
► The pass statement does nothing—it simply allows the
program to continue running.
Loop control statements - pass

# Example: Function to check if a number is positive or negative and do nothing if it


is zero
num=int(input(“Enter a number”))
if num > 0:
print(f"{num} is positive.")
elif num < 0:
print(f"{num} is negative.")
else:
pass # Placeholder for when the number is zero; we will implement it later
print("This message will always print after the condition checks.")

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 print numbers from 1 to 10


using a while loop.
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

► Python’s random module supports several ways to do this, but the


easiest is to call the function random.randint with two integer
arguments.

>>> import random


>>> for roll in range(10):
print(random.randint(1, 6), end = " ")
2 4 6 4 3 2 3 6 2 2
Guessing game.

At start-up, the user enters the smallest number and the


largest number in the range. The computer then selects
a number from this range. On each pass through
the loop, the user enters a number to attempt to
guess the number selected by the computer. The
program responds by saying “You’ve got it,” “Too large,
try again,” or “Too small, try again.” When the user finally
guesses the correct number, the program congratulates
him and tells him the total number of guesses.

Credits :Prof Sarju S, SJCET


Guessing game.
import random
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess:
")) if userNumber < myNumber:
print("Too small!")
elif userNumber > myNumber:
print("Too large!")
else:
print("Congratulations! You've got it in", count,"tries!")
break

Page 35
LIST
List
A list is an ordered collection of values, with each value being identified by a
unique index.

The values within a list are referred to as elements.

The elements in a list can be of any data type.

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 [ ]

Eg: >> empty_list = [ ] # creates an empty set and assigns it to

variable empty_list

2. List with elements : by playing them inside the square brackets

Eg: bum = [1, 2 , 3 , 4 , 5 ]

mixed = [ 4, [5, 6], ‘string’ , True]

The elements need not be of the same type.


One of the element of the list can be another
Create List
3. List comprehensions : they provide a shorter syntax to generate lists from
existing iterables like lists, tuples, strings, or ranges,
Eg: >> squares = [ x**2 for x in range(5) ]
output
[0, 1, 4, 9, 16]
a condition can also be added so that only certain values that satisfy the
condition atre included in the list
Eg: >> even_squares = [ x**2 for x in range(10) if x % 2 == 0]
output
[0, 4, 16, 36, 64]
Create list
4. Using range and list functions

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

- a = [ 11, 22, 33, 44, 55]

-5 -4 -3 -2 -1
List Operations
2. Slicing :extract a subset of elements

>> a = [ 99, 88, 77, 66, 55]

>> a[1:3]

output

[ 88, 77]

>> a[:2]

output

[99, 88]

>>a[2:]

output

[77, 66, 55]


3. List traversal

using for loop using while loop

a = [ 99, 88, 77, 66, 55] a = [ 99, 88, 77, 66, 55]

for i in a: i=0

print(a) while i<len(a):

print(a[i])

i=i+1
Modifying Lists

a = [ 99, 88, 77, 66, 55]

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

b=[99,88,77,66,55, 99,88,77,66,55, 99,88,77,66,55]


len() function takes a list as a parameter and returns the number of elements in the list
>> x = [ 1, 2, 'joe', 99]
>> print(len(x))
output
4
len() tells us the number of elements of any set or sequence (such as a string...)
>> greet = 'Hello Bob'
>> print(len(greet))
output
9
Testing Membership in a list with ‘in’ and ‘not in’
>> a =[99,88,77,66,55]

>> print(77 in a) print(66 not in a)

output output

True False

>> print(50 in a) print(90 not in a)

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]

print(a < b) print(c < b)

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]

print(b > a) print(c > b)

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]

print(a < = b) print(c < = b)

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]

print(b >= a) print(c > = b)

output output

True False
Method Description

index() Returns the index of the first occurrence of the specified value.

insert() Inserts a specified value at a specified position (index) in the list.

append() Adds a value to the end of the list.

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).

reverse() Reverses the elements of the list in place.


Method Description Example

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.

insert() ►Inserts an element at a specified numbers = [10, 20, 30, 40,


position. 50]
# Insert 25 at index 2
►Syntax: list.insert(index,
numbers.insert(2, 25)
value) print(numbers)
# Output: [10, 20, 25, 30,
40,50]
Method Description Example

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]

extend() ►Extends the list by appending numbers = [10, 20, 30]


elements from # Adds all elements from
another list (or any iterable). the second list
numbers.extend([40, 50,
►Syntax: list.extend(iterable)
60]) print(numbers)
# Output: [10, 20, 30, 40,
50,60]
Method Description Example

remove() ►Removes the first numbers = [10, 20, 30, 40,


occurrence of a specified 30]
value. # Removes the first
occurrence of 30
►Syntax :
numbers.remove(30)
list.remove(value) print(numbers)
►Raises : ValueError if the # Output: [10, 20, 40, 30]
specified value is not found.

count() ►Returns the number of numbers = [10, 20, 30, 10,


20, 10]
occurrences of a specified
print(numbers.count(10))
value.
# Output: 3
►Syntax:
Method Description Example

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

>> string1 = “Hello World”

2. Double quotes string

>> string2 = “Python Class”

3. Triple quote for Multiline string

>>string3 = “””this is a mutliline string, extending

over two lines”””


Accessing String
1. Indexing: using square brackets
my_string =”Hello”
print(my_string[1])
output
‘e’
Note: Negative index
print(my_string[=1])
output
‘o’
Slicing
syntax string[start:end:step]

eg:
my_string =”Hello”
print(my_string[1:3])
output
el
Slicing
syntax string[start:end:step]
eg:

my_string =”Hello, World”


eg:
print(my_string[::2])
my_string =”Hello, World”
print(my_string[1:11:2]) output
output Hlo ol
el,Wr
Operators
1. Concatenation : + operator
2. Repetition : + operator
String Operations
1. String Length : len()
2. Lowercase conversion : lower()
3. Uppercase conversion : upper()
4. Remove leading and trailing whitespace : strip()
5. Splitting a string using a delimiter :” split(“delimiter”)
6. Joining into a single string : join()
7. Finding a substring: returns the index of first occurrence of a substring
8. Replace occurrence of a substring with another substring :replace()
9. Finding alphabet : isalpha()
String Operations
10. starting prefix : startwith()
11. ending prefix : endswith()
12. Counting : count()

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

split() ►splitsa single string into string1 = “apple,orange,grape”


substring based on a # Reverses the list
common delimiter. string2 =
string1.split(“,”)
►output is a string
print(string2)
►Syntax : # Output:
string.split() [“apple”,”orange”,”grape”]
References

► https://www.freecodecamp.org/news/python-range-function-example/
► https://www.w3schools.com/python/ref_func_range.asp

Page 78

You might also like