0% found this document useful (0 votes)
31 views18 pages

HIGH Chances Pyton Qustion Answer in 2024

Uploaded by

ranajitbarik2005
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)
31 views18 pages

HIGH Chances Pyton Qustion Answer in 2024

Uploaded by

ranajitbarik2005
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/ 18

Created by: - RONI☺

High-Chance MCQs, SAQs, and Long Questions with Answers

Based on the consistent patterns in the provided question papers, below are important questions divided into
MCQs, SAQs (Short Answer Questions), and Long Answer Questions. These questions have a high
probability of appearing in the December 2024 semester.

MCQs with Answers

1. Which of the following is not a valid way to import a module in Python?


o (a) import module_name
o (b) from module_name import *
o (c) include module_name (Answer) INCLUDE USING IN C
o (d) import module_name as alias
2. How do you define an empty dictionary in Python?
o (a) empty_dict = {} (Answer) dectanary is inelisize in carley baress {}
o (b) empty_dict = []
o (c) empty_dict = ()
o (d) empty_dict = set()
3. What does the len() function do in Python?
o (a) list.count()
o (b) len(list) (Answer) len function is used in calculate the string length
o (c) list.length()
o (d) list.size()
4. What is the purpose of the join() method in Python?
o (a) Splits a string into a list of substrings
o (b) Checks if two strings are equal
o (c) Concatenates multiple strings with a separator (Answer) join() is used for add the string in other
o (d) Converts a string to lowercase string
5. Which of the following loops is used to iterate over a sequence in Python?
o (a) for loop (Answer)
o (b) while loop
o (c) until loop
o (d) do-while loop
6. What does the input() function do in Python?
o (a) Displays text on the screen
o (b) Imports external modules
o (c) Takes user input from the keyboard (Answer)
o (d) Generates random numbers

SAQs with Answers

1. What is Python? What are its features?


o Python is a high-level, interpreted language known for simplicity and versatility.
o Features: Easy syntax, dynamic typing, extensive libraries, cross-platform, and OOP support.
2. What is the difference between a list and a tuple?
o List: Mutable, created using [].
o Tuple: Immutable, created using ().
3. Explain the use of break and continue statements in loops.
o break: Exits the loop prematurely.
o continue: Skips the current iteration and moves to the next.
4. What is a Python dictionary?
o A dictionary is a collection of key-value pairs, defined using {}. Example:

python
Copy code
my_dict = {"name": "Alice", "age": 25}

5. What is the purpose of the else clause in loops?


o The else clause executes when the loop completes without encountering a break statement.
6. Explain default and variable-length arguments in Python functions.
o Default arguments: Provide a default value if no argument is passed.
o Variable-length arguments: Allow passing multiple values using *args or **kwargs.

Long Questions with Answers

1. Explain Python's file handling methods with examples.


o Modes: r (read), w (write), a (append).
o Methods:

python
Copy code
with open("file.txt", "w") as file:
file.write("Hello, World!") # Writing to a file
with open("file.txt", "r") as file:
content = file.read() # Reading from a file
print(content)

2. Differentiate between local and global variables with examples.


o Local variable: Defined inside a function and accessible only there.
o Global variable: Defined outside any function and accessible throughout the program.
Example:

python
Copy code
x = 10 # Global
def my_function():
x = 5 # Local
print(x)
my_function()
print(x)

3. What is Django? Explain the MVC architecture.


o Django is a Python web framework for building applications.
o MVC (Model-View-Controller):
 Model: Handles data.
 View: Displays data to the user.
 Controller: Manages user interaction and updates the model/view.
4. Write a Python program to check if a number is prime.

python
Copy code
num = 7
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")

5. What are Python's different data types?


o Common types:
 int: Integer values.
 float: Decimal values.
 str: Text strings.
 list: Ordered, mutable collections.
 tuple: Ordered, immutable collections.
 dict: Key-value pairs.
6. Explain slicing with examples.
o Slicing is used to extract a portion of a sequence. Syntax: [start:end:step].
Example:

python
Copy code
lst = [1, 2, 3, 4, 5]
print(lst[1:4]) # Output: [2, 3, 4]
print(lst[::-1]) # Output: [5, 4, 3, 2, 1]

Recommendations for December 2024

Additional High-Chance Questions with Answers


2
MCQs with Answers

