0% found this document useful (0 votes)
379 views7 pages

Python Programming Question Bank

Uploaded by

kavyagouda257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
379 views7 pages

Python Programming Question Bank

Uploaded by

kavyagouda257
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT

(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

INTRODUCTION TO PYTHON PROGRAMMING


QUESTION BANK
MODULE -1
1. State and explain any six features of python.
2. State any six applications of python.
3. Explain input command in python with suitable example.
4. Explain print command in python with suitable example.
5. State which of the following python statements are valid and invalid.
a. print("ksk", + "123")
b. print("ksk" '+' "123")
c. print("ksk", '+', "123")
d. print('ABC is a "technological" University')
e. print(2 + '3')
f. print('2' * 3)
6. What will be the output of the following print statements?
a. print('abc' * 2)
b. print(3+4j + 2+1j)
c. print(3*2 // 4)
7. State which of the following Python statements are valid and invalid.
a. x = input("enter a number")
b. x = input()
c. x = input("")
d. x = input(" ' ")
e. x = input(2)
f. x = input("2" + "3")
8. What will be the value of variables x & y after executing the Python program?
Assume that user enters a value 5.
a. temp=input("enter a number")
b. x=temp*5
c. y=int(temp)*5
9. What will be the output of the following program? Assume that the user will enter
only integer value.
a. temp=input("enter a number")
b. x=temp*0
c. y=int(temp)*0
d. print(x)
e. print(y)
10. What are the types of following variables?
a. a = 55
b. b = ‘3 + 4j’
c. c = “1DBATU”
d. e = a
e. f = b+c
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

11. Rewrite the following code with proper indentation to get the output as
Expected output
cube of 1 is:1
square of 2 is:4
cube of 3 is:27
square of 4 is:16
cube of 5 is:125
Code without indentation
abc = [1,2,3,4,5]
for x in abc:
if x%2 == 0:
print("square of ", x , "is:")
print(x**2)
else:
print("cube of ", x , "is:")
print(x**3)
12. What will be the output of the following print statements?
a. print(123,"\nabc")
b. print("****","\\n***","\\n**","\\n*")
c. print(" ' " ' " " ' " ' ")
13. Explain any six arithmetic operators of Python with suitable examples of each.
14. Explain any six assignment operators of Python with suitable examples of each.
15. Explicate all comparison operators of Python with suitable examples of each.
16. Explain the “and, or, not” operators of Python with suitable examples of each.
17. Explain the while loop with a suitable example.
18. Explain the for loop with a suitable example.
19. Explain the break and continue statement with a suitable example of each.
20. What will be the output of the following Python statements?
a. print(23 // 5)
b. print(2 != 2)
c. print(2 < 0)
21. Develop a Python program to read student details like name, USN, and marks of 3
subjects and display student information with total and percentage.
22. Design a program to find the area of a circle, triangle, and rectangle
23. Design a program to check if a number is odd or even
24. Design a program to check if a number is positive, negative or zero
25. Design a program to check if a number is prime or not
26. Why does this expression cause an error? How can you fix it?
a. 'I have eaten ' + 99 + ' burritos.'
27. Explain three functions that can be used to get the integer, floating-point number, or
string version of a value.
28. Evaluate the following expressions:
a. (5 > 4) and (3 == 5)
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

b. not (5 > 4)
c. (5 > 4) or (3 == 5)
d. not ((5 > 4) or (3 == 5))
e. (True and True) and (True == False)
f. (not False) or (not True)
29. Design a Python code that prints Hello if 1 is stored in spam, prints Howdy if 2 is
stored in spam, and prints Greetings! if anything else is stored in spam.
30. Differentiate between range(10), range(0, 10), and range(0, 10, 1) in a for loop?
31. Write a short program that prints the numbers 1 to 10 using a for loop. Then write an
equivalent program that prints the numbers 1 to 10 using a while loop.
32. Illustrate the Starting, Stopping, and Stepping Arguments to range()
33. Explain different Flow Control Statements in Python
34. Design a program to display all prime numbers within a range
35. Design a program to find the largest of 2 numbers
36. Design a program to find the largest of 3 numbers using flow control and Boolean
operators
37. Design a program to find the factorial of a number
38. Design a program to implement a calculator in python
39. Design a program to check for leap year
40. Design a program to check if a number is an Armstrong Number.( Armstrong number
is a number that is equal to the sum of cubes of its digits for a 3 digit [Link]: 153
= 13+53+33)
41. Design a program to check if a number is a palindrome or not
42. Design a program to count the number of occurrences of each digit in a number
43. Design a program to swap two numbers
44. Design a program on if, elif, else statements, while and for loops
45. List the naming convention rules for variables. Identify the valid and invalid variables
among the following with proper reasoning i)account num ii)num3 iii) my_name iv)
7days v) amtin$
46. Analyse the following code for adding 2 numbers. What is the output generated? Will
the output generated be as expected? If not, explain why. Change the code to get the
desired output
a. a=input()
b. a=input()
c. print(a+b)
47. Explain the different ways of importing modules to a Python program with examples.
48. Explain with an example the elements of flow control
49. Write the evaluation steps for the given statement if myAge is ‘25’
a. print('You will be ' + str(int(myAge) + 1) + ' in a year.')

