Operators: The Essential Tools of Python

Operators are the special symbols that let you do math, make decisions, and work with data in Python. They're like the tools in a toolbox, each designed for a specific job.

What are they?

Operators are symbols that represent actions you can perform on numbers, words, and other data.

They're the building blocks for your code's calculations, comparisons, and logical decisions.

Why are they important?

Operators let you:

Get ready to explore these powerful tools and see how they bring your Python code to life!

Types of Python Operators

Python divides the operators into the following groups:

Python Arithmetic Operators

Arithmetic operators like +, -, *, /, %,**, // are used with numeric values to perform common mathematical operations:

1. Python Addition Operator

In Python, the + symbol can do numeric addition and string concatenation.

Numeric Addition:

Purpose: Adds two numeric values together.

Operands: Works with integers (whole numbers) and floats (numbers with decimals).

Syntax: result = value1 + value2


# Adding integers 
a = 5 
b = 10 
sum = a + b  # sum will be 15 
 
 # Adding floats 
c = 3.14 
d = 2.71 
total = c + d  # total will be 5.85 
 
 # Adding complex numbers 
e = 1 + 2j
f = 3 - 4j
result = e + f  # result will be (4-2j)

String Concatenation:

Purpose: Combines two strings (sequences of characters) into a single string.

Operands: Works with strings.

Syntax: new_string = string1 + string2


greeting = "Hello" 
name = "Sunil" 
message = greeting + ", " + name + "!"  # message will be "Hello, Sunil!" 
 
string1 = "Code by " 
string2 = "Sunil" 
new_string = string1 + string2  # new_string will be "Code by Sunil"

Key Points:

The + operator serves a dual purpose in Python, handling numeric addition and string concatenation.

Understanding the context and data types involved is essential to interpret its behavior correctly.

Use it for calculations with numbers and for creating new strings by joining existing ones.

2. Python Subtraction Operator

Purpose: Subtracts one numeric value from another.

Operands: Works with integers (whole numbers) and floats (numbers with decimals).

Syntax: result = value1 - value2

Basic Subtraction:


x = 15 
y = 7 
difference = x - y # difference will be 8

Negative Results:


temperature = 25 
drop = 10 
new_temperature = temperature - drop # new_temperature will be 15 
account_balance = 50 
withdrawal = 75 
remaining_balance = account_balance - withdrawal # remaining_balance will be -25

3. Python Multiplication Operator

In Python, the * symbol can do numeric multiplication and string repetition.

Numeric Multiplication:

Purpose: Multiplies two numeric values together.

Operands: Works with integers (whole numbers), floats (numbers with decimals), and complex numbers.

Syntax: result = value1 * value2

# Multiplying integers 
num1 = 12 
num2 = 5 
product = num1 * num2  # product will be 60 
 
 # Multiplying floats 
price = 9.99 
quantity = 3 
total_cost = price * quantity  # total_cost will be 29.97 
 
 # Multiplying complex numbers 
c1 = 2 + 3j
c2 = 4 - 1j
c = c1 * c2  # c will be (5+14j)

String Repetition:

Purpose: Creates a new string by repeating a given string multiple times.

Operands: Works with strings.

Syntax: new_string = string * number_of_repetitions

string= "-" 
dashed_line = string * 20  # dashed_line will be "--------------------" 
 
emoji = "" 
celebration = emoji * 5  # celebration will be "" 
 
name = "Sunil" 
pattern = name * 3  # pattern will be "SunilSunilSunil"

Key Points:

The * operator has a dual role in Python, performing both numeric multiplication and string repetition.

It's important to consider the data types involved to understand its behavior.

Use it for calculations involving products of numbers and for creating strings with repeated patterns.

4. Division: Breaking Down Numbers

Purpose: Divide one numeric value by another.

Operands: Works with integers (whole numbers), floats (numbers with decimals), and complex numbers.

Syntax: result = value1 / value2

Division with Integers:

Produces a float as a result, even if the division is exact.

a = 10 
b = 3 
quotient = a / b # quotient will be 3.3333333333333335 (a float)

Division with Floats:

Always yields a float result.

pi = 3.14159 
circumference = 2 * pi * radius # circumference will be a float

