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

PythonReduction

Uploaded by

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

PythonReduction

Uploaded by

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

Q1. What is dry run? Q11.

Define identifiers
Ans. Dry run is a technique used by Python Ans. Identifier is a user-defined name used to
developers to test their scripts or programs identify a variable, function, class, module etc
without actually executing any of the actions in the program. There are following some
they are designed to perform. rules to name an identifier • It can be the
Q2. List the types of type conversion in combination of alphabets and digits but it
Python. must start with an alphabet or underscore
Ans. implicit type conversion and explicit only. • It must not contain any whitespace or
type conversion. special character except underscore • It must
not be similar to any keywords • It is case-
Q3. What is the use of pass statement?
sensitive. Examples of valid identifiers: a123,
Ans. The pass statement is used as a
_mks, roll_no, etc Examples of invalid
placeholder for future code. identifiers: 123a, roll no, web-tech etc.
Q4. Explain the function enumerate (). Q12. Explain backward indexing in strings.
Ans. allows you to keep track of the Solution:
number of iterations (loops) in a loop. Backward indexing starts from -1,-2,-3…,
Q5. Explain the extend method of list. where -1 is the last element in a string, -2 is
Ans. used to add elements of an iterable the second last and so on.
(such as string, list, tuple, set, etc.) to the Example: mystr = 'Omkar’
end of another list. print(mystr[-1])
Q6. What are required arguments in print(mystr[-2])
function? print(mystr[-11:-8])
print(mystr[::-1])
Ans. the arguments passed to a function in
Q13. Explain any 2 metacharacters used
correct positional order.
in regular expression
Q7. Explain any 2 functions in time
Ans. r'Char[mander|meleon|izard]'
module.
matches “Charmander “, “Charmeleon “,
Ans. time.ctime() Defined as the time and “Charizard.”
where we pass seconds since epoch in a
Q14. How to handle exception in Python?
variable argument and returns a time
Ans. The "try" keyword is used to specify a
string that represents the local current
block where we should place an exception
time.
code. It means we can't use try block
time.asctime()calculates the current time
alone. The try block must be followed by
in hour:minutes format.
either catch or finally. The "catch" block is
Q8. What are the types of file in Python?
used to handle the exception.
Ans. There are mainly two types of data
Q15.What is the use of pass statement?
files — text file and binary file.
Solution: The pass statement is a null
1.Text files 2. Binary files
statement used as a placeholder for
Q9. Write the use of seek & tell function.
future code. It is generally used in empty
Ans. Seek-The seek() function in Python is
code to avoid error because empty code is
used to move the file cursor to the
not allowed in loops, function definition,
specified location. Tell-The tell() method class definition or in if statement. When
returns the current file position in a file
the pass statement is executed, nothing
stream
happens.
Q10. Explain any 2 built-in list functions.
Q16.Explain the extend method of list.
Ans. hash() – Returns the hash value of a
Solution: The extend() method adds each
specified object
element of the passed iterable to the end
help() – Executes the built-in help system
of the current list. Syntax:
id() – Returns the id of an object.
list.extend(iterable)
Q1. Write a short note on datatypes in Q3. What is a module? What is package?
Python. Explain with example.
Ans. in Python, data types classify the Ans. in programming, a *module* is a file
various types of data that can be used in containing Python code. It can define
programming. Some common data types functions, classes, and variables that can
include: be used in other Python files. For
Numeric: Integers (int), floating-point example, if you create a file named
numbers (float), and complex numbers utils.py with various helper functions like
(complex). calculate, validate, etc., utils.py is a
Sequence Types: Lists (list), tuples (tuple), module that can be imported into other
and strings (str). Python scripts.
Mapping Type: Dictionary (dict), which A *package* is a collection of modules
stores key-value pairs. that are organized in a directory. It
Boolean Type: bool, representing True or contains an additional __init__.py file to
False. mark the directory as a Python package.
Set Types: Sets: (set), which store unique For instance, if you have a directory
elements. named my_package with utils.py inside it
None Type: None, representing absence and an __init__.py file, my_package
of a value. becomes a package. Other scripts can
Python is dynamically typed, meaning you import modules from this package like
don't need to declare the type of a from my_package import utils.
variable explicitly; the interpreter infers it So, modules are individual files, while
based on the value assigned. packages are directories containing
Q2. Write a short note on exception multiple modules in Python.
handling. Q4.Explain any 2 built-in list functions.
Ans. When a function detects an Solution:
exceptional situation, you represent this append(): The append() method appends an
with an object. This object is called an element to the end of the list Syntax:
list.append(element) where, element can be
exception object. In order to deal with the
of any type i.e. string, number, object etc •
exceptional situation, you throw the
insert(): The insert() method inserts the
exception. This passes control, as well as specified value at the specified position
the exception, to a designated block of Syntax: list.insert(pos,element) where, pos is
code in a direct or indirect caller of the a number specifies position of the inserted
function that threw the exception. This value and element can be of any type i.e.
block of code is called a handler. In a string, number, object etc
handler, you specify the types of Example:
exceptions that it may process. The C++ mylist = ['java','python','php']
run time, together with the generated mylist.append('web technology')
code, will pass control to the first print(mylist)
mylist.insert(1,'cpp')
appropriate handler that is able to process
print(mylist)
the exception thrown. When this
happens, an exception is caught. A
handler may rethrow an exception so it
can be caught by another handler.
Q5. How to handle exception in Python? Q2. Write a Python program to display
Solution: An exception can be defined as an power of 2 using anonymous function.
abnormal condition in a program which may Solution:
occur during execution. Whenever an terms=int(input("Enter the number of
exception occurs, it will interrupt the flow of terms?"))
the program and program will get aborted i.e. result = list(map(lambda x: 2 ** x,
improper termination. Such exceptions can be range(terms)))
handled in python by using try block and print("The total number of terms :", terms)
except block. The code that can raise for i in range(terms):
exceptions are kept inside try block and the print("2 raised to power", i, "is", result[i])
code that handle the exception are written Q3. Write a Python program to print even
within except block. There may be more than length words in a string
one except block after try block. There may be Solution:
optional else block and finally block in str = input('Enter a string : ')
exception handling mechanism. words = str.split(" ")
Syntax: print('Even length words in given string are as
try: #block of code(s) follows')
except Exception1: for w in words: if len(w) % 2 == 0:
#block of code(s) print(w)
except Exception2: Q4. Write a Python program to check for
#block of code(s) Zero Division Error Exception.
else: Solution:
#this code executes if no except block is a = int(input("Enter a number:"))
executed b = int(input("Enter another number:"))
finally: try:
#must executable block of code(s) if b==0: raise ZeroDivisionError
-- If no exception occurs, all except blocks will else: c = a/b
get skipped and program continues further. print('Result : ',c)
-- If an exception occurs within try clause, the except ZeroDivisionError:
control immediately passes to an appropriate print('Can\'t divide by zero')
except block and after handling exception print("ZeroDivisionError occurred and
program continues further. handled")
-- We can keep some codes in else block Q5. Write a Python program to find gcd of a
which will be executed if no exception occurs. number using recursion.
-- And the code which we want to be Solution:
executed compulsory, can be kept in finally def gcd(a, b):
block. We can use a finally block along with if (b == 0):
try block only. return a
Q1. Write a Python program to check if a else: return gcd(b,a%b)
given number is Armstrong. a = int(input('Enter a number: '))
Solution: b = int(input('Enter another number : '))
no = int(input('Enter a number:')) x = gcd(abs(a),abs(b))
no1 = no print("The gcd of",a,"and",b,"is",x)
sum = 0
while(no>0): d = no%10 sum = sum + (d**3)
no = no//10
if sum==no1: print(no1,'is armstrong number')
else: print(no1,'is not armstrong number')
Q6. Write a Python program to check for Q9. What is dictionary? Give example.
Zero Division Error Exception. Solution:
Solution: Dictionary is a collection of key-value pairs. It
a = int(input("Enter a number:")) is a mutable, unordered, and iterable data
b = int(input("Enter another number:")) type. Each key in a dictionary must be unique,
try: and the values can be of any data type,
if b==0: including other dictionaries. Dictionaries are
raise ZeroDivisionError defined using curly braces ()', and the key-
else: c = a/b print('Result : ',c) value pairs are separated by colons.
except ZeroDivisionError: Q10 j) What is lambda function? Give
print('Can\'t divide by zero') example.
print("ZeroDivisionError occurred and Solution:
handled") Lambda function is a concise way to create
Q7. What are the advantages of Python? anonymous or unnamed functions. Lambda
Ans. functions are often used for short-lived
1.Readability and Simplicity: Python operations where a full function definition is
emphasizes readability and clean code, not necessary.
making it easy for developers to write and Syntax:
maintain code. lambda arguments: expression
2.Large Standard Library: Python comes with
a comprehensive standard library that
provides modules and packages for a wide
range of tasks.
3.Community and Support: Python has a
large and active community of developers.
This community contributes to the language's
growth, shares knowledge, and provides
support through forums, mailing lists, and
other online platforms.
4.Diverse Application Domains: Python is
suitable for a wide range of applications, from
web development and data science to
artificial intelligence and automation. Open
5.Source and Free: Python is an open-source
language, and its interpreter is freely available
Q8. Demonstrate set with example.
Solution:
Set is an unordered collection of unique
elements. Sets are defined by enclosing a
comma- separated list of elements inside
curly braces
Example:
myset (1,2,3,4,5)
print("Set:",myset)
myset.add(6)
myset.add(3)
print("Modified Set:", myset)
myset.remove(2)
print("Set after removal:", myset)

You might also like