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

Question Bank Solution-1

Uploaded by

phantomsightx666
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)
39 views

Question Bank Solution-1

Uploaded by

phantomsightx666
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/ 51

College of Technology (01)

Silver Oak College of Engineering and


Technology Bachelor of Technology
Department of Information Technology (10)

Semester: 4 Academic Year: 2021-22


Python
Subject Name: Subject Code: 1010043221
Programming

Unit -1
Q1 Explain features of python.
Ans
Features in Python
There are many features in Python, some of which are discussed below –

1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in python language and anybody can learn python basics in a few
hours or days. It is also a developer-friendly language.

2. Free and Open Source:


Python language is freely available at the official website and you can download it
from the given download link below click on the Download Python keyword.
Download Python
Since it is open-source, this means that source code is also available to the public.
So you can download it as, use it as well as share it.

3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, objects encapsulation,
etc.

1
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.

5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not
need to remember the system architecture, nor do we need to manage the memory.

6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++
language and also we can compile that code in C/C++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have python code
for windows and if we want to run this code on other platforms such as Linux,
Unix, and Mac then we do not need to change it, we can run this code on any
platform.

8. Python is Integrated language:


Python is also an Integrated language because we can easily integrated python with
other languages like c, c++, etc.

9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at
a time. like other languages C, C++, Java, etc. there is no need to compile python
code this makes it easier to debug our code. The source code of python is
converted into an immediate form called bytecode.

10. Large Standard Library


Python has a large standard library which provides a rich set of module and
functions so you do not have to write your own code for every single thing. There
are many libraries present in python for such as regular expressions, unit-testing,
web browsers, etc.

11. Dynamically Typed Language:


Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
2
Q2 Compare python with C and Java.
Ans

3
Q3 Python is interpreted language. Explain it
Ans
Python is an interpreted language, which means the source code of a Python
program is converted into bytecode that is then executed by the Python virtual
machine. Python is different from major compiled languages, such as C and C + +,
as Python code is not required to be built and linked like code for these languages.
This distinction makes for two important points:

Python code is fast to develop: As the code is not needed to be compiled
and built, Python code can be readily changed and executed. This makes for
a fast development cycle.

Python code is not as fast in execution: Since the code is not directly
compiled and executed and an additional layer of the Python virtual machine
is responsible for execution, Python code runs a little slow as compared to
conventional languages like C, C + +, etc.
Strengths