Division by Zero:

Raises a ZeroDivisionError exception, indicating an invalid operation.

# This code will cause an error: result = 100 / 0 # ZeroDivisionError: division by zero

Complex Number Division:

Involves a specific formula for calculating the quotient of complex numbers.

c1 = 3 + 2j 
c2 = 1 - 4j 
c_quotient = c1 / c2 # c_quotient will be (-0.4117647058823529-0.9058823529411765j) 

Remember:

The / operator produces a floating-point result for integer division in Python 3.

To achieve integer division with truncation (floor division), use the // operator.

Be cautious of division by zero to prevent errors.

Complex number division follows a distinct set of rules.

5. Floor Division: Dividing to the Ground Floor

Purpose: Divides two numbers and discards any remainder, returning the integer quotient.

Operands: Works with integers (whole numbers) and floats (numbers with decimals).

Syntax: result = value1 // value2

Integer Division:

Always produces an integer result, even if the quotient has a decimal part.

pieces = 17 // 3 # pieces will be 5 (discarding the 0.3333...) 

Float Division:

Rounds the result down to the nearest integer, effectively truncating the decimal part.

average = 12.7 // 4 # average will be 3 (not 3.175)

Negative Numbers:

Rounds towards negative infinity, meaning the result is always smaller or equal to the actual quotient.

division = -9 // 2 # division will be -5 (not -4)

Zero:

Dividing by zero still results in a ZeroDivisionError exception.

Common Applications:

Calculating whole numbers of items:

total_slices = pizzas * slices_per_pizza // guests # Integer result 

Rounding down for financial calculations:

purchase_amount = 10000 
tax_rate = 12.54 # Assuming a percentage 
base_tax = purchase_amount // tax_rate # Truncated to discard cents

Ignoring remainders in measurements:

total_minutes_worked = 1400 
full_hours_worked = total_minutes_worked // 60 # Whole hours only 

Remember:

Floor division is specifically designed to produce integer results, even when working with floats.

It's different from regular division (/), which yields a float in most cases.

Use it when you need to discard remainders and focus on whole-number quotients.

6. Modulo: The Remainder Revealer

Purpose: Find the remainder when one number is divided by another.

Operands: Works with integers (whole numbers) and floats (numbers with decimals).

Syntax: result = value1 % value2

Revealing Remainders:

Calculates what's left over after a division, focusing on the “undivided part.”

remainder = 19 % 4 # remainder will be 3 

Integers vs. Floats:

With integers, the remainder is always an integer.

With floats, the remainder is also a float.

int_remainder = 14.5 % 3 # int_remainder will be 1.5 (a float)

Zero as a Divisor:

Dividing by zero still results in a ZeroDivisionError exception.

Negative Operands:

The sign of the remainder matches the sign of the dividend (the first operand).

negative_remainder = -17 % 5 # negative_remainder will be -2 

Common Applications:

Even/Odd Determination:

is_even = number % 2 == 0 # True if number is even

Alternating Patterns:

color_cycle = ["red", "green", "blue"] 
current_color = color_cycle[index % len(color_cycle)] # Cycles through colors

Checking Divisibility:

is_divisible_by_3 = number % 3 == 0 # True if number is divisible by 3

Wrapping Around Sequences:

index = 5 
wrapped_index = index % list_length # Ensures index stays within list bounds

Remember:

The modulo operator reveals patterns and relationships within numbers.

It's essential for tasks involving remainders, cyclic behavior, and divisibility checks.

Use it to make your code more versatile and adaptable to various scenarios.

6. Exponentiation: Powering Up Your Calculations

Purpose: Raises a number to a specified power, meaning it multiplies the number by itself a certain number of times.

Operands: Works with integers (whole numbers), floats (numbers with decimals), and complex numbers.

Syntax: result = base ** exponent

Key Behaviors:

Squaring and Beyond:

Squaring a number is a common case: base ** 2

But it can handle any exponent: result = 5 ** 3 # result will be 125 (5 * 5 * 5)

Square Roots (Kind Of):

Use a fractional exponent of 0.5 for a pseudo-square root: approx_root = 25 ** 0.5 # approx_root will be 5.0 (approximately)

