Unit III PSPP
Unit III PSPP
Unit III PSPP
(Jan 2019)
An operator is a symbol that specifies an operation to be performed on the operands. Operand It is a
data item on which operators perform operations.
Eg: a+b Here, a, b are Operands and + is Operator
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators or shift operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators It allows basic arithmetic operations like addition, subtraction, multiplication,
division, modulus and floor division.
Relational Operator
Relational operators are used to compare the relation between two or more operands. Operands may be
variable, value or expression. It compares two operands and returns either true or false.
Assignment operators are used to assign values to variables. a = 5 is a simple assignment operator that
assigns the value 5 on the right to the variable a on the left. There are various compound operators a +=
5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.
Membership Operators
Python offers two membership operators to check or validate the membership of a value. It tests for
membership in a sequence, such as strings, lists, or tuples.
Identity Operator
Identity Operator in Python is a special comparison operator used to check if two variables reference
the same object in memory. They are different from the equality operators that compare values. In
Python, there are two identity operators: is and is not. Both of these operators are used to verify if the
variables on either side of the operator point to the same object or not.
Conditional statements are an essential part of programming in Python. They allow you to make
decisions based on the values of variables or the result of comparisons.
if statement
In order to write useful programs, we almost always need the ability to check conditions and change
the behavior of the program accordingly. Conditional statements give us this ability. The simplest form
is the if statement:
if x > 0 :
print('x is positive')
The boolean expression after the if statement is called the condition. We end the if statement with a
colon character (:) and the line(s) after the if statement are indented.
Conditional Alternative
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed. The syntax looks like this:
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed.
Example Program
largest = num1
else:
largest = num2
Chained conditionals
Sometimes there are more than two possibilities and we need more than two branches. One way to
express a computation like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
else:
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
Example Program
largest = num1
largest = num2
else:
largest = num3
Python programming language provides the following types of loops to handle looping requirements.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
count = 0
count = count + 1
print("Hello Python")
Output
Hello Python
Hello Python
Hello Python
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In
Python, there is “for in” loop which is similar to for each loop in other languages. Let us learn how to
use for in loop for sequential traversals.
Syntax:
statements(s)
n=4
Output
Example with List, Tuple, string, and dictionary iteration using For Loops in Python
We can use a for loop to iterate lists, tuples, strings and dictionaries in Python.
print("List Iteration")
for i in l:
print(i)
Output
List Iteration
geeks
for
geeks
print("\nTuple Iteration")
for i in t:
print(i)
Output
Tuple Iteration
geeks
for
geeks
print("\nString Iteration")
s = "Python"
for i in s:
print(i)
Output
String Iteration
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
Output
Dictionary Iteration
xyz 123
abc 345
A fruitful function in Python is a function that not only performs a specific task but also returns a value
or result after its execution. Unlike void functions, which perform a task without producing an output,
fruitful functions provide a way to obtain and utilize the computed result within the program.
To define a fruitful function in Python, you need to use the keyword "def" followed by the function
name, input parameters, and a return statement that specifies the value to be returned. For example, if
you want to define a function that returns the square of a number, you can define it as follows:
def square(x):
return x ** 2
In this example, the function is named "square," and it takes a single input parameter "x." The function
processes the input parameter by squaring it (i.e., raising it to the power of 2) and then returns the
result using the return statement.
Dead Code: The code which lies below the return statement or where the code can never reach during
its execution is known as dead code.
To call a fruitful function in Python, you need to use the function name and provide any necessary
arguments. For example, if you have defined a function named "square" that takes a single argument
and returns its square, you can call it as follows:
result = square(3)
In this example, the function "square" is called with an input parameter of 3. The function processes
the input parameter by squaring it and then returns the result, which is assigned to the variable "result."
def add():
a=15
b=24
c=a+b
return c
c=add()
print(c)
Output
39
These are different class of Python function that completes all of a function’s actions without returning
a value.
Here you will see the code, implementation, and explanation of the example of a void function in
python.
def add():
a=15
b=27
c=a+b
print(c)
c=add()
Output
42
Required/Positional parameters: These are parameters that are passed to a function in a specific
order and are required for the function to work correctly. They are also known as positional
arguments. If a required parameter is not provided when calling the function, a TypeError will
be raised.
Keyword parameters: These are parameters that are passed to a function with their
corresponding parameter name. They are also known as named arguments. Keyword arguments
can be passed in any order and can be omitted if a default value is defined for them.
Default parameters: These are parameters that have a default value assigned to them in the
function definition. If a value is not provided for the parameter when calling the function, the
default value is used instead.
Variable-length parameters in fruitful functions in python: These are parameters that allow a
function to accept any number of arguments. There are two types of variable length parameters
in Python: *args and *kwargs. args: It is used to pass a variable number of non-keyword
arguments to a function. **kwargs: It is used to pass a variable number of keyword arguments
to a function.
In Python, a variable’s scope refers to the region of the program where it is accessible. There are two
types of scopes in Python: local scope and global scope.
Local Scope: A local scope refers to the region of the program where a variable is defined
within a function. Variables defined inside a function are only accessible within that function,
and cannot be accessed outside of it. This is known as the local scope of a variable.
Global Scope: A global scope refers to the region of the program where a variable is defined
outside of a function, i.e., at the top level of the program. Variables defined in the global scope
can be accessed from anywhere in the program, including inside functions.
Reusability: Fruitful functions can be used in multiple places within a program, reducing the
amount of code duplication and increasing reusability.
Modularity: Fruitful functions help to break down complex tasks into smaller, more
manageable functions. This improves the readability of the code and makes it easier to
maintain.
Efficiency: Fruitful functions can perform complex operations and return the result in a single
statement, making the code more efficient and easier to understand.
Flexibility: Fruitful functions can be used with any data type, making them flexible and
adaptable to different programming needs.
5. Discuss in detail about string slices and string immutability. Or Analyse String slicing.
Illustrate how it is done in python with an example.
To access a range of characters in a string, you need to slice a string. One way to do this is to use the
simple slicing operator :
With this operator you can specify where to start the slicing, where to end and specify the step.
Slicing a String
If S is a string, the expression S [ start : stop : step ] returns the portion of the string from index start to
index stop, at a step size step.
Syntax
Basic Example
S = 'ABCDEFGHI'
print(S[2:7]) # CDEFG
You can specify both positive and negative indices at the same time.
S = 'ABCDEFGHI'
print(S[2:-5]) # CD
You can specify the step of the slicing using step parameter. The step parameter is optional and by
default 1.
Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent to S[0:stop]
Whereas, omitting the stop index extends the slice to the end of the string. Meaning, S[start:] is
equivalent to S[start:len(S)]
Reverse a String
You can reverse a string by omitting both start and stop indices and specifying a step as -1.
S = 'ABCDEFGHI'
print(S[::-1]) # IHGFEDCBA
string = "Geeksforgeeks"
print(len(string))
The upper() method returns a string where all characters are in upper case.
The find() method finds the first occurrence of the specified value and returns -1 if the value is not
found.
The count() method returns the number of times a specified value appears in the string.
The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
The islower() method returns True if all the characters are in lower case, otherwise False.
The isupper() method returns True if all the characters are in upper case, otherwise False.
The isalpha() method returns True if all the characters are alphabet letters (a-z).
txt = "CompanyX"
x = txt.isalpha()
print(x)
The isdigit() method returns True if all the characters are digits, otherwise False.
txt = "50800"
x = txt.isdigit()
print(x)
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
The join() method takes all items in an iterable and joins them into one string.
def gcd(x,y):
if y == 0:
return x
else:
return gcd(y,x%y)
print(gcd(100,30))
base = 5
exponent = 3
result = base
if exponent != 0:
for i in range(exponent - 1):
result = result * base
else:
result == 1
print("Exponential value is : ", result) # 125
def _sum(arr):
sum = 0
for i in arr:
sum = sum + i
return(sum)
arr = [12, 3, 4, 15]
n = len(arr)
ans = _sum(arr)
print('Sum of the array is ', ans)
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
14. a. Write a Python program to find the factorial of the given number without recursion with
recursion.
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 5
print("Factorial of",num,"is",
factorial(num))
Factorial of the given number with recursion
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 7
result = factorial(num)
print("The factorial of", num, "is", result)
def printFibonacciNumbers(n):
f1 = 0
f2 = 1
if (n < 1):
return
print(f1, end=" ")
for x in range(1, n):
print(f2, end=" ")
next = f1 + f2
f1 = f2
f2 = next
printFibonacciNumbers(7)
def fibonacci_numbers(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return fibonacci_numbers(num-2)+fibonacci_numbers(num-1)
n=7
for i in range(0, n):
print(fibonacci_numbers(i), end=" ")
Nested if Statement
if statement can also be checked inside other if statement. This conditional statement is called a nested
if statement. This means that inner if condition will be checked only if outer if condition is true and by
this, we can see multiple conditions to be satisfied.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flow chart:-
Example:
# Nested if statement example
num = 10
if num > 5:
print("Bigger than 5")
Output:
Bigger than 5
Between 5 and 15
Sometimes there are more than two possibilities and we need more than two branches. One way to
express a computation like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
Else:
print('x and y are equal')
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flow Chart:-
Example:-
Example Program
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
15. b. Explain with an example while loop, break statement and continue statement in Python.
Python programming language provides the following types of loops to handle looping requirements.
In python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the program is
executed.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
Output
Hello Python
Hello Python
Hello Python
break Statement
The break statement is used to terminate the loop immediately when it is encountered.
The syntax of the break statement is:
break
The working of break statement in for loop and while loop is shown above.
break Statement with for Loop
We can use the break statement with the for loop to terminate the loop when a certain condition is met.
For example,
for i in range(5):
if i == 3:
break
print(i)
Output
0
1
2
In the above example, we have used the for loop to print the value of i. Notice the use of the break
statement,
if i == 3:
break
Here, when i is equal to 3, the break statement terminates the loop. Hence, the output doesn't include
values after 2.
We can also terminate the while loop using the break statement. For example,
i=1
if i >= 5:
break
i=i+1
Output
6* 1=6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
In the above example, we have used the while loop to find the first 5 multiples of 6. Here notice the
line,
if i >= 5:
break
This means when i is greater than or equal to 5, the while loop is terminated.
continue Statement
The continue statement is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.
continue
The working of the continue statement in for and while loop is shown above.
We can use the continue statement with the for loop to skip the current iteration of the loop. Then the
control of the program jumps to the next iteration. For example,
for i in range(5):
if i == 3:
continue
print(i)
Output
In the above example, we have used the for loop to print the value of i. Notice the use of the continue
statement,
if i == 3:
continue
Here, when i is equal to 3, the continue statement is executed. Hence, the value 3 is not printed to the
output.
In Python, we can also skip the current iteration of the while loop using the continue statement. For
example,
num = 0
num += 1
if (num % 2) == 0:
continue
print(num)
Output
In the above example, we have used the while loop to print the odd numbers between 1 to 10. Notice
the line,
if (num % 2) == 0:
continue
Here, when the number is even, the continue statement skips the current iteration and starts the next
iteration.
16. a. Compare lists and array with example. Can list be considered as an array? Justify.
Both list and array are the data structure in python used to store multiple items. Let’s figure out some
major differences between list and array in python.
What is List?
The list is an important component used to collect multiple items in a single variable. It has the ability
to collect items that usually consist of elements of multiple data types. These may include character
logical values, numeric values, and more.
What is Array?
An array is also a vital component that collects several items. Arrays are also known as data structure.
Python has several in-built data structures, such as arrays.
1 List is used to collect items that usually An array is also a vital component that collects
consist of elements of multiple data types. several items of the same data type.
2 List cannot manage arithmetic operations. Array can manage arithmetic operations.
3 When it comes to flexibility, the list is When it comes to flexibility, the array is not
perfect as it allows easy modification of suitable as it does not allow easy modification of
data. data.
5 In a list, the complete list can be accessed In an array, a loop is mandatory to access the
without any specific looping. components of the array.
If the type of data is not predetermined, there is a collection of data belonging to multiple types. For
instance, to store the record of students having entities such as name(string), ID(integer),
and marks(float), a list is a preferred choice.
If the data to be stored belongs to the same data type, then an array or a list can be preferred here.
The choice will then depend on other parameters such as the size of the data, operations to be
performed, and usage.
Memory Consumption
Memory consumption in lists is more as some additional space is allocated during the initialization
of the list. If the data collection is relatively smaller, then a list is an efficient choice here.
Arrays are suitable for storing large amounts of data, as the memory consumption of arrays is more
efficient than lists.
16. b. Write a python function Anagram1 ( ) to check whether two strings are anagram of each
other or not with built-in string function and are Anagram2 ( ) to check the anagram without
using built-in string function.
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
found=0
notFound=0
lenOne = len(s1)
lenTwo = len(s2)
if lenOne == lenTwo:
for i in range(lenOne):
found = 0
for j in range(lenOne):
if s1[i] == s2[j]:
found = 1
break
if found==0:
notFound = 1
break
if notFound==1:
else:
else:
s1 ="listen"
s2 ="silent"
Anagram1(s1, s2)
Anagram2(s1,s2)
Output