4
Python has steadily risen in the charts of widely used programming languages and,
according to several surveys and research, it is the fifth most important language in
the world. Recently several surveys depicted Python to be the most popular
language for machine learning and data science! We will compile a brief list of
advantages that Python offers that will likely explain its popularity.
Easy to learn: Python is a relatively easy-to-learn language. Its syntax is simple
for a beginner to learn and understand. When compared with languages like C or
Java, there is minimal boilerplate code required in executing a Python program.
Supports multiple programming paradigms: Python is a multiparadigm,
multipurpose programming language. It supports object-oriented programming,
structured programming, functional programming, and even aspect-oriented
programming. This versatility allows it to be used by a multitude of programmers.
Extensible: Extensibility of Python is one of its most important characteristics.
Python has a huge number of modules easily available that can be readily installed
and used. These modules cover every aspect of programming from data access to
implementation of popular algorithms. This easy-to-extend feature ensures that a
Python developer is more productive, as a large array of problems can be solved by
available libraries.
Active open-source community: Python is open source and supported by a large
developer community. This makes it robust and adaptive. The bugs encountered
are easily fixed by the Python community. Being open source, developers can
tinker with the Python source code if necessary.
1.4.1 Pitfalls
Although Python is a very popular programming language, it comes with its own
share of pitfalls. One of the most important limitations it suffers is in terms of
execution speed. Being an interpreted language, it is slow when compared to
compiled languages. This limitation can be a bit restrictive in scenarios where
extremely high performance code is required. This is a major area of improvement
for future implementations of Python, and every subsequent Python version
addresses it. Although we have to admit it can never be as fast as a compiled
language, we are convinced that it makes up for this deficiency by being super-
efficient and effective in other departments.
You can install Python and the necessary libraries individually using a
prepackaged Python distribution that comes with necessary libraries (i.e.,
Anaconda). Anaconda is a packaged compilation of Python along with a whole
suite of libraries, including core libraries that are widely used in data science. The
main advantage of this distribution is that we do not need an elaborate setup and it
works well on all flavors of operating systems and platforms, especially Windows.
The Anaconda distribution comes with a wonderful IDE, Spyder (Scientific Python
Development Environment), as well as other useful utilities like Jupyter
5
Notebooks, the IPython console, and the excellent package management tool
Conda (Sarkar et al., 2018).
1.4.2 Drawbacks
The only real drawback of Python is that it is not as fast as Java or C. You can,
however, call C-compiled programs from Python. This gives you the best of both
worlds and allows you to incrementally develop a program. If the program is built
in a modular fashion, you can first get it up and running in Python and then, to
improve speed, start building portions of the code in C. The Boost C + + library
makes this easy to do. Other tools, such as Cython and PyPy, allow you write
typed versions of Python with performance gains over regular Python. If an idea
for a program or application is flawed, then it will be flawed at low speed as well
as high speed. If an idea is a bad idea, writing code can make it fast or scale
(Harrington, 2012).
1.4.3 The NumPy library
NumPy is the backbone of machine learning in Python. It is one of the most
important libraries in Python for numerical computations. It adds support to core
Python for multidimensional arrays (and matrices) and fast vectorized operations
on these arrays. It is employed in almost all machine learning and scientific
computing libraries. The extent of popularity of NumPy is verified by the fact that
major OS distributions, like Linux and MacOS, bundle NumPy as a default
package instead of considering it as an add-on package (Sarkar et al., 2018).
1.4.4 Pandas
Pandas is a vital Python library for data manipulation, wrangling, and analysis. It
functions as an intuitive and easy-to-use set of tools for execution operations on
any kind of data. Pandas allows you to work with both cross-sectional data and
time series–based data. DataFrame is the most important and useful data structure
that is employed for almost all types of data representation and manipulation in
Pandas. Unlike NumPy arrays, a DataFrame can contain heterogeneous data.
Naturally, tabular data are characterized by means of DataFrames, which are
analogous to Excel sheets or SQL tables. This is really beneficial in representing
raw datasets as well as processed feature sets in machine learning and data science.
All the operations can be performed along the axes, rows, and columns in a
DataFrame (Sarkar et al., 2018).

6
Unit 2
Q4 Which are the built-in data types in python?
Ans

Python Data Types


Built-in Data Types
In programming, data type is an important concept.

Variables can store data of different types, and different types can do different
things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Getting the Data Type


You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5

7
print(type(x))

Setting the Data Type

8
Setting the Specific Data Type

Q5 Explain a list with examples and explain any 5 methods with


examples.
Ans
Adding and Appending
append(): Used for appending and adding elements to List.It is used to add
elements to the last position of List.

Syntax:
list.append (element)
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)

9
print(List)
Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]

insert(): Inserts an elements at specified position.


Syntax:
list.insert(<position, element)
Note: Position mentioned should be within the range of List, as in this case
between 0 and 4, elsewise would throw IndexError.(<position, element)

List = ['Mathematics', 'chemistry', 1997, 2000]


# Insert at index 2 value 10087
List.insert(2,10087)
print(List)

Output:

['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]


extend(): Adds contents to List2 to the end of List1.
Syntax:
List1.extend(List2)

List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]

# Add List2 to List1


List1.extend(List2)
print(List1)

# Add List1 to List2 now


List2.extend(List1)
print(List2)
Output:

[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
sum(), count(), index(), min() and max() functions of List

sum() : Calculates sum of all the elements of List.


Syntax:

10
sum(List)

List = [1, 2, 3, 4, 5]
print(sum(List))
Output:

15
What happens if numeric value is not used a parameter?
Sum is calculated only for Numeric values, elsewise throws TypeError.
See example:

List = ['gfg', 'abc', 3]


print(sum(List))
Output:

Traceback (most recent call last):


File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
count():Calculates total occurrence of given element of List.
Syntax:
List.count(element)

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:

4
length:Calculates total length of List.
Syntax:
len(list_name)

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:

10
index(): Returns the index of first occurrence. Start and End index are not
necessary parameters.
11
Syntax:
List.index(element[,start[,end]])

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output:

1
Another example:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2,2))
Output:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]

"""index(element, start, end) : It will calculate till index end-1. """

