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

Paper Solution

Uploaded by

Faraz Niyazi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Paper Solution

Uploaded by

Faraz Niyazi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Q1 Explain the Programming Cycle for Python in detail.

Ans:- Python is an interpreted, high-level, general-purpose


programming language. A python
programming cycle consists of below main steps.
1. Design a solution
2. Write a code
3. Test the code
4. Debug the code
5. Repeat 2-4 until the program runs correctly.

Q1 Describe the concept of List Slicing with a suitable example.


Ans:- list is a collection of items that are ordered and changeable. One of
the most powerful
features of Python lists is slicing, which allows you to extract a subset of
the elements from
a list.
Slicing a list is done using the syntax list[start:end:step], where start is
the starting index of
the slice, end is the ending index (exclusive) of the slice, and step is the
step size between
each element in the slice
example of using list slicing to extract a subset of elements from a list:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# get the first three elements
print(my_list[:3]) # [0, 1, 2]
# get the elements from index 3 to index 6 (exclusive)
print(my_list[3:6]) # [3, 4, 5]
# get every other element starting from index 1
print(my_list[1::2]) # [1, 3, 5, 7, 9]
# get the last two elements
print(my_list[-2:]) # [8, 9]

Q3:- Show the way to import the module in python


There are different ways to import a module in Python, but the most
common ones are:
1. import statement: This statement is used to import a module into your
Python
script.
import math # import the math module
print(math.pi) # access the pi constant defined in the math module
2. from ... import statement: This statement is used to import specific
attributes,
functions, or classes from a module into your Python script.
from math import pi # import the pi constant from the math module
print(pi)
3. import ... as statement:This statement is used to import a module with
an alias
name to avoid naming conflicts with other objects in your code.
import math as m # import the math module with an alias name 'm'
print(m.pi)
4. from ... import * statement: This statement is used to import all the
attributes,
functions, or classes from a module into your Python script.
from math import * # import all attributes, functions, and classes
print(pi)

Q4 Differentiate between Python Arrays and lists?


Ans:- 1. Data type: Arrays can only store elements of the same data
type, while lists can store elements of
any data type.
2. Memory allocation: Arrays are allocated in contiguous memory
locations, which makes them more
efficient for numerical operations. Lists are implemented as dynamic
arrays that are dynamically
resized as needed, which can be time-consuming for large lists.
3. Size: Arrays have a fixed size, while lists are dynamic and can be
resized at any time.
4. Operations: Arrays have a smaller set of functions and methods than
lists, but they have additional
operations that are optimized for numerical operations, such as slicing,
indexing, broadcasting,
and vectorized operations. Lists have a wider range of built-in functions
and methods.
5. Import: Arrays are implemented using the array module or the numpy
library, which need to be
imported separately, while lists are built-in and do not require any
external imports.

Q5 Define floor division with an example.


floor division is a mathematical operation that returns the quotient of a
division rounded
down to the nearest integer. The floor division operator is represented by
//. Here's an
Example:
>>> 15 // 2
7
>>> -15 // 2
-8

Q6 Explain the difference between 'append' and 'extend' in Python?


Ans:- Both append() and extend() are methods used in Python to add
elements to a list. However,
they have some differences in terms of their functionality.
● append() is used to add a single element to the end of the list. It takes a
single
argument, which can be any data type, and adds it to the end of the list.
Here's an
example:
>>> my_list = [1, 2, 3]
>>> my_list.append(4)
>>> print(my_list)
[1, 2, 3, 4]
● extend() is used to add multiple elements to the end of the list. It takes
an
iterable, such as a list or a tuple, and adds each element of the iterable to
the end
of the list. Here's an example:
>>> my_list = [1, 2, 3]
>>> my_list.extend([4, 5, 6])
>>> print(my_list)
[1, 2, 3, 4, 5, 6]

Q7 What is a dictionary in Python?


dictionary is a built-in data structure that represents a collection of key-
value pairs.
Dictionaries are also known as associative arrays, maps, or hash tables in
other
programming languages. In a dictionary, the keys must be unique,
hashable, and immutable,
while the values can be of any data type and mutable.
Dictionaries are defined using curly braces {} and each key-value pair is
separated by a
colon :. Here's an example:
>>> my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
>>> print(my_dict)
{'name': 'John', 'age': 30, 'city': 'New York'}

Q8 What is object-oriented programming (OOP) in Python? Give


an example.
Ans:- Object-oriented programming (OOP) is a programming paradigm
that is based on the
objects that interact with one another.
concept of "objects", which can contain data and methods (functions)
that act on that data.
OOP allows for the creation of complex, reusable, and modular code by
organising it into
In Python, everything is an object, including built-in data types such as
integers, strings,
and lists. Python supports OOP through the use of classes, which are
templates for creating
objects. A class defines the attributes (data) and methods (functions) that
an object of that
class will have.
simple class in Python:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def description(self):
return f"{self.year} {self.make} {self.model}"
#We can create an object of the Car
my_car = Car('Toyota', 'Corolla', 2022)
# Now we can access the attributes of the my_car object and call its
methods:
print(my_car.make) # Output: Toyota
print(my_car.description()) # Output: 2022 Toyota Corolla

Q8 What will be the output of the following python code


Ans:- def count1(s):
vowels = "AEIOUaeiou"
count = 0
for c in s:
if c in vowels:
count += 1
return count
print(count1('I love India'))
The output of this code would be 6

