A Beginner's Guide to Python Operators and Expressions with Examples
So, you've decided to learn Python? That's awesome! One of the first things you'll need to wrap your head around is operators and expressions, essential building blocks in any programming language. Let's explore these concepts with some easy examples to get you started on your Python journey.
A Beginner's Guide to Python Operators and Expressions
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Assignment Operators
1. Arithmetic Operators
Arithmetic operators are pretty straightforward. They allow you to perform basic mathematical operations like adding, subtracting, multiplying, and dividing numbers.
-
Addition (+): Combines two numbers together.
result = 5 + 3 print(result) # Output: 8
-
Subtraction (-): Takes one number away from another.
result = 10 - 3 print(result) # Output: 7
-
Multiplication (*): Multiplies two numbers.
result = 4 * 2 print(result) # Output: 8
-
Division (/): Divides one number by another.
result = 16 / 4 print(result) # Output: 4.0
-
Modulus (%): Gives the remainder of a division.
result = 7 % 3 print(result) # Output: 1
2. Comparison Operators
Comparison operators compare two values and return either True
or False
.
-
Equal (==): Checks if two values are the same.
print(5 == 5) # Output: True
-
Not equal (!=): Checks if two values are different.
print(5 != 3) # Output: True
-
Greater than (>): Checks if one value is larger than the other.
print(7 > 3) # Output: True
-
Less than (<): Checks if one value is smaller than the other.
print(4 < 8) # Output: True
-
Greater than or equal to (>=): Combines greater than or equal conditions.
print(5 >= 5) # Output: True
3. Logical Operators
Logical operators help you combine multiple conditions.
-
And (and): Returns
True
if both conditions are true.print((5 > 3) and (3 < 7)) # Output: True
-
Or (or): Returns
True
if at least one condition is true.print((5 < 3) or (3 < 7)) # Output: True
-
Not (not): Reverses the logical state of its operand.
print(not(7 > 3)) # Output: False
4. Assignment Operators
Assignment operators allow you to store values in variables.
-
Equals (=): Assigns value from right side to left side.
x = 10 print(x) # Output: 10
-
Add and assign (+=): Adds right value to left variable and assigns result.
x = 5 x += 3 print(x) # Output: 8
Congratulations, you've just scratched the surface of Python operators and expressions! Understanding these fundamentals will really help you as you continue to dig deeper into coding.
Keep experimenting and practicing these examples on your own. Happy coding!