Exponential Growth and Decay:

Models phenomena like population growth or radioactive decay: population = initial_population * growth_rate ** years

Complex Number Exponentiation:

Involves intricate calculations using Euler's formula.

Common Applications:

Financial Calculations:

compound_interest = principal * (1 + interest_rate) ** years

Scientific Formulas:

kinetic_energy = 0.5 * mass * velocity ** 2 
gravitational_force = G * mass1 * mass2 / distance ** 2

Geometric Patterns:

area_of_circle = pi * radius ** 2 
volume_of_sphere = (4/3) * pi * radius ** 3

Cryptography and Number Theory:

encryption_key = random_prime ** large_exponent

Remember:

Exponentiation unlocks calculations involving repeated multiplication and powers.

It's essential for modeling growth, decay, geometric relationships, and advanced mathematical concepts.

Use it to harness the power of exponents in your Python code!

Python Assignment Operators

Assignment operators are used to assign values to variables. They combine the process of assigning a value with a specific operation, making code more concise and efficient.

Here are the common assignment operators in Python:

1. = (Simple Assignment):

Assigns the value on the right to the variable on the left.

x = 5 # Assigns the value 5 to the variable x

2. += (Add and Assign):

Adds the value on the right to the variable on the left and assigns the result back to the variable.

x = 10 
x += 5 # Equivalent to x = x + 5, now x becomes 15

3. -= (Subtract and Assign):

Subtracts the value on the right from the variable on the left and assigns the result back to the variable.

y = 20 
y -= 8 # Equivalent to y = y - 8, now y becomes 12

4. *= (Multiply and Assign):

Multiplies the variable on the left by the value on the right and assigns the result back to the variable.

a = 4 
a *= 3 # Equivalent to a = a * 3, now a becomes 12

5. /= (Divide and Assign):

Divide the variable on the left by the value on the right and assign the result back to the variable.

b = 15 
b /= 5 # Equivalent to b = b / 5, now b becomes 3.0

6. %= (Modulo and Assign):

Calculates the remainder when the variable on the left is divided by the value on the right and assigns the result back to the variable.

c = 17 
c %= 4 # Equivalent to c = c % 4, now c becomes 1

7. **= (Exponent and Assign):

Raises the variable on the left to the power of the value on the right and assigns the result back to the variable.

d = 2 
d **= 3 # Equivalent to d = d ** 3, now d becomes 8

8. &= (Bitwise AND assign operator):

Sets each bit to 1 if both bits are 1 and assign the result back to the variable.

x = 3 
 
x &= 2 
 
 # x becomes 2 
 
 # Binary representation 
 
 # 3 = 0000000000000011 
 # 2 = 0000000000000010 
 # -------------------- 
 # 2 = 0000000000000010 
 # ====================

9. |= (Bitwise OR assign operator):

Sets each bit to 1 if one of the two bits is 1 and assigns the result back to variable

x = 3 
 
x |= 1 
 
 # x becomes 3 
 
 # Binary representation 
 
 # 3 = 0000000000000011 
 # 1 = 0000000000000001 
 # -------------------- 
 # 3 = 0000000000000011 
 # ====================

11. ^= (Bitwise XOR assign operator)

Sets each bit to 1 if only one of two bits is 1 and assigns the result back to the variable.

x = 3 
 
x ^= 1 
 
 # x becomes 2 
 
 # Binary representation 
 
 # 3 = 0000000000000011 
 # 1 = 0000000000000001 
 # -------------------- 
 # 2 = 0000000000000010 
 # ====================

12. <<= (Left shift assign operator)

Shift left by pushing zeros in from the right let the leftmost bits fall off and assign the result back to the variable.

x = 3 
 
x <<= 1 
 
 # x becomes 6 
 
 # Binary representation 
 
 # 3 = 0000000000000011 
 # 1 bit shifted to left 
 # 6 = 0000000000000110

13. >>= (Right shift assign operator)

Shift right by pushing copies of the leftmost bit in from the left, let the rightmost bits fall off, and assign result back to the variable.

x = 3 
 