1. What is the output of list(range(2, 6))? 2 is the start and 6 is the stop
value
o (a) [2, 3, 4, 5] (Answer)
o (b) [2, 3, 4, 5, 6]
o (c) (2, 4, 6)
o (d) [2, 5]
2. How do you remove an item from a list by its value?
o (a) pop()
o (b) remove() (Answer) remove is the list operation
o (c) delete()
o (d) discard()
3. Which of the following is a Python tuple?
o (a) {1, 2, 3}
o (b) [1, 2, 3]
o (c) (1, 2, 3) (Answer) tuple is inilize the parenthesis bracket "()"
o (d) None of these
4. What will be the output of print("diploma"[2:-1])?
o (a) plo
o (b) iplom (Answer) start in 2 index is i
o (c) diploma and -1 is stop index in last
o (d) Error
5. Which function converts a string to uppercase?
o (a) lower()
o (b) upper() (Answer)
o (c) capitalize()
o (d) None of these
6. Which operator has the lowest precedence in Python?
o (a) *
o (b) **
o (c) or (Answer) or in the low precedencs
o (d) and

SAQs with Answers

1. What is slicing in Python?


o Slicing is used to extract a specific portion of a sequence (like a list or string). Syntax:
[start:end:step].
Example: "hello"[1:4] → "ell".
2. What is the difference between break and continue?
o break: Terminates the loop entirely.
o continue: Skips the current iteration and moves to the next.
3. What is the purpose of the len() function?
o It returns the length (number of elements) of a sequence or collection. Example: len([1, 2,
3]) → 3.
4. Explain Python's join() and split() methods.
o join(): Combines elements of a list into a string with a separator. Example: ",".join(["a",
"b"]) → "a,b".
o split(): Splits a string into a list based on a separator. Example: "a,b".split(",") → ["a",
"b"].
5. What is a lambda function?
o A lambda function is an anonymous, inline function defined using the lambda keyword.
Example: f = lambda x: x + 1 → f(2) → 3.
6. What are positional, default, and variable-length arguments?
o Positional: Arguments passed in order.
o Default: Arguments with default values.
o Variable-length: Accepts multiple arguments using *args or **kwargs.
7. What is Django?
o Django is a Python web framework that follows the MVC architecture, allowing developers to
build scalable web applications efficiently.
Long Questions with Answers

1. Explain Python's Data Types with Examples.


o int: Represents integers. Example: x = 10.
o float: Represents decimals. Example: y = 3.14.
o str: Represents text. Example: z = "hello".
o list: Mutable collection. Example: lst = [1, 2, 3].
o tuple: Immutable collection. Example: tpl = (1, 2, 3).
o dict: Key-value pairs. Example: d = {"name": "Alice"}.
2. Describe File Handling in Python with Examples.
o Reading Files:

python
Copy code
with open("file.txt", "r") as f:
content = f.read()
print(content)

o Writing Files:

python
Copy code
with open("file.txt", "w") as f:
f.write("Hello, world!")

3. Differentiate Between for and while Loops.


o For loop: Iterates over a sequence (e.g., list, string). Example:

python
Copy code
for i in range(5):
print(i)

o While loop: Runs while a condition is True. Example:

python
Copy code
x = 0
while x < 5:
print(x)
x += 1

4. Write a Python Program to Find the Factorial of a Number.

python
Copy code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120

5. Explain MVC Architecture in Django.


o Model: Handles database interactions (e.g., defining tables).
o View: Defines the logic for displaying data.
o Controller: Connects models and views, handles user inputs.
6. Explain the break, continue, and pass Statements.
o Break: Exits the loop immediately.
o Continue: Skips to the next iteration.
o Pass: Does nothing (placeholder).

Key Python Programs (High Probability)

1. Check if a Number is Palindrome.