# will check from index 2 to 4.


print("After checking in index range 2 to 4")
print(List.index(2,2,5))

# will check from index 2 to 3.


print("After checking in index range 2 to 3")
print(List.index(2,2,4))

Output:

After checking in index range 2 to 4


4
After checking in index range 2 to 3
Traceback (most recent call last):
File "", line 1, in
List.index(2,2,4)
ValueError: tuple.index(x): x not in tuple
min() : Calculates minimum of all the elements of List.
Syntax:
12
min(List)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(min(List))
Output:

1.054
max(): Calculates maximum of all the elements of List.
Syntax:
max(List)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(max(List))
Output:

5.33
sort() and reverse() functions

reverse(): Sort the given data structure (both tuple and list) in ascending order. Key
and reverse_flag are not necessary parameter and reverse_flag is set to False, if
nothing is passed through sorted().
Syntax:
sorted([list[,key[,Reverse_Flag]]])
list.sort([key,[Reverse_flag]])

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

#Reverse flag is set True


List.sort(reverse=True)

#List.sort().reverse(), reverses the sorted list


print(List)
Output:

[5.33, 4.445, 3, 2.5, 2.3, 1.054]

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


sorted(List)
print(List)
Output:
13
[1.054, 2.3, 2.5, 3, 4.445, 5.33]
Deletion of List Elements

To Delete one or more elements, i.e. remove an element, many built in functions
can be used, such as pop() & remove() and keywords such as del.

pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs.

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop())
Output:

2.5

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop(0))
Output:

2.3
del() : Element to be deleted is mentioned using list name and index.
Syntax:
del list.[index]

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


del List[0]
print(List)
Output:

[4.445, 3, 5.33, 1.054, 2.5]


remove(): Element to be deleted is mentioned using list name and element.
Syntax:
list.remove(element)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


List.remove(3)
14
print(List)
Output:

[2.3, 4.445, 5.33, 1.054, 2.5]

Q6 Write a program to reverse a list.


Ans
Reversing a List in Python
Python provides us with various ways of reversing a list. We will go through few
of the many techniques on how a list in python can be reversed.
Examples:

Input : list = [10, 11, 12, 13, 14, 15]


Output : [15, 14, 13, 12, 11, 10]

Input : list = [4, 5, 6, 7, 8, 9]


Output : [9, 8, 7, 6, 5, 4]
Method 1: Using the reversed() built-in function.
In this method, we neither reverse a list in-place(modify the original list), nor we
create any copy of the list. Instead, we get a reverse iterator which we use to cycle
through the list.
# Reversing a list using reversed()
def Reverse(lst):
return [ele for ele in reversed(lst)]

# Driver Code
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
Output:

[15, 14, 13, 12, 11, 10]


Method 2: Using the reverse() built-in function.
Using the reverse() method we can reverse the contents of the list object in-place
i.e., we don’t need to create a new list instead we just copy the existing elements to
the original list in reverse order. This method directly modifies the original list.
# Reversing a list using reverse()
def Reverse(lst):

15
lst.reverse()
return lst

lst = [10, 11, 12, 13, 14, 15]


print(Reverse(lst))

# Reversing a list using reverse()


def Reverse(lst):
lst.reverse()
return lst

lst = [10, 11, 12, 13, 14, 15]


print(Reverse(lst))
Output:

[15, 14, 13, 12, 11, 10]


Method 3: Using the slicing technique.
In this technique, a copy of the list is made and the list is not sorted in-place.
Creating a copy requires more space to hold all of the existing elements. This
exhausts more memory.

# Reversing a list using slicing technique


def Reverse(lst):
new_lst = lst[::-1]
return new_lst

lst = [10, 11, 12, 13, 14, 15]


print(Reverse(lst))
Output:

[15, 14, 13, 12, 11, 10]

Q7 Differentiate between list and set.


Ans

16
Q8 Explain dictionary with example.
Ans

Dictionary
The dictionary is an unordered collection that contains key:value pairs
separated by commas inside curly brackets. Dictionaries are optimized
to retrieve values when the key is known.

The following declares a dictionary object.

Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New
Delhi"}

Above, capitals is a dictionary object which contains key-value pairs


inside { }. The left side of : is a key, and the right side is a value. The
key should be unique and an immutable object. A number, string or
tuple can be used as key. Hence, the following dictionaries are also
valid:

