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

pwp solved qb

The document is a question bank for Python programming covering various topics such as modes of Python, comments, list operations, logical and relational operators, data types, and control flow statements. It includes explanations, examples, and code snippets for each topic, making it a comprehensive resource for learning Python. Additionally, it addresses built-in functions, mutable vs immutable data structures, and dictionary creation and access.

Uploaded by

sr5824241
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)
6 views

pwp solved qb

The document is a question bank for Python programming covering various topics such as modes of Python, comments, list operations, logical and relational operators, data types, and control flow statements. It includes explanations, examples, and code snippets for each topic, making it a comprehensive resource for learning Python. Additionally, it addresses built-in functions, mutable vs immutable data structures, and dictionary creation and access.

Uploaded by

sr5824241
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/ 16

PWP

PT-1 Question Bank (2024-25)

1)​ List and explain different modes of Python.​


Python has three main modes for writing and executing programs:

1. Interactive Mode

●​ Runs commands directly in the Python shell.


●​ Best for quick testing and debugging.
●​ Shows results immediately after entering a command.

2. Script Mode

●​ Write programs in a .py file and run them later.


●​ Useful for larger projects and reusable code.
●​ Can be executed using the Python interpreter.

3. IDLE Mode

●​ Uses Python’s built-in Integrated Development Environment (IDLE).


●​ Provides a simple interface for writing and running Python code.
●​ Ideal for beginners to learn and experiment.

2)​ How to give single and multiline comment in Python​


Single-line comment: Starts with #.​
python​
CopyEdit​
# This is a single-line comment