python
Copy code
num = 121
if str(num) == str(num)[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

2. Check if a Number is Prime.

python
Copy code
num = 29
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")

3. Reverse a String.

python
Copy code
s = "hello"
print(s[::-1]) # Output: "olleh"

4. Find the Sum of Digits of a Number.

python
Copy code
num = 123
total = sum(int(digit) for digit in str(num))
print(total) # Output: 6

5. Print Fibonacci Series up to n Terms.

python
Copy code
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(5) # Output: 0 1 1 2 3
Additional High-Chance Questions with Answers
3
MCQs with Answers

1. What is the purpose of the is operator in Python?


o (a) Checks if two values are equal
o (b) Checks if two variables refer to the same object (Answer)
o (c) Performs bitwise operations
o (d) None of these
2. Which of the following is the correct syntax for defining a function in Python?
o (a) function myFunc():
o (b) def myFunc(): (Answer)
o (c) define myFunc():
o (d) funct myFunc()
3. Which Python function is used to return the largest number in a list?
o (a) len()
o (b) max() (Answer)
o (c) sum()
o (d) list.max()
4. Which keyword is used to define a class in Python?
o (a) def
o (b) class (Answer)
o (c) object
o (d) new
5. What is the output of round(3.14159, 2)?
o (a) 3.14 (Answer)
o (b) 3.1
o (c) 3.141
o (d) 4
6. What is the result of the following Python expression?
10 // 3
o (a) 3.33
o (b) 3 (Answer)
o (c) 4
o (d) Error

SAQs with Answers

1. What is the purpose of the __init__() method in Python classes?


o The __init__() method is the constructor method in Python classes, used to initialize an
object's attributes when it is created.
Example:

python
Copy code
class Person:
def __init__(self, name):
self.name = name
obj = Person("Alice")
print(obj.name) # Output: Alice

2. What are Python decorators?


o Decorators are functions that modify the behavior of other functions or methods. They are
defined using the @decorator_name syntax. Example:

python
Copy code
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@decorator
def my_function():
print("Hello!")

my_function()

3. What is the difference between deepcopy() and copy()?


o copy(): Creates a shallow copy, copying only the outer structure.
o deepcopy(): Creates a deep copy, copying both outer and inner structures.
Example:

python
Copy code
import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

4. What are Python modules and packages?


o Module: A file containing Python code (functions, classes, etc.). Example: math.
o Package: A collection of modules organized in a directory with an __init__.py file.
5. Explain the difference between is and ==.
o is: Checks if two objects are the same (memory reference).
o ==: Checks if two objects have the same value.
Example:

python
Copy code
a = [1, 2]
b = [1, 2]
print(a is b) # False
print(a == b) # True

Long Questions with Answers

1. Write a Python program to calculate the sum of the squares of a list of numbers.
python
Copy code
numbers = [1, 2, 3, 4]
squares_sum = sum(x**2 for x in numbers)
print("Sum of squares:", squares_sum)
# Output: Sum of squares: 30

2. What are Python's different types of operators? Explain with examples.


o Arithmetic Operators: +, -, *, /, //, %, **.
Example: x = 10 % 3 → 1.
o Comparison Operators: ==, !=, >, <, >=, <=.
Example: x = (5 > 3) → True.
o Logical Operators: and, or, not.
Example: x = (True and False) → False.
o Bitwise Operators: &, |, ^, ~, <<, >>.
Example: x = 5 & 3 → 1.
o Assignment Operators: =, +=, -=.
Example: x += 5.
3. Explain mutable and immutable data types in Python.
o Mutable: Can be modified after creation. Example:

python
Copy code
lst = [1, 2, 3]
lst[0] = 10 # Changes the first element
print(lst) # Output: [10, 2, 3]

o Immutable: Cannot be modified after creation. Example:

python
Copy code
tup = (1, 2, 3)
# tup[0] = 10 # Error: Tuples are immutable

4. Write a Python program to reverse a string without using slicing.

python
Copy code
def reverse_string(s):
reversed_str = ""
for char in s:
reversed_str = char + reversed_str
return reversed_str

print(reverse_string("hello")) # Output: olleh

5. What is the significance of Django middleware?


o Middleware in Django is used to process requests and responses globally. It provides
functionalities like session handling, security, authentication, etc.
Example: SessionMiddleware ensures sessions are managed efficiently.
6. Write a Python program to check if a number is even or odd.

python
Copy code
num = 10
if num % 2 == 0:
print("Even")
else:
print("Odd")

Python Programs for Practice (High Probability)

1. Program to Count Vowels in a String

python
Copy code
s = "hello world"
vowels = "aeiou"
count = sum(1 for char in s if char.lower() in vowels)
print("Vowel count:", count) # Output: Vowel count: 3

2. Program to Generate Fibonacci Series

python
Copy code
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(6) # Output: 0 1 1 2 3 5

3. Program to Find Factorial Using Iteration

python
Copy code
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # Output: 120

Additional High-Chance Questions with Answers


4
MCQs with Answers

1. What is the output of print(type([])) in Python?


o (a) <class 'dict'>
o (b) <class 'list'> (Answer)
o (c) <class 'tuple'>
o (d) <class 'set'>
2. What does the id() function do in Python?
o (a) Returns the memory address of an object (Answer)
o (b) Checks the identity of an object
o (c) Compares two objects
o (d) None of these
3. What is the default mode of the open() function in Python?
o (a) r (Answer)
o (b) w
o (c) a
o (d) rb
4. Which of the following is a Python set?
o (a) {1, 2, 3} (Answer)
o (b) [1, 2, 3]
o (c) (1, 2, 3)
o (d) None of these
5. What will be the output of the following code?

python
Copy code
print(2 ** 3 + 5 // 2) 2^3=8
5/2=2
o (a) 11 (Answer) 8+2=10
o (b) 9
o (c) 8
o (d) 10 ans
6. What is the purpose of __name__ == '__main__' in Python?
o (a) To define the main function
o (b) To check if the script is run as the main program (Answer)
o (c) To import other modules
o (d) To terminate a program

SAQs with Answers

1. What is the purpose of the super() function in Python?


o The super() function is used to call a method from a parent class inside a child class.
Example:

python
Copy code
class Parent:
def greet(self):
print("Hello from Parent!")

class Child(Parent):
def greet(self):
super().greet() # Calls Parent's greet()
print("Hello from Child!")

obj = Child()
obj.greet()
# Output:
# Hello from Parent!
# Hello from Child!

2. What is Python's zip() function?


o The zip() function combines two or more iterables into tuples, pairing corresponding elements.
Example:
python
Copy code
a = [1, 2, 3]
b = ['a', 'b', 'c']
print(list(zip(a, b))) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]

3. Explain Python's isinstance() function.


o The isinstance() function checks if an object is an instance of a specific class or a subclass
thereof.
Example:

python
Copy code
print(isinstance(5, int)) # True
print(isinstance("Hello", str)) # True

4. What is the difference between sort() and sorted() in Python?


o sort(): Modifies the original list in place.
o sorted(): Returns a new sorted list without modifying the original.
Example:

python
Copy code
lst = [3, 1, 2]
print(sorted(lst)) # [1, 2, 3]
print(lst) # [3, 1, 2]
lst.sort()
print(lst) # [1, 2, 3]

5. What are Python's membership operators?


o in: Returns True if a value exists in a sequence.
o not in: Returns True if a value does not exist in a sequence.
Example:

python
Copy code
print('a' in 'apple') # True
print(5 not in [1, 2, 3]) # True

6. What are Python’s logical operators?


o and: Returns True if both conditions are true.
o or: Returns True if at least one condition is true.
o not: Negates a condition.

Long Questions with Answers

1. Write a Python program to find the largest element in a list.

python
Copy code
lst = [3, 5, 7, 2, 8]
print("Largest element:", max(lst)) # Output: Largest element: 8
2. Explain Python's exception handling mechanism with an example.
o Exception handling uses try, except, and optionally finally blocks to manage errors
gracefully.
Example:

python
Copy code
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
# Output:
# Cannot divide by zero.
# Execution completed.

3. Write a Python program to count the occurrences of each character in a string.

python
Copy code
from collections import Counter
s = "hello"
count = Counter(s)
print(count) # Output: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

4. Explain different types of arguments in Python functions with examples.


o Positional arguments: Passed in order.
o Default arguments: Use default values if none provided.
o Keyword arguments: Passed by name.
o Variable-length arguments: Use *args for multiple positional arguments and **kwargs for
keyword arguments.
Example:

python
Copy code
def func(a, b=2, *args, **kwargs):
print(a, b, args, kwargs)
func(1, 3, 4, 5, x=10, y=20)
# Output: 1 3 (4, 5) {'x': 10, 'y': 20}

5. Write a Python program to sort a dictionary by its values.

python
Copy code
d = {'a': 3, 'b': 1, 'c': 2}
sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_d) # Output: {'b': 1, 'c': 2, 'a': 3}