Example: Dictionary Objects


d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"Oneand Half", 2.5: "Two and Half", 3.5:"Three and Half"}


# float key, string value

items={("Parker","Reynolds","Camlin"):"pen",
("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value

17
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int
value

However, a dictionary with a list as a key is not valid, as the list is


mutable:

Error: List as Dict Key


dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

But, a list can be used as a value.

Example: List as Dictionary Value


dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}

The same key cannot appear more than once in a collection. If the key
appears more than once, only the last will be retained. The value can
be of any data type. One value can be assigned to more than one key.

Example: Unique Keys


>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"}

The dict is the class of all dictionaries, as shown below.

Example: Distinct Type


>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'>

A dictionary can also be created using the dict() constructor method.

Example: dict() Constructor Method


>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'}

Q9 Explain Bitwise Operator.


Ans

18
A bitwise operator is an operator used to perform bitwise operations on bit patterns
or binary numerals that involve the manipulation of individual bits.

Bitwise operators are used in:

• Communication stacks where the individual bits in the header attached to the
data signify important information
• Embedded software for controlling different functions in the chip and
indicating the status of hardware by manipulating the individual bits of
hardware registers of embedded microcontrollers
• Low-level programming for applications such as device drivers,
cryptographic software, video decoding software, memory allocators,
compression software and graphics
• Maintaining large sets of integers efficiently in search and optimization
problems
• Bitwise operations performed on bit flags, which can enable an instance of
enumeration type to store any combination of values defined in an
enumerator list

Q10 Explain membership operator.


Ans
A Membership Operator in Python can be defined as being an operator that is
used to validate the membership of a value. This operator is used to test
memberships in variables such as strings, integers as well as tuples. Membership
Operators as a whole contain a number of different operators.

Q11 Explain python list constructor.


Ans
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
Without list comprehension you will have to write a for statement with a
conditional test inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

19
for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.

Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]

The condition if x != "apple" will return True for all elements other than "apple",
making the new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
newlist = [x for x in fruits]

Q12 Explain List Comprehension.


Ans
List comprehension in Python is an easy and compact syntax for creating
a list from a string or another list. It is a very concise way to create a new list by
performing an operation on each item in the existing list. List comprehension is
considerably faster than processing a list using the for loop.

List Comprehension Syntax:


20
[expression for element in iterable if condition]

As per the above syntax, the list comprehension syntax contains three parts: an
expression, one or more for loop, and optionally, one or more if conditions. The
list comprehension must be in the square brackets []. The result of the first
expression will be stored in the new list. The for loop is used to iterate over the
iterable object that optionally includes the if condition.

Suppose we want to find even numbers from 0 to 20 then we can do it using a for
loop, as shown below:

even_nums = []
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)

Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

The same result can be easily achieved using a list comprehension technique
shown below.

even_nums = [x for x in range(21) if x%2 == 0]


print(even_nums)

Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

The same result can be easily achieved using a list comprehension technique
shown below.

even_nums = [x for x in range(21) if x%2 == 0]


print(even_nums)
Unit 3
Q1 Explain the while loop with an example.
Ans
Python while Loop
Loops are used in programming to repeat a specific block of code. In this article,
you will learn to create a while loop in Python.

21
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate
beforehand.
Syntax of while Loop in Python
while test_expression:
Body of while
In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
Flowchart of while Loop

Flowchart for while loop in Python


Example: Python while Loop
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n

# To take input from the user,

22
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

When you run the program, the output will be:


Enter n: 10
The sum is 55

Q2 Make a simple calculator using if else.


Ans
# Python Program to build a Simple Calculator using Nested If
choice = int(input("Enter your choice:n")) # User's choice[1,2,3,4]if (choice>=1 an
d choice<=4):
print("Enter two numbers: ")
num1 = int(input())
num2 = int(input())

if choice == 1: # To add two numbers


res = num1 + num2
print("Result = ", res)

elif choice == 2: # To subtract two numbers


res = num1 - num2
23
print("Result = ", res)

elif choice == 3: # To multiply two numbers


res = num1 * num2
print("Result = ", res)

elif choice == 4: # To get quotient with decimal value


res = num1 / num2
print("Result = ", res)

elif choice == 5:
exit()
else:
print("Wrong input..!!")

Input:

Enter your choice:

