Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit III PSPP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

1. Explain in detail various types of operators.

(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

Various Types of 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.

Bitwise Operators or shift operators

It is used to represent the data at bit level. It operates on integers only.


Assignment Operators

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.

2. Discuss conditional alternative and chained conditional in detail.(Jan 2019, Jan2022)

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

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if (num1 >= num2) :

largest = num1

else:

largest = num2

print("The largest number is", largest)

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:

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.

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)

3. Explain in detail about iterations.

Python programming language provides the following types of loops to handle looping requirements.

While Loop in Python


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.

Let’s see a simple example of while loop in Python.

# Python program to illustrate while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Python")

Output

Hello Python

Hello Python

Hello Python

For Loop in 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:

for iterator_var in sequence:

statements(s)

It can be used to iterate over a range and iterators.

n=4

for i in range(0, n):


print(i)

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.

Python program to illustrate iterating over a list

print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)

Output

List Iteration

geeks

for

geeks

Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)
Output

Tuple Iteration

geeks

for

geeks

Iterating over a String

print("\nString Iteration")

s = "Python"

for i in s:

print(i)

Output

String Iteration

Iterating over dictionary

print("\nDictionary Iteration")

d = dict()
d['xyz'] = 123

d['abc'] = 345

for i in d:

print("%s %d" % (i, d[i]))

Output

Dictionary Iteration

xyz 123

abc 345

4. Explain in detail about Fruitful Functions.

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

Example of Fruitful Function in Python


Now we will see an example with code, output followed by its explanation.

def add():

a=15

b=24

c=a+b

return c

c=add()

print(c)

Output

39

Void Function in Python

These are different class of Python function that completes all of a function’s actions without returning
a value.

Example of Void Function in Python

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

Parameters in Fruitful Functions in Python

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

Scope in Fruitful Function in Python

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.

Advantages of Fruitful Functions

Fruitful functions offer several advantages over non-fruitful (void) 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

Here is a basic example of string slicing.

S = 'ABCDEFGHI'
print(S[2:7]) # CDEFG

Note that the item at index 7 'H' is not included.

Slice with Negative Indices

You can also specify negative indices while slicing a string.


S = 'ABCDEFGHI'
print(S[-7:-2]) # CDEFG

Slice with Positive & Negative Indices

You can specify both positive and negative indices at the same time.

S = 'ABCDEFGHI'
print(S[2:-5]) # CD

Specify Step of the Slicing

You can specify the step of the slicing using step parameter. The step parameter is optional and by
default 1.

# Return every 2nd item between position 2 to 7


S = 'ABCDEFGHI'
print(S[2:7:2]) # CEG

Negative Step Size

You can even specify a negative step size.

# Returns every 2nd item between position 6 to 1 in reverse order


S = 'ABCDEFGHI'
print(S[6:1:-2]) # GEC

Slice at Beginning & End

Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent to S[0:stop]

# Slice first three characters from the string


S = 'ABCDEFGHI'
print(S[:3]) # ABC

Whereas, omitting the stop index extends the slice to the end of the string. Meaning, S[start:] is
equivalent to S[start:len(S)]

# Slice last three characters from the string


S = 'ABCDEFGHI'
print(S[6:]) # GHI

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

6. Write a python code to search a string in the given list.

def index(s, sub):


start = 0
end = 0
while start < len(s):
if s[start+end] != sub[end]:
start += 1
end = 0
continue
end += 1
if end == len(sub):
return start
return -1

>>> index("dedicate", 'cat')


4
>>> index("this is an example", 'example')
11
>>> index('hello world', 'word')
-1

7. Write a Python program to find the square root of a number.


def newtonsqrt(n):
approx=0.5*n
better=0.5*(approx+n/approx)
while better!=approx:
approx=better
better=0.5*(approx+n/approx)
return approx
print(newtonsqrt(64))

8. Explain about string modules in detail.


The string module in Python is a versatile and foundational component of the standard library,
primarily focusing on text constants, text templates, and various utility functions for working with
strings.

len() function returns the length of the string.

string = "Geeksforgeeks"
print(len(string))

The upper() method returns a string where all characters are in upper case.

txt = "Hello my friends"


x = txt.upper()
print(x)