Key Programs to Practice

1. Find the GCD of Two Numbers

python
Copy code
import math
print(math.gcd(12, 18)) # Output: 6

2. Check if a String is a Substring of Another

python
Copy code
s1 = "hello world"
s2 = "world"
print(s2 in s1) # Output: True

3. Check if a Year is a Leap Year

python
Copy code
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")

4. Reverse a Number

python
Copy code
num = 12345
reversed_num = int(str(num)[::-1])
print(reversed_num) # Output: 54321

5. Convert Celsius to Fahrenheit

python
Copy code
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(fahrenheit) # Output: 77.0

Final High-Chance Questions with Answers for December 2024 Semester


5
Below is an extensive list of additional MCQs, SAQs, Long Questions, and Python Programs to ensure
maximum coverage.

MCQs with Answers

1. Which method is used to add an element at a specific index in a list?


o (a) append()
o (b) insert() (Answer)
o (c) extend()
o (d) add()
2. What is the output of bool([])?
o (a) True
o (b) False (Answer)
o (c) Error
o (d) None
3. Which of the following is not a valid Python data type?
o (a) list
o (b) set
o (c) queue (Answer)
o (d) dict
4. Which keyword is used for defining a generator function?
o (a) yield (Answer)
o (b) return
o (c) def
o (d) async
5. What is the output of the following code?