Enter two numbers:

Output:

Result = 45

24
Q3 Explain Enumerate function with example.
Ans
Python enumerate() Function

Example
Convert a tuple into an enumerate object:

x = ('apple', 'banana', 'cherry')


y = enumerate(x)

Definition and Usage


The enumerate() function takes a collection (e.g. a tuple) and returns it as an
enumerate object.

The enumerate() function adds a counter as the key of the enumerate object.

Syntax
enumerate(iterable, start)

Q4 Write a Program to print letters of string “Silver Oak


University” except e and s.
Ans

Q5 Print first 10 even numbers using a while loop.


Ans
x = int(input("Enter a number: "))

i=1

25
while i <= x:

if i % 2 == 0:

print(i, end=" ")

i=i+1

Output:

Q6 Write a program whether the entered number is prime or not.


Ans
# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

26
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

Output
29 is a prime number

Q7 Explain the following with an example.


Ans
1. Range

Python range() Function


Example
x = range(6)
for n in x:
print(n)

Definition and Usage


The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and stops before a specified number.

Syntax
range(start, stop, step)

Parameter Values

27
In operator
Python “in” operator
Basically, the in operator in Python checks whether a specified value is a
constituent element of a sequence like string, array, list, or tuple etc. When
used in a condition, the statement returns a Boolean result evaluating into either
True or False

#in operator working

list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)

print(5 in list1) #True


print("is" in string1) #True
print(88 in tuple1) #False

Here:
Firstly, we have initialised a list list1, a string string1 and a tuple tuple1 with some
values. Then we use the in operator to check whether some values are part of the
above sequences or not.
As we can see from the above output, 5 in list1 evaluates into a True. Which
signifies that the value 5 is found inside the list.
Similarly, using the in operator we also confirm the presence of the
string “is” in string1. But for the last case, the condition results in
a False since 88 is not present inside the sequence tuple1.

2. Not in

28
Python “not in” operator
The not in operator in Python works exactly the opposite way as the in operator
works. It also checks the presence of a specified value inside a given sequence but
it’s return values are totally opposite to that of the in operator.
When used in a condition with the specified value present inside the sequence, the
statement returns False. Whereas when it is not, we get a True.
Let us take the previous example, just replacing in operator with the not in one.
#not in operator working

list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)

print(5 not in list1) #False


print("is" not in string1) #False
print(88 not in tuple1) #True
Output:

not in Output
As expected, the resultant output is the exact opposite of what we got earlier using
the in operator.

Unit 4
Q1 Explain the use and structure of function in python.
Ans

Q2 Explain arbitrary number of arguments in function.


Ans
The arbitrary arguments are passed as tuple (with one asterisk*) to the
function, (you can change it to a list as shown in the code) and calculate the sum

29
of its elements, by coding yourself using a for loop; if don't want to use the sum()
method of python.
What are arbitrary arguments in Python?

An arbitrary argument list is a Python feature to call a function with an


arbitrary number of arguments. It's based on the asterisk “unpacking” operator *
. To catch an arbitrary number of function arguments in a tuple args , use the
asterisk syntax *args within your function definition.

def mySum(*args):
if len(args) == 1:
return args[0]
else:
return args[-1] + mySum(args[:-1])
but when I tested mySum(3, 4), I got this error:

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Q3 Compare type conversion and coercion with example.


Ans
Type Conversion Type Coercion

Type Conversion Type Coercion

Type Conversion, just as the The automatic type conversion


name suggests, is the process of from one data type to another is
converting the type of objects called as Type Coercion. This is
from one data type into another also called as Implicit Type
as per requirement. Conversion.

30
Python supports various built-in The major difference between
type conversion functions such as Type Conversion and Type
int(), long(), float(), str() etc,. Coercion is that, type conversion
is done manually using built-in
This type of conversion is also functions where as type coercion
called as Explicit Type is done automatically.
Conversion or Type Casting.

Q4 Print sum of numbers from 1 to 5 using recursion.


Ans
# Python code to find sum
# of natural numbers upto
# n using recursion

# Returns sum of first


# n natural numbers
def recurSum(n):
if n <= 1:
return n
return n + recurSum(n - 1)

# Driver code
n=5
print(recurSum(n))

Output
15
Q5 Explain the inbuilt math function of python and explain any 2 with examples.
Ans