Multi-line comment: Uses triple quotes (''' or """).​


python​
CopyEdit​
'''

This is a

multi-line comment

'''
3)​ Write basic operations of list
my_list = [1, 2, 3, 4, 5]

my_list.append(6) # Add element

my_list.remove(2) # Remove element

print(len(my_list)) # Find length

4)​ Compare list and tuple. (Any 2 points)​

5)​ Explain logical operators in python with example​ ​


Logical operators in Python are used to combine conditional statements. There are
three main logical operators:

1. AND (and)

●​ Returns True if both conditions are True.


●​ Example:
○​ True and True → True
○​ True and False → False

2. OR (or)

●​ Returns True if at least one condition is True.


●​ Example:
○​ True or False → True
○​ False or False → False

3. NOT (not)

●​ Reverses the result of a condition.


●​ Example:
○​ not True → False
○​ not False → True
6)​ Give two differences between set and dictionary

7)​ Explain relational operators in python


Relational operators (also called comparison operators) are used to compare values. They
return True or False based on the comparison.

1. Equal to (==)

●​ Checks if two values are equal.


●​ Example: 5 == 5 → True

2. Not equal to (!=)

●​ Checks if two values are not equal.


●​ Example: 5 != 3 → True

3. Greater than (>)

●​ Checks if the left value is greater than the right.


●​ Example: 7 > 3 → True

4. Less than (<)

●​ Checks if the left value is smaller than the right.


●​ Example: 4 < 8 → True

5. Greater than or equal to (>=)

●​ Checks if the left value is greater than or equal to the right.


●​ Example: 5 >= 5 → True

6. Less than or equal to (<=)

●​ Checks if the left value is smaller than or equal to the right.


●​ Example: 3 <= 4 → True

🚀
These operators are mostly used in conditions, loops, and decision-making in Python
programs.
8)​ Explain four Built-in tuple functions python with example
Tuples have several built-in functions to help manipulate and analyze data. Here are four
important ones:

1. len() – Find Length

●​ Returns the number of elements in a tuple.

Example:​
my_tuple = (10, 20, 30)

print(len(my_tuple)) # Output: 3

2. count() – Count Occurrences

●​ Returns how many times a value appears in a tuple.

Example:​
my_tuple = (1, 2, 2, 3, 2)

print(my_tuple.count(2)) # Output: 3

3. index() – Find Position

●​ Returns the index of the first occurrence of a value.

Example:​
my_tuple = (5, 10, 15, 20)

print(my_tuple.index(15)) # Output: 2

4. max() – Find Maximum Value

●​ Returns the largest element in a tuple (for numbers or strings).

Example:​
my_tuple = (3, 8, 1, 6)

print(max(my_tuple)) # Output: 8

9)​ Describe break and continue with example.​


Both break and continue are used inside loops to control the flow.

1. break – Stops the Loop

●​ Exits the loop when a condition is met.

Example:​
python​
CopyEdit​
for number in range(1, 6):
if number == 3:
break # Stops the loop at 3
print(number)
Output:​
CopyEdit​
1
2

2. continue – Skips One Iteration

●​ Skips the current loop iteration and moves to the next one.

Example:​
python​
CopyEdit​
for number in range(1, 6):
if number == 3:
continue # Skips 3 and continues
print(number)
Output:​
CopyEdit​
1
2
4
5

Key Difference

break stops the loop completely.

continue skips one iteration and continues.


10)​ Explain mutable and immutable data structures​
Mutable Data Structures

●​ Can be changed after creation.


●​ Allow modification, addition, and deletion of elements.
●​ Examples:
○​ List ([ ])
○​ Dictionary ({key: value})
○​ Set ({ })

Example: List (Mutable)


python

CopyEdit

my_list = [1, 2, 3]

my_list.append(4) # List is modified

print(my_list) # Output: [1, 2, 3, 4]

2. Immutable Data Structures

●​ Cannot be changed after creation.


●​ Any modification creates a new object in memory.
●​ Examples:
○​ Tuple (( ))
○​ String ("text")
○​ Frozen Set (frozenset({ }))

Example: Tuple (Immutable)


python

CopyEdit

my_tuple = (1, 2, 3)

my_tuple[0] = 10 # ❌ This will cause an error


Key Difference
11)​ List operations on set

Python sets support several operations for adding, removing, and manipulating elements.

1. Adding Elements

●​ add(item) → Adds a single element.


●​ update(iterable) → Adds multiple elements.

2. Removing Elements

●​ remove(item) → Removes an element (error if not found).


●​ discard(item) → Removes an element (no error if not found).
●​ pop() → Removes and returns a random element.
●​ clear() → Removes all elements.

3. Set Operations

●​ Union (| or union()) → Combines two sets.


●​ Intersection (& or intersection()) → Common elements of two sets.
●​ Difference (- or difference()) → Elements in one set but not in the other.
●​ Symmetric Difference (^ or symmetric_difference()) → Elements in either set, but not
both.

4. Other Operations

len(set) → Returns the number of elements.

in → Checks if an element exists in a set.

copy() → Creates a copy of the set.


12)​ List data types in Python. Explain any two with example
Python has several built-in data types:

1. Numeric Types

●​ Integer (int)
●​ Floating Point (float)
●​ Complex Number (complex)

2. Sequence Types

●​ String (str)
●​ List (list)
●​ Tuple (tuple)

3. Set Types

●​ Set (set)
●​ Frozen Set (frozenset)

4. Mapping Type

●​ Dictionary (dict)

5. Boolean Type

●​ Boolean (bool)

6. Binary Types

●​ Bytes (bytes)
●​ Bytearray (bytearray)
●​ Memoryview (memoryview)

EXPLANATION OF ANY TWO:


LIST
A list is a group of items arranged in a specific order. You can add,
remove, or change items in a list. Lists are written inside square
brackets [ ]

Simple Features of List


✔ Keeps items in order (same sequence)​
✔ Can store different types of data (numbers, words, etc.)​
✔ Allows repeated items (duplicates)​
✔ Can be changed (add or remove items)

Example of List
# A list of fruits
fruits = ["Apple", "Banana", "Cherry"]
print(fruits)
# Output: ['Apple', 'Banana', 'Cherry']

DICTIONARY
A dictionary stores data in key-value pairs. Each key has a value.
Dictionaries are written inside curly braces { }, and each key is
separated from its value using a colon :.

Features of Dictionary
✔ Stores data as key-value pairs​
✔ Keys must be unique, but values can be duplicates​
✔ Can store different data types (keys and values)​
✔ Mutable (can add, remove, and update values)

Example of Dictionary

# Creating a dictionary
student = {"name": "John", "age": 20, "grade": "A"}
print(student)
# Output: {'name': 'John', 'age': 20, 'grade': 'A'}

13)​ Write a Python Program to accept values from user in a list and find
the largest number and smallest number in a list.
nums = list(map(int, input("Enter numbers: ").split()))

print("Max:", max(nums))

print("Min:", min(nums))

O/P:

Enter numbers: 10 25 5 40 15

Max: 40

Min: 5

14)​ Explain Membership and Assignment operators in python

Membership Operators (in, not in)

●​ These operators check whether a value exists in a sequence (such as a list, tuple, or string).
●​ in returns True if the value is present.
●​ not in returns True if the value is not present.
●​ Example: Checking if a number exists in a list or if a word exists in a sentence.

Assignment Operators (=, +=, -=, *=, /=, etc.)

●​ These operators are used to assign values to variables.


●​ = assigns a value directly.
●​ +=, -=, *=, etc., modify the current value of a variable and update it.
●​ Example: Increasing a variable’s value by adding a number to it.

●​ Membership Operators → Check if something is inside a collection.


●​ Assignment Operators → Assign and modify values in variables.
15) Write python program to perform following operations on Sets.

i)Create set

ii)Access set Element

iii)Update set

iv)Delete set
# i) Create a Set

my_set = {1, 2, 3, 4, 5}

print("Original Set:", my_set)

# ii) Access Set Elements (using loop since sets are unordered)

print("Set Elements:")

for item in my_set:

print(item)

# iii) Update Set (Add elements)

my_set.add(6) # Adding a single element

my_set.update([7, 8, 9]) # Adding multiple elements

print("Updated Set:", my_set)

# iv) Delete Set Elements

my_set.remove(3) # Removes 3 (raises error if not found)

my_set.discard(4) # Removes 4 (does not raise error if not found)

print("Set after deletion:", my_set)

# Delete the entire set

my_set.clear() # Clears all elements

print("Set after clear():", my_set)


16)​Explain decision making statement if – else, if-elif-else with example.
Decision-making statements allow a program to make choices based on conditions.

if-else Statement

●​ The if block runs if the condition is True.


●​ If the condition is False, the else block runs instead.

Example (Checking if a person can vote)

age = int(input("Enter your age: "))

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Explanation:

●​ If the user enters 18 or more, the program prints "You are


eligible to vote."
●​ Otherwise, it prints "You are not eligible to vote."

O/P:

Enter your age: 20


You are eligible to vote.

if-elif-else Statement

●​ if → Checks the first condition.


●​ elif (else-if) → Checks another condition if the first is False.
●​ else → Runs if none of the conditions are True.
Example (Checking if a number is positive, negative, or zero)
num = int(input("Enter a number: "))

if num > 0:
print("The number is Positive.")
elif num < 0:
print("The number is Negative.")
else:
print("The number is Zero.")

Explanation:

●​ If the number is greater than 0, the program prints "The number is Positive."
●​ If the number is less than 0, it prints "The number is Negative."
●​ Otherwise, it prints "The number is Zero."

Example Output:
Enter a number: -5

The number is Negative.


17)​Explain building blocks of Python
Building Blocks of Python

Python programs are made up of basic components that help in writing structured and efficient code.
The main building blocks are:

1. Variables and Data Types

●​ Variables store information that can be used later in a program.


●​ Data Types define the type of values stored, such as numbers, text, or lists.
●​ Common data types in Python include integers (numbers), strings (text), lists (collections),
and dictionaries (key-value pairs).

2. Operators

●​ Operators perform different operations, like addition, comparison, or logical checks.


●​ Arithmetic operators (+, -, *, /) help with calculations.
●​ Comparison operators (>, <, ==, !=) compare values.
●​ Logical operators (and, or, not) combine conditions.

3. Conditional Statements (Decision Making)

●​ Conditional statements allow the program to make decisions based on conditions.


●​ The if statement checks if a condition is true and executes a block of code.
●​ The if-else statement provides an alternative if the condition is false.
●​ The if-elif-else statement checks multiple conditions.

4. Loops

●​ Loops help repeat a block of code multiple times.


●​ For Loop is used when the number of repetitions is known.
●​ While Loop runs until a condition becomes false.

5. Functions

●​ Functions allow code reusability by grouping instructions that can be used multiple times.
●​ A function is defined once and can be called whenever needed.
●​ Functions make the code organized, readable, and efficient.

18)​WAP to check entered no is prime or not


num = int(input("Enter a number: "))
if num > 1 and all(num % i != 0 for i in range(2, num)):
print("Prime")
else:
print("Not Prime")
OP:
Enter a number: 7
Prime
Enter a number: 10
Not Prime

19)​Explain creating Dictionary and accessing Dictionary Elements with


example.
A dictionary in Python is used to store data in key-value pairs. Each key is linked to a value, and you
can use the key to access the value. Dictionaries are written inside curly braces { }, with keys and
values separated by a colon :.

How to Create a Dictionary?


You can create a dictionary by using curly braces { } and writing key-value pairs inside.

Example of Creating a Dictionary


python
CopyEdit
# Creating a dictionary
student = {
"name": "John",
"age": 20,
"grade": "A"
}
print(student)
Output:
{'name': 'John', 'age': 20, 'grade': 'A'}
How to Access Dictionary Elements?
You can access values in a dictionary using keys. There are two ways to do this:

1. Using Square Brackets [ ]


python
CopyEdit
print(student["name"]) # Output: John
print(student["age"]) # Output: 20

●​ This method directly gets the value of a key.


●​ If the key does not exist, it will give an error.

2. Using get() Method


python
CopyEdit
print(student.get("grade")) # Output: A
print(student.get("city")) # Output: None (No error if key
is missing)

●​ get() is safer because if the key does not exist, it returns None instead of an error.

20)​ Write a Python program to find the factorial of a number provided by the
user
# Get input from the user
num = int(input("Enter a number: "))
# Initialize factorial variable
factorial = 1
# Calculate factorial using a loop
for i in range(1, num + 1):
factorial *= i
# Print the result
print("Factorial of", num, "is", factorial)
OP:
Enter a number: 5
Factorial of 5 is 120

You might also like