Question Bank
Question Bank
1. What is the need for role of precedence? Illustrate the rules of precedence in with example.
In Python, operator precedence determines the order in which operations are performed in an
expression. Without precedence rules, Python wouldn't know which operation to perform first, which
could lead to incorrect results or unexpected behavior.
()-Parathesis
**-Exponential
+x,-x,-unary plus,unary minus
*,/,//,%-multiplication,division,floor division,modulo
+,- addition,subtraction
EX:10 + (5 * 2) = 20
2. List and explain Comparison and Boolean operators used in Python with example.
Comparison Operators
Comparison operators: are used to compare two values. The result is always a Boolean value: True or
False.
== - equal to
!= - not equal to
> - greater than
< - less than
EX:
a = 10
b = 20
print(a == b)
print(a < b)
EX:
x=7
y = 12
I) len()- Returns the number of items in an object (like a string, list, tuple, etc.).
name = "Python"
print(len(name)) # Output: 6
num = 100
print(str(num)) # Output: '100'
a=5
b = float(a)
print(b) # Output: 5.0
V) int()- Converts a float, string, or other number to an integer (removes decimals if present).
x = 9.8
print(int(x)) # Output: 9
x = 42
print(type(x)) # Output: <class 'int'>
iii) format()-Formats strings by inserting values into placeholders
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is John and I am 25 years old.
fruits.remove('banana')
String Concatenation:
Concatenation means joining two or more strings together using the + operator.
a = "Hello"
b = "World" #Output: HelloWorld
print(a + b)
String Replication:
Replication means repeating a string multiple times using the * operator.
1. if Statement
age = 18
if age >= 18:
print("You are eligible to vote.")
O/p You are eligible to vote.
2. if...else Statement
Executes one block if the condition is True, and another block if it's False.
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
O/p You are not eligible to vote.
3. if...elif...else Statement
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Fail")
O/pGrade: B
8. Differentiate while loop and for loop with example code snippets
Ii) for Loop-Repeats a block of code for each item in a sequence (like a list or range()).
Ii)continue Statement-Skips the current iteration and moves to the next one.