MODULE-2
1. With syntax and example explain how a function is defined in Python
2. Explain return values and return statements
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

3. Illustrate the keyword arguments for print() function


4. Demonstrate the concept of Local and Global Scope in functions with suitable
examples
5. Explain the significance of the global statement
6. Explain indexing and negative indexing in strings and lists
7. Develop a program to generate a Fibonacci sequence of length (N). Read N from the
console.
8. Demonstrate with a suitable example how exceptions are handled in Python.
9. Write a function to calculate factorial of a number with and without recursion.
10. Explain print command in python with suitable example.
11. Develop a Python program to demonstrate different list methods
12. Distinguish between the remove() and pop() methods with code snippets.
13. Distinguish between the insert() and append() methods with code snippets.
14. Differentiate between the copy() and deepcopy() methods with code snippets.
15. Develop a python program to accept n numbers and store them in a list. Then print the
list without ODD numbers in it.
16. Demonstrate the working of keys(),values() and items() methods with examples.
17. Explain the significance of References in Lists
18. Demonstrate the working of in and not in operator.
19. Explain how a cleaner display of the items in a dictionary can be achieved
20. Differentiate between Mutable and Immutable Data Types
21. Develop a program to read a message and create a dictionary of the characters in the
message as keys and their count as values.
22. Explain the working of get() method
23. Explain the working of setdefault() method in dictionary datatype
24. Develop a program to illustrate nested dictionaries
25. Develop a program to create a dictionary of Names and birthdays by taking the input
from the user. Display the birthdate of the person based on their Name.
26. Apply string justification methods to create a menu
27. Explicate Escape characters, raw string, multiline strings, and multiline comments
with examples
28. Explain slicing in strings and lists
29. Demonstrate join() and split() methods on strings with examples
30. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages using functions.
31. Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
32. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable messages.
33. Write a function named DivExp which takes TWO parameters a, b and returns a value
c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception
for when b=0. Develop a suitable program which reads two values from the console
and calls a function DivExp.
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

34. What is the difference between lists and tuples?


35. What are the different ways to remove values from a list?
36. What are the different ways to insert values into a list?
37. Explain how references are passed to functions
38. Illustrate Augmented Assignment Operators
39. Demonstrate the Multiple Assignment Trick
40. Given spam = ['cat', 'bat', 'rat', 'elephant'] Evaluate the following statements
a. spam[0:4]
b. spam[1:3]
c. spam[0:-1]
d. spam[:2]
e. spam[1:]
f. spam[:]

MODULE-3
1. Demonstrate different isX String Methods
2. Explain Copying and Pasting Strings with the pyperclip Module
3. Demonstrate the working of strip(), rstrip(), and lstrip()
4. Given name = 'Zophie', Evaluate the following statements
a. name[0]
b. name[-2]
c. name[0:4]
d. 'z' in name
e. name[7] = 'the'
5. What does the code for an empty dictionary look like?
6. What does a dictionary value with a key 'foo' and a value 42 look like?
7. What is the main difference between a dictionary and a list?
8. What happens if you try to access spam['foo'] if spam is {'bar': 100}?
9. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in
spam and 'cat' in [Link]()?
10. If a dictionary is stored in spam, what is the difference between the
11. expressions 'cat' in spam and 'cat' in [Link]()?
12. What is a shortcut for the following code?
if 'color' not in spam:
spam['color'] = 'black'
13. What module and function can be used to “pretty print” dictionary values?
14. What are escape characters?
15. What do the \n and \t escape characters represent?
16. How can you put a \ backslash character in a string?
17. The string value "Howl's Moving Castle" is a valid string. Why isn’t it a problem that
the single quote character in the word Howl's isn’t escaped?
18. If you don’t want to put \n in your string, how can you write a string with newlines in
it?
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

19. What do the following expressions evaluate to?


• 'Hello world!'[1]
• 'Hello world!'[0:5]
• 'Hello world!'[:5]
• 'Hello world!'[3:]
20. What do the following expressions evaluate to?
• 'Hello'.upper()
• 'Hello'.upper().isupper()
• 'Hello'.upper().lower()
21. What do the following expressions evaluate to?
'Remember, remember, the fifth of November.'.split()
'-'.join('There can be only one.'.split())
22. What string methods can you use to right-justify, left-justify, and center a string?
23. How can you trim whitespace characters from the beginning or end of a string?
24. Explain the working of get() method and setdefault() methods in dictionary datatype
25. Develop a program to create a dictionary of Names and birthdays by taking the input
from the user. Display the birthdate of the person based on their Name.
26. Apply string justification methods to create the following output using the dictionary
datatype
-----------DESTINATION-----------
DAY 1………. BANGALORE
DAY 2………. MYSORE
DAY 3………. BADAMI
DAY 4………. CHITRADURGA
27. Analyse the following statements and write the output.
Given str= ‘Welcome to DSATM’
i) str[-5]
ii) str[16]
iii) 'he' in 'Hello'
iv) str[:6]
v) str[5:-4]