Q9:- What will be the output of the following code?


Ans:- list1 = ['M', 'o', 'n', 'k', 'e', 'y']
print("@".join(list1))
Output: M@o@n@k@e@y
SECTION B

(a) Demonstrate five different built in functions used in the string.


Write a program to check whether a string is a palindrome or not.
Ans:- five different built-in functions used in Python strings:
1. len(): This function returns the length of a string, which is the number
of characters in the
string. For example:
s = "hello"
print(len(s)) # Output: 5
2. upper(): This function returns a new string with all the characters in
the original string
converted to uppercase. For example:
s = "hello"
print(s.upper()) # Output: HELLO
3. lower(): This function returns a new string with all the characters in
the original string
converted to lowercase. For example:
s = "HELLO"
print(s.lower()) # Output: hello
4. replace(): This function returns a new string with all occurrences of a
specified substring
replaced with another substring. For example:
s = "hello world"
print(s.replace("world", "Python")) # Output: hello Python
5. split(): This function splits a string into a list of substrings based on a
specified delimiter.
For example:
s = "hello,world"
print(s.split(",")) # Output: ['hello', 'world']
Now, here's a program to check whether a string is a palindrome or not:
def is_palindrome(s):
# Convert the string to lowercase and remove whitespace
s = s.lower().replace(" ", "")
# Check if the string is equal to its reverse
return s == s[::-1]
# Test the function with some examples
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("Hello, world")) # Output: False
print(is_palindrome("A man a plan a canal Panama")) # Output: True

(b) Explain the following loops with a flow diagram, syntax, and
suitable examples
Ans:- 1. For Loop : The for loop is used to iterate over a sequence (such
as a list, tuple, string, etc.)
and execute a block of code for each element in the sequence. Here is
the syntax of a for
loop in Python:
for var in sequence:
statement(s)
Example
py_list = ['Apple','Mango','Guava','Pineapple']
i=1
#Iterating over the list
for item in py_list:
print ('Item ',i,' is ',item)
i = i+1
Output:
Item 1 is Apple
Item 2 is Mango
Item 3 is Guava
Item 4 is Pineapple

2. While loop: Loops are either infinite or conditional. Python while


loop keeps reiterating a block of code defined inside it until the desired
condition is met.
Ans:- Syntax
while(expression)
statement(s)
Example
n=0
count = 0
while count < 5:
if n % 2 == 0:
print(n)
count += 1
n += 1
Output:
0
2
4
6
8

(c) Explain the continue, break, and pass statements with a suitable
example.
Ans:- In Python, continue, break, and pass are three statements used to
alter the flow of control in loops
and conditional statements.
1. continue: The continue statement is used to skip the current iteration
of a loop and move
on to the next iteration.
Example:
for i in range(1, 11):
if i % 2 == 0:
continue # skip even numbers
print(i)
Output :
1
3
5
7
9
2. break: The break statement is used to exit a loop prematurely, even if
the loop's condition
has not been met.
Example
for i in range(1, 11):
if i == 5:
break # exit loop when i equals 5
print(i)
Output
1
2
3
4
3. pass: The pass statement is used as a placeholder when no action is
required in a block of
code. It is typically used as a placeholder for code that has not yet been
implemented.
Example:
for i in range(1, 11):
if i % 2 == 0:
pass # do nothing for even numbers
else:
print(i)
Output
Copy code
1
3
5
7
9

(d) Develop a program to calculate the reverse of any entered


number.
Ans:- num = int(input("Enter a number: "))
reverse = 0
while num > 0:
remainder = num % 10
reverse = (reverse * 10) + remainder
num = num // 10
print("The reverse of the entered number is:", reverse)
output
Enter a number: 12345
The reverse of the entered number is: 54321

(e) Explain the list Comprehension with any suitable example.


Ans:- List comprehension is a concise and elegant way to create a new
list from an existing one,
using a single line of code. It is a powerful and widely-used feature in
Python.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
In this example, we have a list of numbers [1, 2, 3, 4, 5]. We want to
create a new list that
contains the squares of these numbers. We could do this using a for loop
like so:
numbers = [1, 2, 3, 4, 5]
squares = []
for x in numbers:
squares.append(x**2)
print(squares)
This would give us the same result as the list comprehension version.
However, the list
comprehension is a more concise and readable way to achieve the same
result.
The output of the program will be:
[1, 4, 9, 16, 25]

SECTION C
1. Attempt any one part of the following:
(a) Illustrate Unpacking Sequences, Mutable Sequences, and List
comprehension with examples.
Ans:- Unpacking Sequences:
1. Unpacking sequences is the process of assigning the values of a
sequence (e.g., a tuple, list)
to multiple variables in a single statement. Here's an example:
t = (1, 2, 3)
a, b, c = t
print(a, b, c)
Output :
123
2. Mutable Sequences:
Mutable sequences are sequences (e.g., lists) that can be changed after
they are created.
Here's an example of how to use a list, which is a mutable sequence, to
add or remove
elements:
my_list = [1, 2, 3, 4]
my_list.append(5) # add an element to the end of the list
print(my_list)
my_list.remove(2) # remove an element from the list
print(my_list)
Output
[1, 2, 3, 4, 5]
[1, 3, 4, 5]
3. List Comprehension:
List comprehension is a concise way to create a new list by applying a
transformation to
each element of an existing list. Here's an example:
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]

You might also like