0% found this document useful (0 votes)
5 views9 pages

Python Programs

The document provides an overview of basic Python functions for arithmetic operations, Boolean expressions, and recursion. It explains comparison and logical operators, the use of the bool() function, and the structure of recursive functions with examples like countdown and factorial. Additionally, it discusses the potential for infinite recursion and its causes.

Uploaded by

tej.ch
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Python Programs

The document provides an overview of basic Python functions for arithmetic operations, Boolean expressions, and recursion. It explains comparison and logical operators, the use of the bool() function, and the structure of recursive functions with examples like countdown and factorial. Additionally, it discusses the potential for infinite recursion and its causes.

Uploaded by

tej.ch
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Floor division and modulus

1. Simple Calculator Using Functions:

def add(n1, n2):


return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
def mod(n1, n2):
return n1 % n2
def floordiv(n1, n2):
return n1 // n2
def exponent(n1, n2):
return n1 ** n2

print("Please select operation -\n"


"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n"
"5. Modulus\n"
"6. Floor Division\n"
"7. Exponentiation\n")

sel = int(input("Select operation (1-7): "))


n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))

if sel == 1:
print(n1, "+", n2, "=", add(n1, n2))
elif sel == 2:
print(n1, "-", n2, "=", sub(n1, n2))
elif sel == 3:
print(n1, "*", n2, "=", mul(n1, n2))
elif sel == 4:
print(n1, "/", n2, "=", div(n1, n2))
elif sel == 5:
print(n1, "%", n2, "=", mod(n1, n2))
elif sel == 6:
print(n1, "//", n2, "=", floordiv(n1, n2))
elif sel == 7:
print(n1, "**", n2, "=", exponent(n1, n2))
else:
print("Invalid input")

Boolean expressions
 A Boolean expression in Python is a statement that evaluates to one
of two built-in values: True or False.
 These expressions are fundamental for controlling program flow
using conditional statements (if, elif, else) and loops
(while).
 Boolean expressions are created using comparison operators and
logical operators.

Comparison Operators: These operators compare two values and


return a Boolean result.
Operator Meaning Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 6 True

> Greater than 10 > 5 True

< Less than 10 < 9 False

>= Greater than or equal to 2 >= 2 True

<= Less than or equal to 1 <= 2 True

Logical operators: (and, or, not) are used to combine or modify Boolean
expressions.

Operato Description Example Resul


r t

And True if both operands are True and False


True False
Or True if at least one operand True or True
is True False

Not Inverts the Boolean value not True False

Python bool() Function:


bool() function is used to convert a value or expression to its
corresponding Boolean value (True or False).
# Returns False as x is None
x = None
print(bool(x))

# Returns False as x is an empty sequence


x = ()
print(bool(x))

# Returns False as x is an empty mapping


x = {}
print(bool(x))

# Returns False as x is 0
x = 0.0
print(bool(x))

# Returns True as x is a non empty string


x = 'GeeksforGeeks'
print(bool(x))

Integers and Floats as Boolean:


 In Python, integers and floats can be used as Boolean values with
the bool() function.
 Any number with a value of zero (0, 0.0) is considered False while
any non-zero number (positive or negative) is considered True.
var1 = 0
print(bool(var1))

var2 = 1
print(bool(var2))

var3 = -9.7
print(bool(var3))
Boolean OR Operator: It returns True if any one of the inputs is True else
returns False.
a=5
b=3
c=8
if a > b or b < c:
print("True")

Boolean And Operator: returns False if any one of the inputs is False
else returns True.
a=0
b=2
c=4
if a > b and b<c:
print(True)
else:
print(False)

if a and b and c:
print("True")
else:
print("False")

Boolean Not Operator: only requires one argument and returns the
negation of the argument i.e. returns the True for False and False for True.
a=0
if not a:
print("False")

Python Boolean == (equivalent) and != (not equivalent) Operator:


 Both operators are used to compare two results.
 '==' equivalent operator returns True if two results are equal
 '!=' not equivalent operator returns True if the two results are not
same.
a=0
b=1
if a == 0:
print(True)
if a == b:
print(True)
if a != b:
print(True)
Python is Operator:
 is keyword is used to test whether two variables belong to the same
object.
 The test will return True if the two objects are the same else it will
return False
x = 10
y = 10
if x is y:
print(True)
else:
print(False)

Python in Operator: in operator checks for the membership i.e. checks