x >>= 1 
 
 # x becomes 1 
 
 # Binary representation 
 
 # 3 = 0000000000000011 
 # 1 bit shifted to right 
 # 1 = 0000000000000001

Assignment operators streamline code by combining assignments with operations.

They can be used with various numerical data types (integers, floats) and strings.

They are a convenient way to perform calculations and modifications directly on variables.

Python Comparison operators

Comparison operators, like scales for data, compare values and return a boolean result: True or False.

1. Equal to (==)

Check if the values are the same.

is_it_pizza = "pizza" == "pizza"  # True, because they match 
is_it_cake = "pizza" == "cake"   # False, different foods

2. Not equal to (!=)

Determines if values are different.

is_door_open = door_status != "closed"  # True if the door is open 
is_password_correct = entered_password != correct_password  # True if wrong password

3. Greater than (>)

Compares if the first value is larger.

is_water_boiling = water_temperature > 100  # True if it's really hot 
is_score_high = player_score > 1000  # True for a high score

4. Less than (<)

Check if the first value is smaller.

is_room_cold = room_temperature < 20  # True if it's chilly 
is_battery_low = battery_level < 20  # True if time to charge

5. Greater than or equal to (>=)

Tests for greater than or the same.

is_guest_adult = guest_age >= 18  # True for adults 
is_game_finished = score >= 100  # True if you've reached the goal

6. Less than or equal to (<=)

Checks for less than or the same.

is_speed_safe = car_speed <= 80  # True if within the speed limit 
is_inventory_low = item_count <= 5  # True if need to restock

These operators work with numbers, strings, lists, and other data types. They're essential for making decisions in Python using conditional statements like if, elif, and else.

Python Logical Operators

Logical operators combine conditional statements (True or False) to make more complex decisions. Like puzzle pieces, they create intricate logical patterns.

Here are the 3 main logical operators:

1. and Operator

Return True only if both conditions are True.

x < 5 and  x < 10 # True

2. or Operator

True if at least one condition is True.

x < 5 or x < 4 # True

3. not Operator

Reverses the truth value of a condition.

not(x < 5 and x < 10)

Logical operators are essential for making decisions in Python code, especially within conditional statements and loops. Use them to combine multiple conditions and create more sophisticated logic.

Python Identity Operators

In Python, identity operators are used to check whether two variables refer to the same object in memory, rather than just having the same value.

1. is operator:

It returns True if two variables refer to the same object in memory. Returns False if they refer to different objects, even if their values are the same.

2. is not operator:

Opposite of the (is) operator. It returns True if two variables do not refer to the same object in memory. Returns False if they do refer to the same object.

x = 10 
y = 10 
 print(x is y)   # True (because small integers are cached, so both variables refer to the same object) 
 
a = [1, 2, 3] 
b = [1, 2, 3] 
 print(a is b)   # False (lists are mutable, so even though they have the same elements, they are different objects in memory) 
 
c = "hello" 
d = "hello" 
 print(c is d)   # True (strings are immutable, and Python often optimizes by reusing identical strings) 
 
 None is None   # True

Checking for None:

result = some_function()  # Suppose this function might return None 
 if result is None:
 print("Function returned None")

Comparing with a specific object:

default_user = User("default") 
current_user = get_current_user() 
 if current_user is default_user:
 print("User is not logged in")

Handling mutable and immutable objects:

# Mutable objects (lists) 
list1 = [1, 2, 3] 
list2 = list1.copy()  # Create a distinct copy of list1 
 print(list1 is list2)   # False, even though they have the same elements 
 
 # Immutable objects (strings) 
string1 = "abc" 
string2 = "abc"  # Python might reuse the same object for identical strings 
 print(string1 is string2)  # True, they often refer to the same object

Remember:

Python Membership Operators

In Python, membership operators help you check whether an element is present within a sequence like a list, tuple, or string. There are two main membership operators:

1. in operator

This operator returns True if the specified element is found in the sequence, and False otherwise. It works with various sequence types, including:

Lists: Check if an element exists in a list.

fruits = ["apple", "banana", "cherry"] 
 print("banana" in fruits) # Output: True 
numbers = [1, 2, 3, 4, 5] 
 print(6 in numbers) # Output: False


