Python - Operators
//
operator in Python.
In Python, the //
operator is the floor division operator. It performs division and returns the largest integer less than or equal to the quotient.
Example: Using the //
operator for floor division.
# Example
dividend = 10
divisor = 3
# Perform floor division
result = dividend // divisor
print("Result:", result)
Result: 3
In this example, the //
operator is used to perform floor division of 10 by 3, resulting in 3. The general syntax is dividend // divisor
.
+=
and *=
operators with examples.
In Python, the +=
and *=
operators are assignment operators that perform addition and multiplication, respectively, and update the value of the variable.
Example 1: Using the +=
operator for addition.
# Example
num1 = 5
# Add 3 to num1 using +=
num1 += 3
print("Result:", num1)
Result: 8
In this example, the +=
operator adds 3 to the variable num1
, updating its value to 8.
Example 2: Using the *=
operator for multiplication.
# Example
num2 = 4
# Multiply num2 by 2 using *=
num2 *= 2
print("Result:", num2)
Result: 8
In this example, the *=
operator multiplies the variable num2
by 2, updating its value to 8.
not
operator to negate a boolean value in Python?
In Python, the not
operator is a unary operator used to negate a boolean value. It returns True
if the operand is False
, and False
if the operand is True
.
Example: Using the not
operator to negate a boolean value.
# Example
is_python_fun = True
# Use not to negate the boolean value
not_python_fun = not is_python_fun
# Display the results
print("Original Value:", is_python_fun)
print("Negated Value:", not_python_fun)
Original Value: True Negated Value: False
In this example, the not
operator negates the boolean value of is_python_fun
, changing it from True
to False
.
()
operator in Python and give examples of its use.
In Python, the ()
operator is used for creating tuples, specifying function arguments, and controlling the order of operations. It is also used for function calls and grouping expressions.
Example 1: Creating a tuple using ()
.
# Example
my_tuple = (1, 2, 3)
# Display the tuple
print("Tuple:", my_tuple)
Tuple: (1, 2, 3)
In this example, the ()
operator is used to create a tuple containing the elements 1, 2, and 3.
Example 2: Using ()
for function calls and grouping expressions.
# Example
result = (5 + 3) * 2
# Display the result
print("Result:", result)
Result: 16
Here, the ()
operator is used to group the addition operation before multiplying by 2, affecting the order of operations.