Module 2
Decision Making
Topic to be covered
•Decision Making
•Functions
•Strings
Conditional Statement(If Statement)
• Conditional statements in Python are used to execute certain blocks of code
based on specific conditions. These statements help control the flow of a
program, making it behave differently in different situations.
If Statement
If statement is the simplest form of a conditional statement. It executes a block of code
if the given condition is true.
Syntax
if test_expression:
True statements block
rest of program statements
Cont….
• The if statement consistes of a if keyword followed by a
test_expression. The test_expression evaluates to a Boolean value.
# Simple program to check if a number is
positive
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
Stop
If-else Statement
• In Python, the if...else statement allows you to execute one block of
code if a condition is true, and another block if the condition is false
• Syntax
if condition:
# block of code executed if condition is true
else:
# block of code executed if condition is false
# Write a program to demonstrate to check a
number is even or odd
number = int(input("Enter a number: "))
if number % 2 == 0:
print(number, "is Even")
else:
print(number, "is Odd")
# Program to check whether a given year is a leap year
or not
year = int(input("Enter a year: "))
# Leap year conditions:
# 1. Year is divisible by 400 → Leap year
# 2. Year is divisible by 4 but not by 100 → Leap year
# Otherwise → Not a leap year
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print(year, "is a Leap Year")
else:
print(year, "is NOT a Leap Year")
Nested conditional statements
• Nested means enclosing one conditional construct in another.
Syntax if condition1:
if condition2:
Statement 1
else:
Statement 2
else
if(test_Expr):
Statement 3
else:
statement 4
if-elif-else Statement
•The if-elif-else statement is used when you have multiple conditions to test.
•Python checks conditions from top to bottom:
[Link] the first if condition is True, its block runs and the rest are skipped.
[Link] not, it checks the next elif.
[Link] none of the if or elif conditions are true, the else block runs (if present).
Syntax:
if condition1:
# Block A (executes if condition1 is true)
elif condition2:
# Block B (executes if condition1 is false and condition2 is true)
elif condition3:
# Block C (executes if above conditions are false and condition3 is true)
else:
# Block D (executes if all conditions are false)
# Write a python program for grade classification
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
elif marks >= 40:
print("Grade D")
else:
print("Fail")
# Program to find the largest of two numbers
# Input two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Compare numbers
if num1 > num2:
print("The largest number is:", num1)
elif num2 > num1:
print("The largest number is:", num2)
else:
print("Both numbers are equal.")
# Program to find the largest of three numbers
# Input three numbers using if-else only
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Compare numbers using only if-else
if num1 > num2:
if num1 > num3:
largest = num1
else:
largest = num3
else:
if num2 > num3:
largest = num2
else:
largest = num3
print("The largest number is:", largest)
If and match-case
• A Python match-case statement takes an expression and compares its value to
successive patterns given as one or more case blocks.
• Only the first pattern that matches gets executed. It is also possible to extract
components (sequence elements or object attributes) from the value
into variables.
• With the release of Python 3.10, a pattern matching technique
called match-case has been introduced, which is similar to the switch-case
Syntax:
match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2 ...
case 'pattern n' : statement n
Iteration
• Iteration means repeating a set of instructions multiple times until a
condition is met or until all elements in a sequence are processed.
• In Python, iteration allows you to process items in lists, strings,
dictionaries, or even numbers in a range
Types of Iteration
• For Loop
• This is when you know how many times you want to loop, or you want to loop over
every element of a collection.
• While Loop
• This is when you don’t know in advance how many times to loop.
The loop continues until a condition becomes false.
For Loop
• A for loop is used for definite iteration, which means repeating a block of code
a fixed number of times or for each element in a sequence.
• It is commonly used when we know how many times the loop should run.
Syntax
for variable in sequence:
# code block
Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
Output
I like apple
I like banana
I like cherry
For value in sequence
Statement1
Statement 2
.
Statement n
Rest of the program
statement
Updating variables
• Updating a variable means changing its value during the execution of a
program. Usually, you increase or decrease its value using arithmetic
operations.
Example
count = 0 # initial value
count = count + 1 # update: increase by 1
print(count)
Range() function
• The range() function in Python generates an immutable sequence of numbers. It is
commonly used for iterating a specific number of times in for loops. The numbers
generated are integers and can be customized with start, stop, and step arguments.
syntax
range(stop)
range(start, stop)
range(start, stop, step)
Parameters:
stop (required): The sequence will stop before this number. Due to zero-based indexing,
the last number generated will be stop - 1.
start (optional): The starting number of the sequence. If omitted, it defaults to 0.
step (optional): The increment (or decrement) between consecutive numbers in the
sequence. If omitted, it defaults to 1. A negative step can be used to generate numbers
in reverse order.
• range(stop): Generates numbers from 0 up to (but not including) stop.
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
• range(start, stop): Generates numbers from start up to (but not
including) stop.
for i in range(2, 7):
print(i)
• range(start, stop, step): Generates numbers from start up to
# Output: 2, 3, 4, 5, 6
(but not including) stop, with an increment of step.
for i in range(1, 10, 2):
print(i)
# Output: 1, 3, 5, 7, 9
• Negative step (counting backward).
for i in range(10, 0, -1):
print(i)
# Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Using range()
• The range() function generates a Example
sequence of numbers. for char in "PYTHON":
print(char)
Example: Output
P
for i in range(1, 6): Y
print(i) T
H
Output O
1 N
2
3
4
5
range(1, 6) gives numbers from 1 to 5
(stop is excluded).
The syntax of a for loop with the range()
function
C3, Slide 26
A for loop that prints the numbers 0 through 4
C3, Slide 27
#Write a python program to print the Sum of First N
Natural Numbers
n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total =total+ i
print("Sum =", total)
#write a python program to print the multiplication
table of a number
OUTPUT
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
#Write a python program to print even numbers
between 1 and 20 output
for i in range(2, 21, 2):
print(i)
#Write a python program to find the factorial of a
number
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial =", fact)
OUTPUT
# Program to generate Fibonacci series
n = int(input("Enter the number of terms: "))
# Step 2: Initialize the first two Fibonacci numbers
a=0
b=1
print("Fibonacci series:")
print(a, b,end=" ")
for i in range(2, n):
c=a+b
print(c, end=" ")
a=b
b=c
The break Statement
•The break statement terminates the for loop immediately before it
loops through all the items.
Example
languages = ['Swift', 'Python', 'Go', 'C++']
for lang in languages:
if lang == 'Go':
break
print(lang)
OUTPUT
Swift
Python
The Continue statement
• The continue statement skips the current iteration of the loop and continues
with the next iteration.
For example,
languages = ['Swift', 'Python', 'Go', 'C++']
for lang in languages:
if lang == 'Go':
continue
print(lang)
OUTPUT
Swift
Python Note:Here, when lang is equal to 'Go’,
the continue statement executes, which skips the
C++ remaining code inside the loop for that iteration.
While Loop
• A while loop in Python repeatedly executes a block of code as long as a
specified condition remains True.
• It is a form of indefinite iteration, meaning the number of times the loop will
run is not necessarily known in advance.
• The body of the loop should change the value of one or more variables so that
eventually the condition becomes false and the loop terminates.
• Otherwise the loop will repeat forever, which is called an infinite loop.
Syntax
while <condition>:
# Code to be executed repeatedly
# Statements
# Program to print n natural numbers using while loop
n = int(input("Enter the value of n: "))
i=1
print("The first", n, "natural numbers are:")
while i <= n:
print(i)
i += 1
• Output
Enter the value of n: 5
The first 5 natural numbers are:
1
2
3
4
5
# Find the sum of first n natural numbers
n = int(input("Enter a number: "))
i=1
sum = 0
while i <= n:
sum += i
i += 1
print("Sum of first", n, "natural numbers is:", sum)
• Output
Enter a number: 5
Sum of first 5 natural numbers is: 15
#Print even numbers between 1 and n
n = int(input("Enter a number: "))
i=2
while i <= n:
print(i)
i =i+ 2
•Output
Enter a number: 10
2
4
6
8
10
# Write a python program to Reverse a given number
num = int(input("Enter a number: "))
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num =num// 10
print("Reversed number:", rev)
• Output
Enter a number: 1234
Reversed number: 4321
#Program to check a given number is palindrome
or not
num = int(input("Enter a number: "))
temp = num
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
if temp == rev:
print("It is a palindrome number")
else:
print("It is not a palindrome number")
Break Statement with while Loop
• A while loop in Python repeatedly executes a block of code as long as a
specified condition is True. The break statement can be used within a
while loop to exit the loop based on dynamic conditions that may not
be known beforehand.
#Write a python program to check a given number is a
prime or not.
num = int(input("Enter a number: ")) Output
if num <= 1:
print(num, "is not a prime number")
else:
i=2
while i <= num // 2:
if num % i == 0:
print(num, "is not a prime number")
break
i += 1
else:
print(num, "is a prime number")
Continue in while loop
• The continue statement in a Python while loop is used to skip the remaining code
within the current iteration of the loop and proceed directly to the next iteration.
• When continue is encountered, the program immediately jumps back to the
beginning of the while loop, re-evaluating the loop's condition.
# Program to demonstrate while loop with break, continue, and if-else
count = 1 # initialization
while count <= 10:
if count == 5:
print("Count is 5, skipping this number using continue.")
count += 1
continue # skips the rest of the loop when count == 5
if count == 8:
print("Count reached 8, breaking the loop.") Output
break # stops the loop completely
if count % 2 == 0:
print(count, "is even.")
else:
print(count, "is odd.")
count += 1 # increment
User- defined Functions
• Intro
• Python enables user to define their own functions. These functions are known as user
defined function.
• A function is a named block of organized, reusable code designed to perform a specific
task.
• Grouping of code that can be invoked by a name as and when required as many as time
required.
• Python Functions are a block of statements that does a specific task.
• The idea is to put some commonly or repeatedly done task together and make a function
so that instead of writing the same code again and again for different inputs,
• There can be any number of statements inside the function, but they have to be
indented from the def
Advantage of functions
• They make your code modular rather than monolithic. It is easy for debugging.
• These function are reusable in nature and can be invoked any number of times.
• A user defined function can be developed independently by developers.
• A program divided into functions is easier to understand.
• A program divided into functions is easier to maintain.
What are actual parameter and formal parameter
• "formal parameters" and "actual parameters" distinguish between how
arguments are defined within a function and how they are provided during a
function call.
• Formal Parameters:
• Formal parameters are the variables listed inside the parentheses in a
function's definition. They act as placeholders for the values that the function
expects to receive when it is called. These parameters define the names and
the order in which the function will accept input.
• Actual Parameters (or Arguments):
• Actual parameters, also known as arguments, are the actual values, variables,
or expressions that are passed to a function when it is called. These values are
assigned to the corresponding formal parameters within the function's scope
# Function definition
def add_numbers(a, b): # 'a' and 'b' are formal arguments
sum = a + b
print("The sum is:", sum)
# Function call
add_numbers(5, 10) # 5 and 10 are actual arguments
Flow of execution
• A function is defined before its first use, we have to know the order in which
statements are executed, which is called the flow of execution.
• Execution always begins at the first statement of the program. Statements
are executed one at a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the
function is called.
• We can define one function inside another. In this case, the inner definition
isn’t executed until the outer function is called.
• The flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Functions that require arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
• Example:
def add_numbers(a, b):
sum = a + b
print('Sum:', sum)
add_numbers(2, 3)
# Output: Sum: 5
Variable Scope
• Variable scope in Python defines the region of a program where a variable is
accessible
Local Scope (L):Variables defined inside a function are local to that function.
• They are created when the function is called and destroyed when the function
finishes execution.
• You cannot access it outside the function.
Global Variables
• A global variable is declared outside of all functions or blocks.
• It can be accessed anywhere in the program — both inside and outside
functions.
• But if you try to change its value inside a function without telling Python it’s
global, Python will treat it as a new local variable.
Example
x = 10 # Global variable
def display():
print("Inside function, x =", x)
display()
print("Outside function, x =", x)
Function Argument with Default Values
• In Python, we can provide default values to function arguments.
• We use the = operator to provide default values.
def add_numbers( a = 7, b = 8): Output
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
Calling Function
• A function call is a statement that executes the function object. When
we call a user defined function, the program control jumps to the
function definition and executes statements present in the function’s
body.
• a user defined function in different ways. They are:
• inside another function
• through the main segment of the program
• directly from the Python prompt.
Calling function
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Calling the function with an argument
greet_person("Bob") # Calling the function again with a different
argument
Returning Values from a Function:
• In Python, a function can return a value using the return statement. This allows
the function to send a result back to the part of the code that called it.
• Here's how it works: Using the return keyword.
• The return keyword is placed inside the function, followed by the value or
expression you want to send back.
# Function to find factorial of a number using function
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
# Main part of the program
num = int(input("Enter a number: "))
# Function call
result = factorial(num)
# Display result
print("Factorial of", num, "is:", result)
Output
Enter a number: 5
Factorial of 5 is: 120
# Function to check whether a number is odd
def is_odd(num):
if num % 2 != 0:
return True
else:
return False
# Main part of the program
n = int(input("Enter a number: "))
# Function call and result display
if is_odd(n):
print(n, "is an Odd Number.")
else:
print(n, "is Not an Odd Number.")
# Function to check if a number is positive or negative
def check_number(num):
if num > 0:
print(num, "is a Positive Number.")
elif num < 0:
print(num, "is a Negative Number.")
else:
print("The number is Zero.")
# Main part of the program
n = float(input("Enter a number: "))
# Function call
check_number(n)
Returning Value
• A return statement is used to end the execution of the function call and it
"returns" the value of the expression following the return keyword to the
caller.
• The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is returned.
• A return statement is overall used to invoke a function so that the passed
statements can be executed.
• Syntax
# A function that calculates and returns a value
def add(a, b):
result = a + b
return result
The value returned from the function is stored in a variable
sum_value = add(5, 3)
print(sum_value)
# Outputs: 8
#Find the largest of 2 number using function.
def largest(a, b):
if a > b:
return a
else:
return b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Largest number is", largest(x, y))
Recursion
• A recursive function is a function that calls itself one or more times
until it encounters a base case which prevents further recusion.
• A base is case which leads to problrm solution without further
recursion.
• If base case is missing the recursive calls may lead to infinity.
How to calculate the factorial of a number
Murach's Python © 2016, Mike Murach & Associates, Inc.
Programming C13, Slide 66
A recursive function that calculates the factorial of a
number
Murach's Python © 2016, Mike Murach & Associates, Inc.
Programming C13, Slide 67
#Write a python program to compute factorial of number
using recursion
def factorial(n):
if n == 0 or n == 1: # base condition
return 1
else:
return n * factorial(n - 1) # recursive call
num = int(input("Enter a number: "))
print("Factorial of", num, "is:", factorial(num))
The Fibonacci series
C13, Slide 69
The tree of function calls
that calculate the 5th number in the series
C13, Slide 70
# Write a python program to compute the Fibonacci series
using recursion.
Output
def fib(n):
if n <= 1: # base condition
return n
else:
return fib(n-1) + fib(n-2) # recursive call
terms = int(input("Enter number of terms: "))
print("Fibonacci Series:")
for i in range(terms):
print(fib(i))
Strings
• In Python, a string is a sequence of Unicode characters, used to
represent textual data. They are an immutable data type, meaning
their content cannot be changed once created.
• A string in Python is a sequence of characters enclosed in single (' '),
double (" "), or triple quotes (''' ''' or """ """).
Key Characteristics and Operations:
•Immutability: Once a string is created, its value cannot be altered. Any operation that appears to modify a
string, such as replace() , actually returns a new string with the changes.
•Indexing and Slicing: Individual characters can be accessed using zero-based indexing
(e.g., my_string[0] ), and substrings can be extracted using slicing (e.g., my_string[1:4] ). Negative indexing is
also supported to access characters from the end of the string.
•Concatenation: Strings can be joined together using the + operator.
•Replication: Strings can be repeated a specified number of times using the * operator.
•Built-in Methods: Python's str class provides numerous methods for manipulating strings, including:
•len() : Returns the length of the string.
•upper() , lower() , capitalize() : For case conversion.
•find() , rfind() , count() : For searching and counting characters/substrings.
•replace() : To substitute substrings.
•strip() , lstrip() , rstrip() : To remove leading/trailing whitespace.
•split() : To divide a string into a list of substrings based on a delimiter.
•join() : To concatenate a sequence of strings using a specified delimiter.
•String Formatting: Various methods exist for embedding variable values into strings, including f-strings
(formatted string literals), the format() method, and the older % operator.
String formatting options
• String formatting means inserting values inside a string in a readable and
flexible way.
• 1. Using f-Strings (Python 3.6+)
name = “Raj"
age = 21
marks = 89.567
print(f"My name is {name}, I am {age} years old, and my marks are
{marks:.2f}.")
My name is Raj, I am 21 years old, and my marks are 89.57.
• 2. Using [Link]() Method
• name = "Mahalaxmi"
• age = 21
• print("My name is {} and I am {} years old.".format(name, age))
• My name is Mahalaxmi and I am 21 years old.
3. String Concatenation (Basic but less
flexible)
name = “Raj"
age = 21
print("My name is " + name + " and I am " + str(age) + " years old.")
Indexing
• string indexing allows access to individual characters within a string using their
position. Strings are ordered sequences, and each character is assigned an
index, starting from 0 for the first character.
• Access characters from the beginning of the string.
• The first character is at index 0, the second at index 1, and so on.
We can access characters in a String in Two ways :
1. Accessing Characters by Positive Index Number: In this type of Indexing we
pass a Positive index (which we want to access) in square brackets. The index
number starts from index number 0
2. Accessing Characters by Negative Index Number: In this type of Indexing, we
pass the Negative index(which we want to access) in square brackets. Here
the index number starts from index number -1 (which denotes the last
character of a string).
Accessing Characters by Positive Index Number:
word = "PYTHON"
print(word[0]) # P
print(word[3]) # H
print(word[5]) # N
Character P Y T H O N
Index 0 1 2 3 4 5
Accessing Characters by Negative Index Number:
word = "PYTHON"
print(word[-1]) # N
print(word[-2]) # O
print(word[-6]) # P
Character P Y T H O N
Index -6 -5 -4 -3 -2 -1
Slicing
• String Slicing allows us to extract a part of the string. We can specify a start
index, end index, and step size.
• The general format for slicing is:
string[start : end : step]
start : We provide the starting index.
end : We provide the end index(this is not included in substring).
step : It is an optional argument that determines the increment between each
index for slicing.
Example
text = "PYTHON"
print(text[1:4]) Output: YTH
Character P Y T H O N
Index (+) 0 1 2 3 4 5
Index (-) -6 -5 -4 -3 -2 -1
Examples
Basic Slicing
s = "Python"
print(s[0:3]) # Pyt
print(s[2:6]) # thon
Omitting Start or End
If you leave out start, Python assumes 0.
If you leave out end, Python assumes till the end of the string.
print(s[:4]) # Pyth (from start to index 3)
print(s[2:]) # thon (from index 2 to end)
print(s[:]) # Python (whole string)
Using Step Value
The step value controls how many characters to skip.
print(s[0:6:2]) # Pto (every 2nd character)
print(s[::3]) # Ph (every 3rd character)
String Manipulation Function
Write a python program to check a given character is
vowel or consonants
ch = input("Enter a letter: ")
if ch in 'aeiouAEIOU':
print("It is a vowel")
else:
print("It is a consonant")
Output
Enter a letter: e
It is a vowel
Write a python program to count number of characters
in a given string
text = input("Enter a string: ")
count = len(text)
print("Number of characters in the string:", count)
Output:
Enter a string: hello world
Number of characters in the string: 11
Write a python program to count number of
characters in a given string without using string
functions
text = input("Enter a string: ")
count = 0
for ch in text:
count = count + 1
print("Number of characters in the string:", count)
Output:
Enter a string: hello
Number of characters in the string: 5
Write a python program to find a substring in a
given string
text = input("Enter a string: ")
sub = input("Enter a substring: ")
if sub in text:
print("Substring found!")
else:
print("Substring not found!")
Output:
Enter a string: hello world
Enter a substring: world
Substring found!
Write a python program to compare two string are equal
or not
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
# Using the built-in string function 'casefold()' to compare without case sensitivity
if [Link]() == [Link]():
print("Both strings are equal")
else:
print("Strings are not equal")
Output:
Enter first string: Hello
Enter second string: hello
Both strings are equal
Write a python program to reverse a string using string
function.
text = input("Enter a string: ")
reverse = text[::-1]
print("Reversed string:", reverse)
Output:
Enter a string: python
Reversed string: nohtyp
Write a python program to reverse a string without using
string functions
text = input("Enter a string: ")
reverse = ""
i = len(text) - 1 # start from the last index
while i >= 0:
reverse = reverse + text[i]
i=i-1
print("Reversed string:", reverse)
Output:
Enter a string: python
Reversed string: nohtyp
Write a python program to check a given string is
palindrome or not
text = input("Enter a string: ")
# Reverse the string
reverse = text[::-1]
if text == reverse:
print("It is a palindrome")
else:
print("It is not a palindrome")
Output:
Enter a string: madam
It is a palindrome
Write a python program to find substring in a string
without using
string = input("Enter the main string: ")
string functions
sub = input("Enter the substring: ")
found = False
for i in range(len(string) - len(sub) + 1):
match = True
for j in range(len(sub)):
Output:
if string[i + j] != sub[j]:
match = False
break
if match:
found = True
break
if found:
print("Substring found!")
else:
print("Substring not found!")
Thank You