Tuples: Similar to lists, you can check for element presence in tuples.

my_tuple = ("apple", "banana", "cherry") 
 print("orange" in my_tuple) # Output: False

Strings: Check if a substring exists within a string.

message = "Hello, world!" 
 print("world" in message) # Output: True

2. not in operator

This operator is the opposite of in. It returns True if the specified element is not found in the sequence, and False otherwise. It works with the same sequence types as in.

fruits = ["apple", "banana", "cherry"] 
 print("mango" not in fruits) # Output: True 
numbers = [1, 2, 3, 4, 5] 
 print(6 not in numbers) # Output: True

Important points to remember:

Membership operators only check for the value of an element, not its memory location. So, even if identical objects exist in different parts of the sequence, the operator will only consider their values.

For strings,(in) checks for the exact presence of the substring. Order matters.

Membership operators do not work with dictionaries directly. They can only be used with the keys of a dictionary, not the values.

Python Bitwise Operators

Bitwise operators are used to compare binary numbers

1. Bitwise AND (&)

Sets a bit to 1 only if both corresponding bits in the operands are 1.

5 & 3 # Output: 1 
 
 # 5 = 0101 
 # 3 = 0011 
-----------
 # 1 = 0001

Common Application

Bitwise operator AND (&) can be used to check if the number is even or odd.

The bitwise AND operator (&) can be used to check if a number is even in Python. If the result of the bitwise AND operation between the number and 1 is 0, then the number is even. Otherwise, the number is odd.

number = 5 
 if number & 1 == 0:
 print("Even") 
 else:
 print("Odd")

2. Bitwise OR (|)

Sets a bit to 1 if either of the corresponding bits in the operands are 1.

5 | 3 # output: 7 
 
 # 5 = 0101 
 # 3 = 0011 
-----------
 # 7 = 0111

3. Bitwise XOR (^)

Sets a bit to 1 if the corresponding bits in the operands are different.

5 ^ 3 # output: 6 
 
 # 5 = 0101 
 # 3 = 0011 
-----------
 # 6 = 0110

4. Bitwise NOT (~)

Inverts all the bits in the operand (flips 0s to 1s and 1s to 0s).

~5 # output: -6 
 # 5 = 0101 
---------
 #-6 = 1110 # All bits are flipped

5. Bitwise Left Shift (<<)

Shifts the bits of the left operand to the left by the number of positions specified by the right operand, filling in 0s on the right.

x = 5 
x <<= 1 # Output: 10 
 
 # 5 = 0101 
----------
 #10 = 1010 # output 10

6. Bitwise Right Shift (>>)

Shifts the bits of the left operand to the right by the number of positions specified by the right operand, filling in 0s on the left for positive numbers, and 1s for negative numbers.

x = 5 
x >>= 1 # Output: 2 
 
 # 5 = 0101 
----------
 # 2 = 0010 # output

Bitwise operators work directly on the binary representation of numbers, providing efficient and low-level control over data. They are often used in system programming, communication protocols, image processing, and other domains where bit-level manipulation is crucial.

Operator Precedence

Operator Precedence: The order in which operators are evaluated in an expression.

Associativity: The order in which operators of the same precedence are evaluated.

Here's a breakdown of operator precedence and associativity in Python:

