0% found this document useful (0 votes)
18 views13 pages

Adi's PWP PT-1 Solution

The document is a comprehensive question bank covering various aspects of Python programming, including modes of operation, comments, list operations, data types, and control structures. It explains concepts such as mutable vs immutable data structures, logical and relational operators, and provides examples for better understanding. Additionally, it includes programming exercises and explanations of built-in functions and data structures like dictionaries and sets.
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)
18 views13 pages

Adi's PWP PT-1 Solution

The document is a comprehensive question bank covering various aspects of Python programming, including modes of operation, comments, list operations, data types, and control structures. It explains concepts such as mutable vs immutable data structures, logical and relational operators, and provides examples for better understanding. Additionally, it includes programming exercises and explanations of built-in functions and data structures like dictionaries and sets.
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/ 13

PWP PT-1 Question Bank

1. List and explain different modes of Python.


• Interactive Mode (REPL - Read-Eval-Print Loop)
o Executes commands one at a time in the Python shell.
o Used for quick testing and debugging.
o Example:

• Script Mode
o Runs a complete Python program saved in a .py file.
o Used for developing full applications.
o Example:

o Run With:

2. How to give single and multiline comment in Python.


• Single-line Comment:
o Uses the # (hash symbol).
o Everything after # on the same line is ignored by Python.
o Example:

• Multi-line Comment (Using """ or '''):


o Python does not have a built-in multi-line comment syntax like other languages.
o Instead, triple quotes (""" or ''') are used to create a multi-line string, which Python ignores if
not assigned to a variable.
o Example:
3. Write basic operations of list
Lists in Python are ordered, mutable, and allow duplicate values. Here are some basic operations:
Basic Operation of list are:-
1. Traversing the list
Traversing means iterating over each element in a list.
A. Using range() with indexing
Uses range(len(list)) to loop through indexes.
Example:

B. Using enumerate()
enumerate returns both the index and value, making iteration easier.
Example:

2. List Concatenation(+ operator )


Concatenation combines two or more list into one.
Example:

Note:-Does not modify the original list but creates a new one.
3. List Repetition(* operator )
Repetition duplicates a list multiple times.
Example:

4. Finding Length(len())
The len() function returns the number of elements in a list.

Useful for loop and condition checks.


4. Compare list and tuple (Any 2).
List Tuple
Mutable (Can be modified) Immutable (Cannot be modified)
Created using [ ] Created using ( )
Slower (due to modifiability) Faster (as it is fixed and optimized)
Example:- Example:-

5. Explain logical operator in python with example


Logical operators in Python are used to combine conditional statements and return a boolean (True or False)
result.
Types of Logical operator:
1. and (Logical AND)
• Returns True if both conditions are True, otherwise returns False.
• Example:-

2. or (Logical OR)
• Returns True if at least one of the conditions is True, otherwise returns False.
• Example:-

3. not (Logical NOT)


• Reverses the boolean value of the condition.
• Example:-
6. Give two differences between set and dictionary
Set Dictionary
A collection of unique, unordered elements. A collection of key-value pairs.
Does not store key-value pairs. Stores data as key-value pairs (key: value).
Cannot access elements using an index or key. Must Values are accessed using keys, e.g., dict["key"].
iterate over the set.
Does not allow duplicates. Keys must be unique, but values can be duplicated.
Example:- Example:-
my_set = {1, 2, 3, 4, 4} # Duplicates are my_dict = {"name": "John", "age": 25, "city": "New
automatically removed print(my_set) # Output: {1, York"} print(my_dict["name"]) # Output: John
2, 3, 4}

7. Explain relational operators in python


Relational operators (also called comparison operators) are used to compare two values. They return a
boolean value (True or False) based on the comparison result.
• List of Relational Operators:-
Operator Meaning Example Output

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 10 > 7 True

< Less than 3<8 True

>= Greater than or equal to 5 >= 5 True

<= Less than or equal to 6 <= 10 True

• Examples:-

• Usage in Conditional Statements


Relational operators are commonly used in if statements:
8. Explain four Built-in tuple functions python with example
• len() – Returns the Length of the Tuple
o This function returns the number of elements in a tuple.
o Example:-

• max() – Returns the Maximum Value


o This function returns the largest element in a tuple (only works if all elements are
comparable).
o Example:-

• min() – Returns the Minimum Value


o This function returns the smallest element in a tuple.
o Example:

• tuple() – Converts an Iterable into a Tuple


o This function converts a list, string, or other iterable into a tuple.
o Example:

• cmp() – Compare two tuples


o This function compare two tuples and return the value (-1,0,1).
o It will return: -1 if t1<t2
0 if t1=t2
1 if t1>t2
o Example:
9. Describe break and continue with example.
• break Statement:
o The break statement terminates the loop immediately when encountered, even if the loop
condition is still true.
o Example: Using break in a for Loop Output:

• continue Statement:
o The continue statement skips the current iteration and moves to the next iteration of
the loop.
o Example: Using continue in a for Loop Output:

10. Explain mutable and immutable data structures


• Mutable Data Structures
o Mutable data structures allow modifications after creation (elements can be changed, added,
or removed).
o Examples: list, dict, set, bytearray
▪ Example of a Mutable Data Structure (list)

• Immutable Data Structures


o Immutable data structures cannot be modified after creation. Any change creates a new
object.
o Examples: tuple, str, int, float, frozenset, bytes
▪ Example of an Immutable Data Structure (tuple)
11. List operations on set.
Sets in Python support various operations that allow efficient manipulation of elements. Here are some key
operations:
• Union (| or union())
o Combines two sets and removes duplicates.

• Intersection (& or intersection())


o Returns common elements from both sets.

• Difference (- or difference())
o Returns elements in A but not in B.

• Symmetric Difference (^ or symmetric_difference())


o Returns elements that are in one of the sets but not both.

12. List data types in Python. Explain any two with example
1. None Types:
• Null
2. Numeric Types:
• int (Integer)

• float (Floating-point number)

• complex (Complex number)

3. Sequence Types:
• str (String)

• list (List)

• tuple (Tuple)

• bytes (Immutable byte sequence)

• bytearray (Mutable byte sequence)

• range

4. Set Types:
• set (Mutable Set)
• frozenset (Immutable Set)
5. Mapping Type:
• dict (Dictionary)

6. Boolean Type:
• bool (Boolean: True or False)

Explanation of Two Data Types:


1. List (Sequence Type)
• A list is an ordered, mutable collection of elements that can hold different data types.

• Example: Output:

2. Dictionary (Mapping Type)


• A dictionary is an unordered, mutable collection that stores data in key-value pairs.

• Example: Output:

13. Write a Python Program to accept values from user in a list and find the largest number
and smallest number in a list.
Code:- Output:-
14. Explain Membership and Assignment operators in python
• Python provides Membership and Assignment operators for checking values in sequences and
assigning values to variables, respectively.
• Membership Operators (in, not in) :-
Used to check if a value exists in a sequence (list, tuple, string, etc.).
Operators:

Example:

• Assignment Operators (=, +=, -=, *=, /=,%=, //=, **=)


Used to assign or update values of variables.
Operators & Example:

15. Write python program to perform following operations on Sets.


a. Create set
b. Access set Element
c. Update set
d. Delete set

# a. Create a set
my_set = {1, 2, 3, 4, 5}
print("Created Set:", my_set)
# Output: Created Set: {1, 2, 3, 4, 5}
# b. Access set elements (using a loop, as sets are unordered)
print("Accessing Set Elements:")
for item in my_set:
print(item)
# Output (Order may vary):
#1
#2
#3
#4
#5

# c. Update the set (Adding and Removing elements)


my_set.add(6) # Adding a single element
print("After Adding 6:", my_set)
# Output: After Adding 6: {1, 2, 3, 4, 5, 6}

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


print("After Adding multiple elements:", my_set)
# Output: After Adding multiple elements: {1, 2, 3, 4, 5, 6, 7, 8, 9}

my_set.remove(3) # Removing an element (raises error if not found)


print("After Removing 3:", my_set)
# Output: After Removing 3: {1, 2, 4, 5, 6, 7, 8, 9}

my_set.discard(10) # Discarding an element (No error if not found)


print("After Trying to Discard 10 (not present):", my_set)
# Output: After Trying to Discard 10 (not present): {1, 2, 4, 5, 6, 7, 8, 9}

# d. Delete the set


del my_set
print("Set deleted successfully.")
# Output: Set deleted successfully.
16. Explain decision making statement if – else, if-elif-else with example
Python provides decision-making statements to control the flow of execution based on conditions. The key
decision-making statements are:
1. if-else Statement
2. if-elif-else Statement
• if-else Statement
The if-else statement is used to execute one block of code if a condition is True and another block
if the condition is False.
Syntax:

Example: Output:

• if-elif-else Statement
The if-elif-else statement is used when multiple conditions need to be checked. It works like
multiple if conditions, but only the first True condition is executed.
Syntax:

Example: Output:
17. Explain building blocks of Python
Python's building blocks are the fundamental components that define the language's structure and
functionality. Some key building blocks include:
1. Identifiers – Names given to variables, functions, and classes.
• Must start with a letter (A-Z or a-z) or an underscore (_), followed by letters, digits (0-9), or
underscores.
• Example: my_variable = 10
2. Keywords – Reserved words in Python that cannot be used as variable names.
• Examples: if, else, for, while, def, return, class, import, True, False.
3. Indentation – Python uses indentation instead of curly braces {} to define code blocks, making the
code more readable.
• Example:

4. Variables – Used to store data values, allowing dynamic programming.


• Example:

5. Comments – Used to explain code and make it more understandable. They are ignored by the Python
interpreter.
• Single-line comment: # This is a comment
• Multi-line comment:

18. WAP to check entered no is prime or not.


19. Explain creating Dictionary and accessing Dictionary Elements with example.
A dictionary in Python is a collection of key-value pairs. It is unordered, mutable, and indexed by keys, which
means data is stored in a way that allows quick access to values using their keys.
1. Creating a Dictionary
A dictionary is created using curly braces {} or the dict() function, with key-value pairs separated by
colons (:).
Example:

2. Accessing Dictionary Elements


Dictionary elements are accessed using their keys, not index numbers (like lists).
Methods to Access Values:
1. Using square brackets [] (Direct Access)
2. Using .get() method (Safer Access)

20. Write a Python program to find the factorial of a number provided by the user

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