31
32
33
Pi

Pi is a mathematical constant defined as the ratio of the circumference


of a circle to the diameter of the circle.
Π = c/d
Where c is the circumference of the circle and d is the diameter of the
circle. The value of pi is 3.14. Pi (Π) can be accessed in Python as:

Code:

import math

math.pi

#3.141592653589793

34
Output:

Consider the following example where we used pi to find the circumference of a


circle:
Code:
import math

radius = 5

circumference = 2 * math.pi * radius

print ("Circumference of circle = ", circumference)


Output:

Euler’s Number (e)


Euler’s number is the base of the natural logarithm. It is denoted by symbol e. The
value of e is approximated to be 2.718. Euler’s number can be accessed in Python
as follows:
Code:
import math

math.e

#2.718281828459045
Output:

Tau

35
Tau (𝜏) is a mathematical constant, defined as the ratio of the circumference of the
circle to the radius of the circle.
math.tau = 2*pi
Check out the code below:

Code:
import math

math.tau

#6.283185307179586
Output:

Infinity
Infinity is a boundless entity that cannot be defined in numbers. In Python, positive
and negative infinities are defined as follows:
Code:
import math

math.inf

-math.inf
Output:

Infinity is used to compare given numbers to the absolute maximum and absolute
minimum values as demonstrated in the code below:
Code:
import math

x = 13.789

36
x < math.inf

x < -math.inf
Output:

Not a number (nan)


Not a number (nan) refers to non-numerical values. Not a number (nan) makes sure
that the value of a given numerical variable is a number.
Code:
import math

math.nan
Output:

floor() method
The floor() method of the math module rounds down a number to the nearest
integer. Syntax for floor() is given below:
Syntax:
math.floor(x)
x is the input number. The floor() method takes positive or negative numbers as
input.
The floor() method returns the nearest integer less than or equal to x. If the number
is a floating-point number, 10.89, floor() will return 10.
If the number is an integer, floor() will return the same integer. Consider the
following example:
Code:
import math

37
x = 3.5367

math.floor(x)

x=6

math.floor(x)
Output:

ceil() method
The ceil() method of the math module rounds up a number to the nearest integer.
Syntax for ceil() is given below:
Syntax:
math.ceil(x)
x is the input number. The ceil() method takes positive or negative numbers as
input.
The ceil() method returns an integer value greater than or equal to x. If the number
is a floating-point number, 10.89, ceil() will return 11.
If the number is an integer, ceil() will return the same integer. The following
example explains the ceil() method:

Code:
import math

x = 10.89

math.ceil(x)
38
x = 10

math.ceil(x)
Output:

math.sqrt()
The sqrt() method returns the square root of an input value. The syntax of sqrt() is
as follows:
Syntax:
math.sqrt(x)
x is the input number. It must be greater than or equal to 0. If x is less than 0
(negative number), sqrt() will return ValueError.
The sqrt() method returns a floating-point number. Consider the example below:
Code:
import math

math.sqrt(9)

math.sqrt(4)

math.sqrt(24)

math.sqrt(-49)
Output:

39
If the number is less than 0, we will have the following error:

math.fabs(x)
fabs represents the absolute function. The absolute function returns a non-negative
value of the given number.
It means that the absolute value of a positive number will be the same number and
if the given number is negative, the fabs function will convert it into a positive
number.
For example, the fabs value of -8 will be 8 and the fabs value of 8 will be 8. Syntax
of fabs is given below:
Syntax:
math.fabs(x)
x can be an integer or a floating-point.
The method will return a non-negative floating-point number. Consider the
following example:
Code:
import math

math.fabs(-3)

math.fabs(-89.9)

math.fabs(89)
40
Output:

The difference between math.fabs() method and the python’s abs() method is that
the math.fabs() method always returns a floating-point number.

math.pow(x)
The pow() method of the math module returns the value of input number x raised
to the power y that is xy.
The syntax for math.pow() is as follows:
Syntax:
math.pow(x, y)
x is the input number and y is the power of x. If x is 3 and y equals 4, it will mean:
34 = 3 * 3 * 3 * 3.
The function returns a floating-point value.
In mathematics, anything raised to power 0 equals 1, and 1 raised to power
anything also equals 1. Therefore, the pow() method will return 1.0 if y is 0 and x
is any number.
Similarly, pow() will return 1.0 if x is 1 and y is any number.
math.pow(x, 0.0) = 1.0