Parentheses () (highest)
Exponentiation ** (right-to-left)
Multiplication and Division (*, /, //, %) (left-to-right)
Addition and Subtraction (+, -) (left-to-right)
Comparisons (<, <=, >, >=, !=, ==) (left-to-right)
Bitwise AND & (left-to-right)
Bitwise XOR ^ (left-to-right)
Bitwise OR | (left-to-right)
Logical AND and (left-to-right)
Logical OR or (left-to-right)
Assignment operators (=, +=, -=, etc.) (right-to-left)
Identity operators (is, is not) (lowest)


Since identity operators are at the bottom of the precedence list, they are always evaluated last, regardless of other operators in the expression.

Arithmetic Operator Precedence

In Python, arithmetic expressions follow the rules of operator precedence and associativity. The order of evaluation is determined by these rules:

  1. Parentheses: Expressions within parentheses are evaluated first.
  2. Exponentiation (**): Exponentiation is evaluated next. (evaluated from right to left)
  3. Multiplication (*), Division (/), Modulus (%), and Floor Division (//): These operators are evaluated from left to right.
  4. Addition (+) and Subtraction (-): Addition and subtraction are evaluated from left to right.

In the expression a + b - d + e, Python will follow these steps:

  1. a + b: Addition is performed first.
  2. (a + b) - d: Subtraction is performed next.
  3. ((a + b) - d) + e: Finally, the last addition is performed.

Arithmetic Operator Associativity

Associativity is a rule that determines the order of operations for operators with the same precedence.

There are two types of associativity:

Left-Associative: Operations are performed from left to right.

Right-Associative: Operations are performed from right to left.

Examples:

Importance:

Additional Notes:

Comparison Operator's Precedence and Associativity

All comparison operators have the same precedence, meaning they're evaluated from left to right within an expression.

Arithmetic operators have higher precedence than comparison operators. Calculations are done first, then comparisons.

You can use parentheses to control the order of operations explicitly. Comparisons within parentheses are evaluated first.

Logical Operator's Precedence and Associativity

Precedence determines the order in which logical operators are evaluated when multiple operators are present in an expression. It's like the priority seating at a restaurant—some operators get evaluated first.

Here's the precedence order, from highest to lowest:

  1. not
  2. and
  3. or

In Python, logical operators have a left-to-right associativity. This means they're evaluated from left to right within an expression with the same precedence.

result = True or not False and True # True

not False is evaluated first (becomes True) because not have the highest precedence. Then, True or True is evaluated (resulting in True) because and has higher precedence than or

result = True and False or True  # True

True and False is evaluated first (becomes False) because of left-to-right associativity. Then, False or True is evaluated (resulting in True).

Identity Operator's Precedence and Associativity

Identity operators (is and is not) have the lowest precedence among all operators. This means they are evaluated last compared to other operators in an expression.

However, they do not have associativity, as there is only one operand on each side of the operator (is or is not). So, the order of evaluation within an expression with only identity operators doesn't matter.

x = 10 
y = 5 
result = (x is y) and (x == 5) # Evaluates as "(False) and (False)" 
 print(result) # Output: False

Even though is has lower precedence, it's evaluated last within the parentheses

Here, the is operator compares x and y, which are different objects, resulting in False. Then, the operator checks if both False and x == 5 are true (which they aren't), returning the final result of False.

Remember, identity operators only consider object identity, not their values.

Bitwise Operator's Precedence and Associativity

In Python, bitwise operators have specific precedence and associativity that determine the order in which they are evaluated within an expression. Understanding these rules is crucial for writing accurate and efficient bitwise code.

Precedence:

  1. Bitwise NOT (~)
  2. Bitwise left and right shifts
  3. Bitwise AND (&)
  4. Bitwise XOR (^)
  5. Bitwise OR (|)

Associativity:

For operators within the same precedence level, associativity dictates their evaluation order. Bitwise operators follow left-to-right associativity. This means the operator on the left of the expression is evaluated first, then the right operand, and finally the result is combined with the next operator and operand (moving left to right).

Example:

Consider the expression: x = 8 & 6 ^ 3 << 1

Due to precedence, the NOT operator is not involved.

Left-to-right associativity kicks in:

First 3 << 1 is evaluated: 3 << 1 = 6

Then, 8 & 6 is evaluated: 8 & 6 = 0

Finally, 0 ^ 6 is evaluated: 0 ^ 6 = 6

Therefore, the final value of x is 6.

Remember: When dealing with complex bitwise expressions, using parentheses can explicitly define the order of evaluation, even if it aligns with precedence and associativity. This can improve code readability and avoid unintentional outcomes.

Python Operators Quiz

Question-Related to Arithmetic Operators

What is the output of print(“Hi” * 0)?

A. Hi
B. Nothing
C. Error

What is the output of the following code?

print(“Hello” + ” ” + “World”)

A. HelloWorld
B. Hello World
C. Hello World

What is the output of the following code?

print(7 / 2)

A. 3
B. 3.5
C. 4

What is the output of the print(6 / 2)?

A. 3
B. 3.0
c. 4

Which operator is used for string concatenation?

A. +
B. *
C. //

What is the value of 5 + 2 * 3?

A. 11
B. 16
C. 21

Which operation is performed first in the expression 10 - 4 ** 2 + 6?

A. Subtraction
B. Exponentiation
C. Addition

How would you express the following calculation using arithmetic operators: “Subtract 8 from 15, then multiply the result by 2”?

A. 15 – 8 * 2
B. (15 – 8) * 2
C. 2 * 15 – 8

What is the value of (12 / 3) + (4 * 2)?

A. 14
B. 18
C. 20

Which of the following expressions has the same value as 2 ** 3 ** 2?

A. (2 ** 3) ** 2
B. 2 ** (3 ** 2)
C. 2 * 3 * 2

Fill in the blank to make the equation true: 8 - ___ * 4 = 0

A. 2
B. 4
C. 6

What is the correct order of operations in this expression:
9 + 3 * 2 - 6 / 3?

A. Multiply, divide, add, subtract
B. Add, subtract, multiply, divide
C. Divide, multiply, add, subtract

Which operation does the % symbol represent?

A. Exponentiation
B. Modulus (remainder)
C. Floor division

What value would be assigned to the variable x in the following code: x = 10 + 5 * 2 - 4

A. 16
B. 21
C. 26

True or False: Parentheses can always be used to override the default order of operations.

A. True
B. False

What is the value of 2 * 3 ** 2 + 4 // 2 – 1?

A. 15
B. 19
C. 21

Which expression produces a different result than the others?

A. (5 + 2) + 3 ** 2
B. 5 + (2 + 3) ** 2
C. 5 + 2 + (3 ** 2)

Fill in the blank to make the equation true: (16 // 4) ** 2 – _ * 4 = 0

A. 4
B. 3
C. 2

What is the remainder when 55 is divided by 6?

A. 1
B. 3
C. 5

What is the result of 10 // 3 + 10 % 3?

A. 3
B. 4
C. 7

True or False: The expression 4 * 3 // 6 is equivalent to (4 * 3) // 6.

(A) True
(B) False

What is the value of 4 // 2 ** 2 + 8 % 3?

A. 1
B. 2
C. 3

What is the value of 48 // 6 * (3 + 1) – 2 ** 3?

A. 12
B. 24
C. 32

Which of the following expressions has the greatest value?

A. 2 ** 3 ** 2
B. (2 ** 3) ** 2
C. 2 * 3 ** 3

Which operation has higher precedence, modulo or floor division?

A. Modulo
B. Floor division
C. They have the same precedence

What is the value of 128 % 15 // 4 * 2 – 3 ** 2?

A. 1
B. -5
C. -7

What is the value of 5 ** 0?

A. Error
B. 0
C. 1

Which expression produces the smallest value?

(A) 5 ** 4 // 5 ** 2
(B) (5 ** 4) // (5 ** 2)
(C) 5 ** (4 // 5 ** 2)

True or False: The expression (x + y) ** 2 is always equal to x ** 2 + y ** 2.

(A) True
(B) False

What is the value of (2 ** 2 – 4) ** 3 ** 2?

(A) 0
(B) 256
(C) 652

Question-related to Logical Operators

Which of the following expressions evaluates to True?

(a) 10 == 5 or not 4 > 2
(b) 5 != 3 and 7 < 10 ️
(c) True and False or False

What is the associativity of logical operators in Python?

(a) Right-to-left
(b) Left-to-right
(c) It depends on the specific operators

What is the result of the expression not True and False?

(a) True
(b) False

Which operator has the highest precedence?

(a) and
(b) or
(c) not

What does the (or) operator do?

(a) Returns True if both conditions are True
(b) Returns True if at least one condition is True
(c) Reverses the truth value of a condition

Which expression checks if a door is unlocked and the alarm is not active?

a. not (door_locked and not alarm_active)
b. door_locked or not alarm_active
c. not door_locked and not alarm_active

Which expression checks if a player gets 5 or more coins and their health is above 50%?

(a) coins >= 5 and health > 0.5
(b) coins >= 5 or health > 0.5

Which expression checks if a user has enough money, the item is in stock, and it's not their last item?

(a) money >= price and stock > 0 and not last_item
(b) money >= price or stock > 0 or not last_item
(c) (money >= price and stock > 0) or not last_item

Which expression correctly determines if a car can proceed the light is green, no pedestrians are crossing, and there are no oncoming vehicles?

(a) (light == “green”) and not pedestrians_crossing and not oncoming_vehicles
(b) light == “green” or not pedestrians_crossing or not oncoming_vehicles
(c) (light == “green” or not pedestrians_crossing) and not oncoming_vehicles

Question-Related to Identity Operators

You want to check if a variable called message contains an empty string. Which option is correct?

(a) message is ”
(b) not message
(c) len(message) == 0
(d) All of the above

What will the following code print?

a = 5
b = 5
c = a
print(a is b)
print(a is c)
print(b is c)

(a) True, True, True
(b) True, False, True
(c) True, True, False
(d) False, False, False

What will be the output of this code?

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)
print(a is c)
print(b is c)

(a) True, False, False
(b) True, True, True
(c) False, False, False
(d) True, False, True

What is the primary purpose of using the is not operator in Python?

(a) To check if two variables do not refer to the same object in memory.
(b) To compare the numerical values of two variables.
(c) To assign a new value to an existing variable.
(d) To determine if a variable is None.

Question-Related to Membership Operators

What will be the output of the following code?

numbers = [10, 20, 30]
print(15 in numbers)

a) True
b) False
c) Error

Which operator is used to check if a value is not present in a sequence?

a) not
b) in
c) not in

