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

Python main

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

Python main

Uploaded by

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

Write a Python program to check if a given print('Can\'t divide by zero')

number is Armstrong print("ZeroDivisionError occurred and


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

You might also like