28. Illustrate how Strings can be substituted using the sub() Method. Demonstrate the
working of different flags.
29. Illustrate greedy and non-greedy matching techniques with examples.
30. Develop a python program to search the text in a file for phone numbers
(+919900889977) and email addresses (sample@[Link]).
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New Delhi)
(6 Branches CSE, ISE, ECE, EEE, ME& CE Accredited 3 years by NBA, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

31. Determine the regular expressions to generate the following patterns


i. Date of form DD/MM/YYYY or DD-MM-YYYY
(Note: Day and Month can be 1 digit or 2 digits, Year must be 4 digits)
ii. USN of form NAANNAANNN
(Note: N- Number, A- Alphabet)
iii. PAN number of form AAAAANNNNA
(Note: N- Number, A- Alphabet)
iv. email id Ex: sample@[Link]
v. Phone number of the form +919999999999
32. Determine the patterns matched by the following regular expressions with examples. Justify
your answer
i. \d{10}
ii. \d+\s[a-zA-Z]+
iii. (ha)*
iv. DS(CE|ATM)
v. \w{3,5}

MODULE-4
1. Demonstrate different operations that can be performed on files with code snippets.
2. Differentiate between class attributes and instance attributes with suitable examples
for each.
3. Differentiate between aggregation and composition with examples
4. Apply Pandas library to create a column containing names of Indian Cities and a table
with student details for Name, USN, IA1, IA2, and IA3.

Common questions

Powered by AI

Lists in Python are mutable, meaning their elements can be changed, added, or removed, making them useful for datasets that need alteration. They can be defined as `my_list = [1, 2, 3]`. Tuples, defined as `my_tuple = (1, 2, 3)`, are immutable, providing safety in multi-threaded environments and constant data handling. Choosing between them depends on whether data needs to be modified. Use lists when you expect data changes, and tuples when data should remain constant .

Exception handling in Python is managed using the `try`, `except`, `finally`, and `else` blocks. A specific need for exception handling arises when dealing with potential division by zero. For instance, wrapping the division code in a `try` block allows you to catch the exception using `except ZeroDivisionError`. This ensures that the program can address or mitigate the error safely, providing the user with an appropriate message or fallback action .

Slicing in Python allows accessing a range of elements from strings or lists using the syntax `object[start:stop:step]`. Negative indexing can be useful to start counting from the end of the list or string. For example, `my_list[-1]` accesses the last element, while `my_list[-3:]` retrieves the last three elements. Similarly, `my_string[1:-1]` extracts all characters except the first and last ones .

In Python, the 'break' statement is used to terminate the loop prematurely when a certain condition is met. For instance, if we have a loop `for i in range(5):`, adding `break` when `i == 3` would stop the loop when `i` becomes 3 . Conversely, the 'continue' statement skips the current iteration and jumps to the next one. For the same loop, using `continue` when `i == 3` will skip the value 3 from any further code execution within that loop iteration .

The `global` keyword allows you to modify a variable outside the current scope, typically at the module level. In Python, variables defined inside a function are local by default. By using `global`, you can declare that a variable inside the function is globally accessible and modifiable. For example, `global x; x = 10` inside a function will modify the global variable `x` rather than creating a local counterpart .

Mutable data types in Python allow their elements to be changed, added, or removed, while immutable data types do not allow this kind of modification. Lists are an example of a mutable data type because you can add, remove, or change elements within a list. For example, with a list `my_list = [1, 2, 3]`, you can do `my_list.append(4)` to make it `[1, 2, 3, 4]`. On the other hand, tuples are immutable; if `my_tuple = (1, 2, 3)`, trying to `my_tuple[0] = 4` would cause an error .

Assertions are used in Python to test assumptions in your code, acting as automated sanity checks. They help in debugging and can ensure that a function behaves as expected. For example, `assert x > 0, "x must be positive"` checks if x is positive. If the condition is false, it raises an AssertionError with the specified message. This mechanism is crucial for maintaining robust and error-free code .

In Python, the 'and' operator returns True if both operands are true, otherwise it returns False. For example, `(5 > 4) and (3 == 3)` evaluates to True . The 'or' operator returns True if at least one of the operands is true. For example, `(5 > 4) or (3 == 5)` is True because the first expression is true . The 'not' operator reverses the truth value; thus, `not (5 > 4)` evaluates to False .

The `remove()` method in Python deletes the first occurrence of a specified value from the list. For instance, with `my_list = [1, 2, 3, 1]`, `my_list.remove(1)` would result in `[2, 3, 1]`. On the other hand, `pop()` deletes the value at a specified index, defaulting to the last item if no index is given. Using `my_list.pop(0)` on the same list would remove the element at index 0, resulting in `[2, 3, 1]` .

`join()` is used to concatenate a list of strings into a single string with a specified separator. For example, `'-'.join(['a', 'b', 'c'])` results in `'a-b-c'`. `split()` divides a string into a list using a specified delimiter, such as `'a-b-c'.split('-')`, which gives `['a', 'b', 'c']`. These methods are practical for tasks like handling CSV data, where `split()` can parse input lines, and `join()` can prepare data output .

You might also like