Can you use membership operators with dictionaries?

a) Yes, to check for both keys and values
b) Yes, but only to check for keys
c) No, they only work with lists, tuples, and strings

Consider the following code:

words = [“apple”, “banana”, “apple”]
print(“apple” in words)

How many times will the membership check be performed in this case?

a) Once
b) Twice
c) Three times

What will be the output of the following code?

Python
my_tuple = (“hello”, 5, True)
print(5 in my_tuple)

a) True
b) False
c) Error

Question-Related to Bitwise Operators

What will be the output of the following Python code?

x = 5 # 0101 in binary
y = 3 # 0011 in binary

result = x & y # Bitwise AND
print(result)

a) 2
b) 5
c) 7

Which bitwise operator can be used to check if a number is even in Python?

a) | (Bitwise OR)
b) & (Bitwise AND)
c) >> (Right shift)
d) % (Modulo)

What will be the value of z after the following code?

number = 12 # 1100 in binary
z = number ^ 5 # Bitwise XOR

print(z)

a) 7
b) 13
c) 17
d) 22

What does the following Python code do?

x = 10 # 1010 in binary
y = 6 # 0110 in binary

result = x | y # Bitwise OR
print(result)

a) 12
b) 14
c) 16

Which bitwise operator can be used to set the least significant bit of a number to 1 in Python?

a) | (Bitwise OR) with 1
b) & (Bitwise AND) with 1
c) ^ (Bitwise XOR) with 1

What will be the value of z after the following code?

number = 8 # 1000 in binary
z = number << 2 # Bitwise left shift
print(z)

a) 8
b) 16
c) 32

What will be the output of x & y in the following code?

x = 13 (1101 in binary)
y = 7 (0111 in binary)

a) 5 (0101 in binary)
b) 9 (1001 in binary)
c) 14 (1110 in binary)

Which operator can set the least significant bit of a number to 0 in Python?

a) | (Bitwise OR) with 0
b) & (Bitwise AND) with 0
c) ^ (Bitwise XOR) with 0

What does number << 1 do in Python?

a) Doubles the number
b) Divide the number by 2
c) Multiplies the number by the next highest power of 2

How can you check if the second bit from the right (counting from 0) in a number is 1?

a) Use number & (1 << 1)
b) Use number >> 1 & 1
c) Use number % 4 == 2

What will be the output of ~x in Python?

a) Twice the value of x
b) Negative of x
c) Inverted binary representation of x

Which operator can be used to check if a number is negative in Python?

a) x < 0
b) x & (1 << 31) (Check most significant bit)
c) ~x < 0 (Invert and compare)