Python Assignment Operators šŸŽÆ

beginner
13 min

Python Assignment Operators šŸŽÆ

Welcome to our comprehensive guide on Python Assignment Operators! In this lesson, we'll explore various operators that help you assign and manipulate values in Python. Let's dive in!

Basic Assignment Operator šŸ“

The most common operator is the = sign, which assigns a value to a variable.

python
x = 5 print(x) # Output: 5

šŸ’” Pro Tip: Always give descriptive names to your variables to make your code more readable!

Arithmetic Assignment Operators šŸŽÆ

Python offers several arithmetic assignment operators, which combine an operation with an assignment. Here are some examples:

  1. Addition and Assignment (+=)
python
x += 3 print(x) # Output: 8
  1. Subtraction and Assignment (-=)
python
x -= 2 print(x) # Output: 6
  1. Multiplication and Assignment (*=)
python
x *= 2 print(x) # Output: 12
  1. Division and Assignment (/=)
python
x /= 2 print(x) # Output: 6.0
  1. Modulus and Assignment (%=)
python
x %= 3 print(x) # Output: 0
  1. Exponentiation and Assignment (**=)
python
x **= 2 print(x) # Output: 0

šŸ“ Note: The modulus operator (%) gives the remainder of the division, and the exponentiation operator (**) raises a number to the power of another number.

Comparison Operators šŸŽÆ

Comparison operators help you compare two values. Let's see some examples:

  1. Equal to (==)
python
x = 5 y = 5 if x == y: print("x is equal to y")
  1. Not equal to (!=)
python
if x != y: print("x is not equal to y")
  1. Greater than (>)
python
if x > y: print("x is greater than y")
  1. Less than (<)
python
if x < y: print("x is less than y")
  1. Greater than or equal to (>=)
python
if x >= y: print("x is greater than or equal to y")
  1. Less than or equal to (<=)
python
if x <= y: print("x is less than or equal to y")

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

Which operator is used to check if a number is greater than or equal to another number?

Conclusion šŸŽÆ

Now that you've learned about Python assignment and comparison operators, you can write more powerful and efficient code. Don't forget to practice using these operators in your projects and experiments!

Stay tuned for more lessons on Python at CodeYourCraft. Happy coding! šŸ’” šŸ’»