python
Copy code
print(5 > 3 and 3 < 2)

o (a) True
o (b) False (Answer)
o (c) None
o (d) Error
6. Which of the following is a mutable data type?
o (a) tuple
o (b) string
o (c) list (Answer)
o (d) frozenset
7. What will range(5) return?
o (a) [0, 1, 2, 3, 4]
o (b) (0, 1, 2, 3, 4)
o (c) A range object (Answer)
o (d) None

SAQs with Answers

1. What are Python's special methods (magic methods)?


o Special methods in Python start and end with __. Examples:
 __init__: Constructor.
 __str__: String representation of an object.
2. What is the difference between pop() and remove() in a list?
o pop(index): Removes and returns the element at the given index.
o remove(value): Removes the first occurrence of the specified value.
3. What is the map() function in Python?
o The map() function applies a function to all items in an iterable.
Example:

python
Copy code
nums = [1, 2, 3]
result = list(map(lambda x: x**2, nums))
print(result) # [1, 4, 9]

4. What is the purpose of the with statement in Python?


o The with statement is used for resource management, ensuring resources like files are properly
closed after use.
Example:

python
Copy code
with open("file.txt", "r") as f:
content = f.read()

5. What is the difference between deepcopy() and shallow copy()?


o Shallow copy: Copies the reference of nested objects.
o Deep copy: Creates a new copy of nested objects.
Example:

python
Copy code
import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

Long Questions with Answers

1. Explain Python's *args and **kwargs with examples.


o *args: Allows a function to accept multiple positional arguments.
Example:

python
Copy code
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6

o **kwargs: Allows a function to accept multiple keyword arguments.


Example:

python
Copy code
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)

2. Write a Python program to merge two dictionaries.

python
Copy code
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
3. Explain the concept of list comprehension with an example.
o List comprehension is a concise way to create lists.
Example:

python
Copy code
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]

4. Write a Python program to find the second largest number in a list.

python
Copy code
lst = [10, 20, 4, 45, 99]
largest = max(lst)
lst.remove(largest)
second_largest = max(lst)
print(second_largest) # Output: 45

5. Explain the concept of recursion with an example.


o Recursion is when a function calls itself to solve a problem.
Example: Factorial Calculation:

python
Copy code
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120

Key Python Programs for Practice

1. Find the Intersection of Two Lists

python
Copy code
a = [1, 2, 3]
b = [2, 3, 4]
intersection = list(set(a) & set(b))
print(intersection) # Output: [2, 3]

2. Find All Prime Numbers in a Range

python
Copy code
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

primes = [x for x in range(10, 50) if is_prime(x)]


print(primes) # Output: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
3. Generate a Multiplication Table

python
Copy code
num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

4. Check If a List is Sorted

python
Copy code
lst = [1, 2, 3, 4]
print(lst == sorted(lst)) # Output: True

5. Count the Frequency of Elements in a List

python
Copy code
from collections import Counter
lst = [1, 2, 2, 3, 3, 3]
freq = Counter(lst)
print(freq) # Output: Counter({3: 3, 2: 2, 1: 1})

Additional Tips

 Focus on MCQs about basic syntax, operators, methods, and built-in functions.
 Master SAQs on file handling, list comprehensions, and Python-specific concepts like __init__ and
super().
 Practice programming questions, especially involving loops, recursion, and common data structure
manipulations.
 Be familiar with Django basics like MVC architecture, creating a project, and working with models.

These questions, along with the earlier sets, ensure comprehensive preparation for the December 2024
semester exams.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy