Chapter 2: Python Basics
2.3 Operators
In this section, we will discuss the various operators available in Python. Operators are special symbols that allow you to perform operations on values and variables. Python supports several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators.
2.3.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on values.
- Addition (
+
): Adds two values. - Subtraction (): Subtracts the right value from the left value.
- Multiplication (): Multiplies two values.
- Division (
/
): Divides the left value by the right value, resulting in a float. - Floor Division (
//
): Divides the left value by the right value, rounding down to the nearest integer. - Modulus (
%
): Returns the remainder of the division of the left value by the right value. - Exponentiation (
*
): Raises the left value to the power of the right value.
x = 5
y = 2
print(x + y) # Output: 7
print(x - y) # Output: 3
print(x * y) # Output: 10
print(x / y) # Output: 2.5
print(x // y) # Output: 2
print(x % y) # Output: 1
print(x ** y) # Output: 25
2.3.2 Comparison Operators
Comparison operators are used to compare values and return a boolean result (True
or False
).
- Equal to (
==
): Checks if two values are equal. - Not equal to (
!=
): Checks if two values are not equal. - Greater than (
>
): Checks if the left value is greater than the right value. - Less than (
<
): Checks if the left value is less than the right value. - Greater than or equal to (
>=
): Checks if the left value is greater than or equal to the right value. - Less than or equal to (
<=
): Checks if the left value is less than or equal to the right value.
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
2.3.3 Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =
, but there are also compound assignment operators that perform an operation and assignment in a single step.
+=
: Adds the right value to the left variable and assigns the result to the left variable.=
: Subtracts the right value from the left variable and assigns the result to the left variable.=
: Multiplies the left variable by the right value and assigns the result to the left variable./=
: Divides the left variable by the right value and assigns the result to the left variable.//=
: Performs floor division on the left variable by the right value and assigns the result to the left variable.%=
: Calculates the modulus of the left variable divided by the right value and assigns the result to the left variable.*=
: Raises the left variable to the power of the right value and assigns the result to the left variable.
x = 5
x += 3 # Same as x = x + 3, x becomes 8
x -= 2 # Same as x = x - 2, x becomes 6
x *= 4 # Same as x = x * 4, x becomes 24
x /= 3 # Same as x = x / 3, x becomes 8.0
x //= 2 # Same as x = x // 2, x becomes 4.0
x %= 3 # Same as x = x % 3, x becomes 1.0
x **= 2 # Same as x = x ** 2, x becomes 1.0
2.3.4 Logical Operator
Logical operators are used to combine boolean expressions and return a boolean result (True
or False
).
and
: ReturnsTrue
if both expressions are true, otherwise returnsFalse
.or
: ReturnsTrue
if at least one of the expressions is true, otherwise returnsFalse
.not
: ReturnsTrue
if the expression is false, andFalse
if the expression is true.
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
2.3.5 Bitwise Operators
Bitwise operators perform operations on the binary representation of integers.
- Bitwise AND (
&
): Performs a bitwise AND operation on two integers. - Bitwise OR (
|
): Performs a bitwise OR operation on two integers. - Bitwise XOR (
^
): Performs a bitwise XOR operation on two integers. - Bitwise NOT (
~
): Inverts the bits of an integer. - Left Shift (
<<
): Shifts the bits of an integer to the left by a specified number of positions. - Right Shift (
>>
): Shifts the bits of an integer to the right by a specified number of positions.
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
print(x ^ y) # Output: 6 (Binary: 0110)
print(~x) # Output: -6 (Binary: 1010)
print(x << 2) # Output: 20 (Binary: 10100)
print(x >> 1) # Output: 2 (Binary: 0010)
Understanding the various operators in Python will enable you to perform complex operations on your data and create more sophisticated programs. As you continue through this book, you will encounter many practical applications of these operators in various programming tasks and challenges.
Exercise 2.3.1: Simple Arithmetic Operations
In this exercise, you will write a Python program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. You will practice using operators and the print()
function.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare two variables,
num1
andnum2
, and assign them numeric values (e.g., 10 and 5). - Calculate the sum, difference, product, and quotient of
num1
andnum2
, and assign the results to the variablessum
,difference
,product
, andquotient
, respectively. - Use the
print()
function to display the results of the arithmetic operations.
Your final code should look something like this:
num1 = 10
num2 = 5
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
print(f"Sum: {sum}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")
When you run your program, you should see output similar to the following:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0
This exercise helps you become familiar with operators and the print()
function in Python.
Exercise 2.3.2: Maximum of Two Numbers
In this exercise, you will write a Python program that finds the maximum of two numbers entered by the user. You will practice using input, output, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Use the
input()
function to prompt the user to enter two numbers, and assign the results to variablesnum1
andnum2
. Remember to convert the input to the appropriate data type (e.g., float or int). - Use the appropriate operator to find the maximum of the two numbers, and assign the result to a variable named
max_num
. - Use the
print()
function to display the maximum of the two numbers.
Your final code should look something like this:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
max_num = num1 if num1 > num2 else num2
print(f"The maximum of {num1} and {num2} is {max_num}")
When you run your program, you should see output similar to the following (depending on user input):
Enter the first number: 6.5
Enter the second number: 4.2
The maximum of 6.5 and 4.2 is 6.5
Exercise 2.3.3: Calculate the Distance Between Two Points
In this exercise, you will write a Python program that calculates the distance between two points in a 2D plane using their coordinates. You will practice using variables, data types, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare four variables:
x1
,y1
,x2
, andy2
. Assign them appropriate coordinates (e.g., 3, 4, 6, and 8, respectively). - Calculate the distance between the two points using the distance formula
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
, and assign the result to a variable nameddistance
. - Use the
print()
function to display the calculated distance between the two points.
Your final code should look something like this:
x1, y1 = 3, 4
x2, y2 = 6, 8
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"The distance between point A({x1}, {y1}) and point B({x2}, {y2}) is {distance:.2f}")
When you run your program, you should see output similar to the following:
The distance between point A(3, 4) and point B(6, 8) is 5.00
Feel free to modify the variables to practice with different coordinates. These exercises help you become familiar with operators in Python.
2.3 Operators
In this section, we will discuss the various operators available in Python. Operators are special symbols that allow you to perform operations on values and variables. Python supports several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators.
2.3.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on values.
- Addition (
+
): Adds two values. - Subtraction (): Subtracts the right value from the left value.
- Multiplication (): Multiplies two values.
- Division (
/
): Divides the left value by the right value, resulting in a float. - Floor Division (
//
): Divides the left value by the right value, rounding down to the nearest integer. - Modulus (
%
): Returns the remainder of the division of the left value by the right value. - Exponentiation (
*
): Raises the left value to the power of the right value.
x = 5
y = 2
print(x + y) # Output: 7
print(x - y) # Output: 3
print(x * y) # Output: 10
print(x / y) # Output: 2.5
print(x // y) # Output: 2
print(x % y) # Output: 1
print(x ** y) # Output: 25
2.3.2 Comparison Operators
Comparison operators are used to compare values and return a boolean result (True
or False
).
- Equal to (
==
): Checks if two values are equal. - Not equal to (
!=
): Checks if two values are not equal. - Greater than (
>
): Checks if the left value is greater than the right value. - Less than (
<
): Checks if the left value is less than the right value. - Greater than or equal to (
>=
): Checks if the left value is greater than or equal to the right value. - Less than or equal to (
<=
): Checks if the left value is less than or equal to the right value.
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
2.3.3 Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =
, but there are also compound assignment operators that perform an operation and assignment in a single step.
+=
: Adds the right value to the left variable and assigns the result to the left variable.=
: Subtracts the right value from the left variable and assigns the result to the left variable.=
: Multiplies the left variable by the right value and assigns the result to the left variable./=
: Divides the left variable by the right value and assigns the result to the left variable.//=
: Performs floor division on the left variable by the right value and assigns the result to the left variable.%=
: Calculates the modulus of the left variable divided by the right value and assigns the result to the left variable.*=
: Raises the left variable to the power of the right value and assigns the result to the left variable.
x = 5
x += 3 # Same as x = x + 3, x becomes 8
x -= 2 # Same as x = x - 2, x becomes 6
x *= 4 # Same as x = x * 4, x becomes 24
x /= 3 # Same as x = x / 3, x becomes 8.0
x //= 2 # Same as x = x // 2, x becomes 4.0
x %= 3 # Same as x = x % 3, x becomes 1.0
x **= 2 # Same as x = x ** 2, x becomes 1.0
2.3.4 Logical Operator
Logical operators are used to combine boolean expressions and return a boolean result (True
or False
).
and
: ReturnsTrue
if both expressions are true, otherwise returnsFalse
.or
: ReturnsTrue
if at least one of the expressions is true, otherwise returnsFalse
.not
: ReturnsTrue
if the expression is false, andFalse
if the expression is true.
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
2.3.5 Bitwise Operators
Bitwise operators perform operations on the binary representation of integers.
- Bitwise AND (
&
): Performs a bitwise AND operation on two integers. - Bitwise OR (
|
): Performs a bitwise OR operation on two integers. - Bitwise XOR (
^
): Performs a bitwise XOR operation on two integers. - Bitwise NOT (
~
): Inverts the bits of an integer. - Left Shift (
<<
): Shifts the bits of an integer to the left by a specified number of positions. - Right Shift (
>>
): Shifts the bits of an integer to the right by a specified number of positions.
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
print(x ^ y) # Output: 6 (Binary: 0110)
print(~x) # Output: -6 (Binary: 1010)
print(x << 2) # Output: 20 (Binary: 10100)
print(x >> 1) # Output: 2 (Binary: 0010)
Understanding the various operators in Python will enable you to perform complex operations on your data and create more sophisticated programs. As you continue through this book, you will encounter many practical applications of these operators in various programming tasks and challenges.
Exercise 2.3.1: Simple Arithmetic Operations
In this exercise, you will write a Python program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. You will practice using operators and the print()
function.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare two variables,
num1
andnum2
, and assign them numeric values (e.g., 10 and 5). - Calculate the sum, difference, product, and quotient of
num1
andnum2
, and assign the results to the variablessum
,difference
,product
, andquotient
, respectively. - Use the
print()
function to display the results of the arithmetic operations.
Your final code should look something like this:
num1 = 10
num2 = 5
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
print(f"Sum: {sum}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")
When you run your program, you should see output similar to the following:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0
This exercise helps you become familiar with operators and the print()
function in Python.
Exercise 2.3.2: Maximum of Two Numbers
In this exercise, you will write a Python program that finds the maximum of two numbers entered by the user. You will practice using input, output, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Use the
input()
function to prompt the user to enter two numbers, and assign the results to variablesnum1
andnum2
. Remember to convert the input to the appropriate data type (e.g., float or int). - Use the appropriate operator to find the maximum of the two numbers, and assign the result to a variable named
max_num
. - Use the
print()
function to display the maximum of the two numbers.
Your final code should look something like this:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
max_num = num1 if num1 > num2 else num2
print(f"The maximum of {num1} and {num2} is {max_num}")
When you run your program, you should see output similar to the following (depending on user input):
Enter the first number: 6.5
Enter the second number: 4.2
The maximum of 6.5 and 4.2 is 6.5
Exercise 2.3.3: Calculate the Distance Between Two Points
In this exercise, you will write a Python program that calculates the distance between two points in a 2D plane using their coordinates. You will practice using variables, data types, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare four variables:
x1
,y1
,x2
, andy2
. Assign them appropriate coordinates (e.g., 3, 4, 6, and 8, respectively). - Calculate the distance between the two points using the distance formula
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
, and assign the result to a variable nameddistance
. - Use the
print()
function to display the calculated distance between the two points.
Your final code should look something like this:
x1, y1 = 3, 4
x2, y2 = 6, 8
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"The distance between point A({x1}, {y1}) and point B({x2}, {y2}) is {distance:.2f}")
When you run your program, you should see output similar to the following:
The distance between point A(3, 4) and point B(6, 8) is 5.00
Feel free to modify the variables to practice with different coordinates. These exercises help you become familiar with operators in Python.
2.3 Operators
In this section, we will discuss the various operators available in Python. Operators are special symbols that allow you to perform operations on values and variables. Python supports several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators.
2.3.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on values.
- Addition (
+
): Adds two values. - Subtraction (): Subtracts the right value from the left value.
- Multiplication (): Multiplies two values.
- Division (
/
): Divides the left value by the right value, resulting in a float. - Floor Division (
//
): Divides the left value by the right value, rounding down to the nearest integer. - Modulus (
%
): Returns the remainder of the division of the left value by the right value. - Exponentiation (
*
): Raises the left value to the power of the right value.
x = 5
y = 2
print(x + y) # Output: 7
print(x - y) # Output: 3
print(x * y) # Output: 10
print(x / y) # Output: 2.5
print(x // y) # Output: 2
print(x % y) # Output: 1
print(x ** y) # Output: 25
2.3.2 Comparison Operators
Comparison operators are used to compare values and return a boolean result (True
or False
).
- Equal to (
==
): Checks if two values are equal. - Not equal to (
!=
): Checks if two values are not equal. - Greater than (
>
): Checks if the left value is greater than the right value. - Less than (
<
): Checks if the left value is less than the right value. - Greater than or equal to (
>=
): Checks if the left value is greater than or equal to the right value. - Less than or equal to (
<=
): Checks if the left value is less than or equal to the right value.
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
2.3.3 Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =
, but there are also compound assignment operators that perform an operation and assignment in a single step.
+=
: Adds the right value to the left variable and assigns the result to the left variable.=
: Subtracts the right value from the left variable and assigns the result to the left variable.=
: Multiplies the left variable by the right value and assigns the result to the left variable./=
: Divides the left variable by the right value and assigns the result to the left variable.//=
: Performs floor division on the left variable by the right value and assigns the result to the left variable.%=
: Calculates the modulus of the left variable divided by the right value and assigns the result to the left variable.*=
: Raises the left variable to the power of the right value and assigns the result to the left variable.
x = 5
x += 3 # Same as x = x + 3, x becomes 8
x -= 2 # Same as x = x - 2, x becomes 6
x *= 4 # Same as x = x * 4, x becomes 24
x /= 3 # Same as x = x / 3, x becomes 8.0
x //= 2 # Same as x = x // 2, x becomes 4.0
x %= 3 # Same as x = x % 3, x becomes 1.0
x **= 2 # Same as x = x ** 2, x becomes 1.0
2.3.4 Logical Operator
Logical operators are used to combine boolean expressions and return a boolean result (True
or False
).
and
: ReturnsTrue
if both expressions are true, otherwise returnsFalse
.or
: ReturnsTrue
if at least one of the expressions is true, otherwise returnsFalse
.not
: ReturnsTrue
if the expression is false, andFalse
if the expression is true.
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
2.3.5 Bitwise Operators
Bitwise operators perform operations on the binary representation of integers.
- Bitwise AND (
&
): Performs a bitwise AND operation on two integers. - Bitwise OR (
|
): Performs a bitwise OR operation on two integers. - Bitwise XOR (
^
): Performs a bitwise XOR operation on two integers. - Bitwise NOT (
~
): Inverts the bits of an integer. - Left Shift (
<<
): Shifts the bits of an integer to the left by a specified number of positions. - Right Shift (
>>
): Shifts the bits of an integer to the right by a specified number of positions.
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
print(x ^ y) # Output: 6 (Binary: 0110)
print(~x) # Output: -6 (Binary: 1010)
print(x << 2) # Output: 20 (Binary: 10100)
print(x >> 1) # Output: 2 (Binary: 0010)
Understanding the various operators in Python will enable you to perform complex operations on your data and create more sophisticated programs. As you continue through this book, you will encounter many practical applications of these operators in various programming tasks and challenges.
Exercise 2.3.1: Simple Arithmetic Operations
In this exercise, you will write a Python program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. You will practice using operators and the print()
function.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare two variables,
num1
andnum2
, and assign them numeric values (e.g., 10 and 5). - Calculate the sum, difference, product, and quotient of
num1
andnum2
, and assign the results to the variablessum
,difference
,product
, andquotient
, respectively. - Use the
print()
function to display the results of the arithmetic operations.
Your final code should look something like this:
num1 = 10
num2 = 5
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
print(f"Sum: {sum}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")
When you run your program, you should see output similar to the following:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0
This exercise helps you become familiar with operators and the print()
function in Python.
Exercise 2.3.2: Maximum of Two Numbers
In this exercise, you will write a Python program that finds the maximum of two numbers entered by the user. You will practice using input, output, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Use the
input()
function to prompt the user to enter two numbers, and assign the results to variablesnum1
andnum2
. Remember to convert the input to the appropriate data type (e.g., float or int). - Use the appropriate operator to find the maximum of the two numbers, and assign the result to a variable named
max_num
. - Use the
print()
function to display the maximum of the two numbers.
Your final code should look something like this:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
max_num = num1 if num1 > num2 else num2
print(f"The maximum of {num1} and {num2} is {max_num}")
When you run your program, you should see output similar to the following (depending on user input):
Enter the first number: 6.5
Enter the second number: 4.2
The maximum of 6.5 and 4.2 is 6.5
Exercise 2.3.3: Calculate the Distance Between Two Points
In this exercise, you will write a Python program that calculates the distance between two points in a 2D plane using their coordinates. You will practice using variables, data types, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare four variables:
x1
,y1
,x2
, andy2
. Assign them appropriate coordinates (e.g., 3, 4, 6, and 8, respectively). - Calculate the distance between the two points using the distance formula
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
, and assign the result to a variable nameddistance
. - Use the
print()
function to display the calculated distance between the two points.
Your final code should look something like this:
x1, y1 = 3, 4
x2, y2 = 6, 8
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"The distance between point A({x1}, {y1}) and point B({x2}, {y2}) is {distance:.2f}")
When you run your program, you should see output similar to the following:
The distance between point A(3, 4) and point B(6, 8) is 5.00
Feel free to modify the variables to practice with different coordinates. These exercises help you become familiar with operators in Python.
2.3 Operators
In this section, we will discuss the various operators available in Python. Operators are special symbols that allow you to perform operations on values and variables. Python supports several types of operators, including arithmetic, comparison, assignment, logical, and bitwise operators.
2.3.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on values.
- Addition (
+
): Adds two values. - Subtraction (): Subtracts the right value from the left value.
- Multiplication (): Multiplies two values.
- Division (
/
): Divides the left value by the right value, resulting in a float. - Floor Division (
//
): Divides the left value by the right value, rounding down to the nearest integer. - Modulus (
%
): Returns the remainder of the division of the left value by the right value. - Exponentiation (
*
): Raises the left value to the power of the right value.
x = 5
y = 2
print(x + y) # Output: 7
print(x - y) # Output: 3
print(x * y) # Output: 10
print(x / y) # Output: 2.5
print(x // y) # Output: 2
print(x % y) # Output: 1
print(x ** y) # Output: 25
2.3.2 Comparison Operators
Comparison operators are used to compare values and return a boolean result (True
or False
).
- Equal to (
==
): Checks if two values are equal. - Not equal to (
!=
): Checks if two values are not equal. - Greater than (
>
): Checks if the left value is greater than the right value. - Less than (
<
): Checks if the left value is less than the right value. - Greater than or equal to (
>=
): Checks if the left value is greater than or equal to the right value. - Less than or equal to (
<=
): Checks if the left value is less than or equal to the right value.
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
2.3.3 Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is =
, but there are also compound assignment operators that perform an operation and assignment in a single step.
+=
: Adds the right value to the left variable and assigns the result to the left variable.=
: Subtracts the right value from the left variable and assigns the result to the left variable.=
: Multiplies the left variable by the right value and assigns the result to the left variable./=
: Divides the left variable by the right value and assigns the result to the left variable.//=
: Performs floor division on the left variable by the right value and assigns the result to the left variable.%=
: Calculates the modulus of the left variable divided by the right value and assigns the result to the left variable.*=
: Raises the left variable to the power of the right value and assigns the result to the left variable.
x = 5
x += 3 # Same as x = x + 3, x becomes 8
x -= 2 # Same as x = x - 2, x becomes 6
x *= 4 # Same as x = x * 4, x becomes 24
x /= 3 # Same as x = x / 3, x becomes 8.0
x //= 2 # Same as x = x // 2, x becomes 4.0
x %= 3 # Same as x = x % 3, x becomes 1.0
x **= 2 # Same as x = x ** 2, x becomes 1.0
2.3.4 Logical Operator
Logical operators are used to combine boolean expressions and return a boolean result (True
or False
).
and
: ReturnsTrue
if both expressions are true, otherwise returnsFalse
.or
: ReturnsTrue
if at least one of the expressions is true, otherwise returnsFalse
.not
: ReturnsTrue
if the expression is false, andFalse
if the expression is true.
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
2.3.5 Bitwise Operators
Bitwise operators perform operations on the binary representation of integers.
- Bitwise AND (
&
): Performs a bitwise AND operation on two integers. - Bitwise OR (
|
): Performs a bitwise OR operation on two integers. - Bitwise XOR (
^
): Performs a bitwise XOR operation on two integers. - Bitwise NOT (
~
): Inverts the bits of an integer. - Left Shift (
<<
): Shifts the bits of an integer to the left by a specified number of positions. - Right Shift (
>>
): Shifts the bits of an integer to the right by a specified number of positions.
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
print(x ^ y) # Output: 6 (Binary: 0110)
print(~x) # Output: -6 (Binary: 1010)
print(x << 2) # Output: 20 (Binary: 10100)
print(x >> 1) # Output: 2 (Binary: 0010)
Understanding the various operators in Python will enable you to perform complex operations on your data and create more sophisticated programs. As you continue through this book, you will encounter many practical applications of these operators in various programming tasks and challenges.
Exercise 2.3.1: Simple Arithmetic Operations
In this exercise, you will write a Python program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. You will practice using operators and the print()
function.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare two variables,
num1
andnum2
, and assign them numeric values (e.g., 10 and 5). - Calculate the sum, difference, product, and quotient of
num1
andnum2
, and assign the results to the variablessum
,difference
,product
, andquotient
, respectively. - Use the
print()
function to display the results of the arithmetic operations.
Your final code should look something like this:
num1 = 10
num2 = 5
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
print(f"Sum: {sum}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")
When you run your program, you should see output similar to the following:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0
This exercise helps you become familiar with operators and the print()
function in Python.
Exercise 2.3.2: Maximum of Two Numbers
In this exercise, you will write a Python program that finds the maximum of two numbers entered by the user. You will practice using input, output, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Use the
input()
function to prompt the user to enter two numbers, and assign the results to variablesnum1
andnum2
. Remember to convert the input to the appropriate data type (e.g., float or int). - Use the appropriate operator to find the maximum of the two numbers, and assign the result to a variable named
max_num
. - Use the
print()
function to display the maximum of the two numbers.
Your final code should look something like this:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
max_num = num1 if num1 > num2 else num2
print(f"The maximum of {num1} and {num2} is {max_num}")
When you run your program, you should see output similar to the following (depending on user input):
Enter the first number: 6.5
Enter the second number: 4.2
The maximum of 6.5 and 4.2 is 6.5
Exercise 2.3.3: Calculate the Distance Between Two Points
In this exercise, you will write a Python program that calculates the distance between two points in a 2D plane using their coordinates. You will practice using variables, data types, and operators.
Instructions:
- Create a new Python file or open a Python interpreter.
- Declare four variables:
x1
,y1
,x2
, andy2
. Assign them appropriate coordinates (e.g., 3, 4, 6, and 8, respectively). - Calculate the distance between the two points using the distance formula
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
, and assign the result to a variable nameddistance
. - Use the
print()
function to display the calculated distance between the two points.
Your final code should look something like this:
x1, y1 = 3, 4
x2, y2 = 6, 8
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"The distance between point A({x1}, {y1}) and point B({x2}, {y2}) is {distance:.2f}")
When you run your program, you should see output similar to the following:
The distance between point A(3, 4) and point B(6, 8) is 5.00
Feel free to modify the variables to practice with different coordinates. These exercises help you become familiar with operators in Python.