The find() method finds the first occurrence of the specified value and returns -1 if the value is not
found.

txt = "Hello, welcome to my world."


x = txt.find("e")
print(x)

The count() method returns the number of times a specified value appears in the string.

txt = "I love apples, apple are my favorite fruit"


x = txt.count("apple")
print(x)

The swapcase() method returns a string where all the upper case letters are lower case and vice versa.

txt = "Hello My Name Is PETER"


x = txt.swapcase()
print(x)

The islower() method returns True if all the characters are in lower case, otherwise False.

txt = "hello world!"


x = txt.islower()
print(x)

The isupper() method returns True if all the characters are in upper case, otherwise False.

txt = "THIS IS NOW!"


x = txt.isupper()
print(x)

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.

txt = " "


x = txt.isspace()
print(x)

The join() method takes all items in an iterable and joins them into one string.

myTuple = ("John", "Peter", "Vicky")


x = "#".join(myTuple)
print(x)

The split() method splits a string into a list.

txt = "welcome to the jungle"


x = txt.split()
print(x)

9. Write a Python program to find GCD of two numbers.

GCD using function

def compute_hcf(x, y):


while(y):
x, y = y, x % y
return x

hcf = compute_hcf(300, 400)


print("The HCF is", hcf)
GCD using recursive function

def gcd(x,y):
if y == 0:
return x
else:
return gcd(y,x%y)
print(gcd(100,30))

10. Write a Python program to find the exponentiation of a number.

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

11. Write a Python program to sum an array of numbers.

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)

12. Write a Python program to perform linear search.

def search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1
a=[2,34,56,12,32]
print(search(a,12))

13. Write a Python program to perform binary search.

def binary_search(arr, x):


low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# If x is greater, ignore left half
if arr[mid] < x:
low = mid + 1
# If x is smaller, ignore right half
elif arr[mid] > x:
high = mid - 1
# means x is present at mid
else:
return mid
# If we reach here, then the element was not present
return -1

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.

Factorial of the given number without 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)

14. b. Write a Python program to generate first N Fibonacci series numbers.

First N Fibonacci series numbers without recursion

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)

First N Fibonacci series numbers with recursion

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=" ")

15. a. Appraise with an example nested if and elif header in Python

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

if num <= 15:


print("Between 5 and 15")

Output:

Bigger than 5
Between 5 and 15

if-elif (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:
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.

While Loop in Python

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.

Let’s see a simple example of a while loop in Python.

# Python program to illustrate while loop


count = 0
while (count < 3):
count = count + 1
print("Hello Python")

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

Working of break Statement

Working of the break statement

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.

break Statement with while Loop

We can also terminate the while loop using the break statement. For example,

# program to find first 5 multiples of 6

i=1

while i <= 10:

print('6 * ',(i), '=',6 * i)

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.

The syntax of the continue statement is:

continue

Working of continue Statement

How continue statement works in python

The working of the continue statement in for and while loop is shown above.

continue Statement with for Loop

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.

continue Statement with while Loop

In Python, we can also skip the current iteration of the while loop using the continue statement. For
example,

# program to print odd numbers from 1 to 10

num = 0

while num < 10:

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.

Difference between List and Array

S.No. List Array

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.

4 It consumes a larger memory. It consumes less memory than a list.

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.

6 It favors a shorter sequence of data. It favors a longer sequence of data.

Python Array vs List: Who’s the winner?


Type of elements

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.

def Anagram1(s1, s2):

# the sorted strings are checked

if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")

else:

print("The strings aren't anagrams.")

def Anagram2(s1, s2):

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:

print("\nStrings are Not Anagram")

else:

print("\nStrings are Anagram")

else:

print("\nLength of Strings are not Equal")


# driver code

s1 ="listen"

s2 ="silent"

Anagram1(s1, s2)

Anagram2(s1,s2)

17. Write a python code to search a string in the given list.

def check_if_exists(x, ls):


if x in ls:
print(str(x) + ' is inside the list')
else:
print(str(x) + ' is not present in the list')

ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython']


check_if_exists(2, ls)
check_if_exists('Hello', ls)
check_if_exists('Hi', ls)

Output

2 is inside the list


Hello is inside the list
Hi is not present in the list

You might also like