math.pow(1.0, y) = 1.0
Output:

Code:
import math

41
print("3 raised to power 4 = ", math.pow(3, 4))
Output:

math.isclose()
The isclose() method of the math module uses relative and absolute tolerance to
check the closeness of two values. Tolerance is defined as the threshold to check
the closeness of the numbers.
If the two numbers are close to each other, the isclose() method will return true and
return false if they are not close to each other.
The syntax of isclose() is given below:
Syntax:
math.isclose(a, b, rel_tol, abs_tol)

Q6 Explain the concept of lambda anonymous function with


examples.
Ans
What are lambda functions in Python?

In Python, an anonymous function is a function that is defined without a name.


While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.

How to use lambda Functions in Python?

A lambda function in python has the following syntax.

42
Syntax of Lambda Function in python
lambda arguments: expression
Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions can
be used wherever function objects are required.

Example of Lambda Function in python

Here is an example of lambda function that doubles the input value.

# Program to show the use of lambda functions


double = lambda x: x * 2

print(double(5))

In the above program, lambda x: x * 2 is the lambda function. Here x is the


argument and x * 2 is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to
the identifier double . We can now call it as a normal function. The statement

double = lambda x: x * 2

def double(x):
return x * 2
Use of Lambda Function in python

We use lambda functions when we require a nameless function for a short


period of time.

43
In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments). Lambda functions are
used along with built-in functions like filter() , map() etc.

Example use with filter()

The filter() function in Python takes in a function and a list as arguments.


The function is called with all the items in the list and a new list is returned
which contains items for which the function evaluates to True .

Here is an example use of filter() function to filter out only even numbers
from a list.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Unit 5
Q1 Explain the concept of string slicing along with examples.
Ans
In the previous lesson, you saw how you could access individual characters in a
string using indexing. In this lesson, you’ll learn how to expand that syntax to
extract substrings from a string. This technique is known as string slicing. You’ll
practice with the standard syntax, and learn how omitting the first or last index
extends the slice. You’ll also learn how to specify a stride in a string slice by using a
third index.

Here are some string slicing examples:

# Python program to demonstrate


# string slicing

44
# String slicing
String ='ASTRING'

# Using slice constructor


s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])

Output
String slicing
AST
SR
GITA

Q2 Write a program to find all occurrences of a substring in a


string. Example: He is John. John is fine. Expected output: The
count of John is: 2
Ans
Q3 What is string concatenation? Explain different ways to
concatenate strings.
Ans

String Concatenation
String concatenation means add strings together.

Use the + character to add a variable to another variable:

str1="Hello"
str2="World"
print ("String 1:",str1)

45
print ("String 2:",str2)
str=str1+str2

print("Concatenated two different strings:",str)

Output
String 1: Hello
String 2: World

Concatenated two different strings: HelloWorld

Use the * operator


Appending the same string to a string can be done using the * operator, as
follows:

str=str * x

• Where x is the number of times string str is appended to itself.

The following illustration shows how it is done:


str1="Hello"
print ("String 1:",str1)
str1=str1*3

print("Concatenated same string:",str1)

Output

String 1: Hello

Concatenated same string: HelloHelloHello

Q4 Write a program to check if a string is palindrome.


Ans
# function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]

46
# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")

Output
Yes

Q5 Strings are immutable. Explain.


Ans
An immutable object is one that, once created, will not change in its lifetime.

Example

Try the following code to execute:


name_1 = "Varun"
name_2 = "T"+ name_1[1:]
print("name_1 = ", name_1, "and name_2 = ", name_2)

Output
name_1 = Varun and name_2 = Tarun

Q6 List the inbuilt method of strings. Explain any 4 of them with


examples.
Ans

47
Python String Methods

48
49
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

50
# original string never changes
print("\nOriginal String")
print(text)

Output
Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Original String
geeKs For geEkS

Q7 What do you mean by Escape sequence?


Ans
Character combinations consisting of a backslash (\) followed by a letter or by
a combination of digits are called "escape sequences." To represent a newline
character, single quotation mark, or certain other characters in a character constant,
you must use escape sequences.

Q8 Explain any two methods of regular expression with examples.


Ans

51

You might also like