if the value is present in a list, tuple, range, string, etc.
# Create a list
a = [1, 2, 2]
# Check if 1 in list or not
if 1 in a:
print(True)

Recursion: a function calls itself to solve a problem by breaking it down


into smaller, similar sub-problems.
Each recursive function must have two main components to prevent
infinite loops:
 Base Case: A condition that stops the recursion and provides a
direct solution to the simplest instance of the problem.
 Recursive Case: The part of the function that calls itself with a
modified, smaller input, moving the solution progressively closer to
the base case.

Basic structure of recursive function:

def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)

Example : A simple recursive function that counts down from 5


def countdown(n):
if n <= 0:
print("Done!")
else:
print(n)
countdown(n - 1)
countdown(5)

Example: Calculating Factorial


def factorial(n):
if n == 0 or n == 1: # Base
case: if n is 0 or 1, return 1
return 1

else:
return n * factorial(n - 1) # Recursive case:
n! = n * (n-1)!

num = 5 #
Test the function
print(f"The factorial of {num} is {factorial(num)}")

Execution Flow for factorial(5):


1. factorial(5) calls factorial(4)
2. factorial(4) calls factorial(3)
3. factorial(3) calls factorial(2)
4. factorial(2) calls factorial(1)
5. factorial(1) hits the base case and returns 1
6. factorial(2) receives 1, calculates 2 * 1 = 2, and returns 2
7. factorial(3) receives 2, calculates 3 * 2 = 6, and returns 6
8. factorial(4) receives 6, calculates 4 * 6 = 24, and returns 24
9. factorial(5) receives 24, calculates 5 * 24 = 120, and
returns 120

Recursion is useful for problems that are naturally recursive, such


as:
 Fibonacci Sequence: Each number is the sum of the two
preceding ones.
 Tree Traversal: Navigating hierarchical data structures like binary
trees.
 Divide-and-Conquer Algorithms: Sorting algorithms like merge
sort and quick sort.
 File System Operations: Traversing and searching directory
structures.
 Binary Search: Efficiently searching a sorted list.

Infinite recursion in Python


 occurs when a function repeatedly calls itself without a proper base
case or termination condition.
 This is a logical error, similar to an infinite loop, that consumes all
available memory on the call stack, eventually causing the program
to crash with a RecursionError: maximum recursion depth exceeded

The primary causes of infinite recursion are:


 Missing Base Case: A function that calls itself must have a
condition that eventually stops the recursion. Without it, the calls
continue indefinitely.
 Unreachable Base Case: The logic within the function may fail to
modify the parameters in a way that allows the base case condition
to be met.
 For example, if a function is meant to stop when n == 0 but n is
never decremented, the condition is never reached.

def infinite_recursion_example():
print("This function calls itself non-stop!")
infinite_recursion_example() # The
function calls itself again

infinite_recursion_example() # Calling the function starts


the infinite process

Example:
def incorrect_countdown(n):
# The base case 'if n == 0' is never reached if n starts negative
if n == 0:
print("Done!")
return
else:
print(n)
# Calling with n + 1 moves away from the base case of 0
incorrect_countdown(n + 1)
# Calling the function with a positive number works fine, but a negative
number leads to infinite recursion
incorrect_countdown(-1)

Tracing the execution of factorial(3) would look like this:


Ste Action Stack Diagram Notes
p (Top -> Bottom)

1 Initial call factorial(3) factorial(3) n=3

2 factorial(3) calls factorial(2) factorial(2) n=2 in new


factorial(3) frame

3 factorial(2) calls factorial(1) factorial(1) n=1 in new


factorial(2) frame
factorial(3)

4 factorial(1) calls factorial(0) factorial(0) n=0 in new


factorial(1) frame
factorial(2)
factorial(3)

5 factorial(0) hits base case, factorial(1) Frame


returns 1 factorial(2) for n=0 is
factorial(3) popped

6 factorial(1) receives 1, factorial(2) Frame


calculates 1 * 1 = 1, returns 1 factorial(3) for n=1 is
popped

7 factorial(2) receives 1, factorial(3) Frame


calculates 2 * 1 = 2, returns 2 for n=2 is
popped
8 factorial(3) receives 2, __main__ Frame
calculates 3 * 2 = 6, returns 6 for n=3 is
popped

9 Final result 6 is returned Empty Execution is


to __main__ complete

You might also like