Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“ Python Assignment Operators: Complete Guide

Python Assignment Operators - Complete Guide

Assignment operators help you store and update values efficiently in Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • Introduction to Assignment Operators
  • Quick Reference Table
  • Simple Assignment (=)
  • Compound Assignment Operators
  • Real-World Examples
  • Common Mistakes to Avoid
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What assignment operators are — tools to store and update values
  • Simple Assignment (=) — the basic way to assign values
  • Compound Assignment Operators — shortcuts like +=, -=, *=
  • Real-world examples — shopping cart, game score, banking
  • Common mistakes — and how to avoid them
  • Hands-on practice with the interactive editor

Introduction: Mastering Python Assignment Operators

Every Python script needs to store values — that's where Assignment Operators come in. They assign values to variables so your program can "remember" what it calculated.

šŸ’” Key insight: Think of the assignment operator (=) like the "equals" button on a calculator. It takes the result on the right and puts it into the variable on the left.

The Basics

Think of an assignment operator as a bridge between your data and variable. The most common is the equals sign (=) — the foundation of everything you'll build in Python.

Why They Matter

These operators do more than store data — they let you modify, change, or update values on the fly. Instead of writing long, repetitive code, you can keep your scripts clean, efficient, and professional.

Whether you're working with strings, integers, or lists, mastering assignments is your first step toward writing real, functional code.

Quick Reference Table

Here's a quick reference of all Python assignment operators you'll learn in this tutorial:

Operator Example Equivalent To Description
= x = 5 x = 5 Simple assignment
+= x += 3 x = x + 3 Addition assignment
-= x -= 3 x = x - 3 Subtraction assignment
*= x *= 3 x = x * 3 Multiplication assignment
/= x /= 3 x = x / 3 Division assignment
%= x %= 3 x = x % 3 Modulus assignment
//= x //= 3 x = x // 3 Floor division assignment
**= x **= 3 x = x ** 3 Exponentiation assignment
&= x &= 3 x = x & 3 Bitwise AND assignment
|= x |= 3 x = x | 3 Bitwise OR assignment
^= x ^= 3 x = x ^ 3 Bitwise XOR assignment
>>= x >>= 1 x = x >> 1 Right shift assignment
<<= x <<= 1 x = x << 1 Left shift assignment

1. The Basic Assignment Operator (=)

Python has one simple assignment operator: =. Don't confuse this with "equal to" in math — in programming, this is a command to move data.

This operator takes whatever is on the right side (the value or the calculation) and assigns it to the variable on the left side. Whether you're working with a simple number, a string of text, or even complex objects like Lists and Tuples, the = operator is your go-to tool.

General Syntax:
Variable = Value or Expression

# Examples
x = 100          # Assigning 100 to variable x
y = x            # Passing the value of x into y

print("Value of x =", x)
print("Value of y =", y)

# Output:
# Value of x = 100
# Value of y = 100

šŸ“– What happened here? First, we told Python to store 100 in x. Then, we told it to look at what's inside x and put that exact same value into y. It's like making a copy of a file from one folder to another!

2. Compound Assignment Operators

Compound Assignment Operators are shortcuts that let you perform an operation and assignment in a single step. Instead of writing x = x + 5, you can simply write x += 5. These are widely used to make code more concise and readable.

3. Real-World Examples

šŸ›’ Shopping Cart Total

# Shopping Cart Example
total = 0
items = [25.50, 10.00, 15.75]

for price in items:
    total += price  # Same as total = total + price

print(f"Total: ${total:.2f}")

# Output:
# Total: $51.25

šŸŽ® Game Score Tracker

# Game Score Example
score = 0
score += 10  # Player wins! Add 10 points
score *= 2   # Bonus round! Double the score
print(f"Final Score: {score}")

# Output:
# Final Score: 20

šŸ¦ Banking Balance Update

# Banking Balance Example
balance = 1000
balance += 500  # Deposit ₹500
balance -= 200  # Withdrawal ₹200
print(f"Current Balance: ₹{balance}")

# Output:
# Current Balance: ₹1300

4. Common Mistakes to Avoid

āŒ Mistake 1: Confusing = with ==

This is the most common mistake beginners make!

# WRONG (assignment in condition)
if x = 5:  # This will cause a SyntaxError!
    print("x is 5")

# CORRECT (comparison)
if x == 5:
    print("x is 5")

āŒ Mistake 2: Using += on incompatible types

Works fine for strings! But be careful with numbers vs strings.

# This works
text = "Hello"
text += " World"
print(text)  # Output: Hello World

# This will cause an error
num = "10"
num += 5  # TypeError: can only concatenate str to str

āŒ Mistake 3: Forgetting to initialize a variable

You can't use += on a variable that hasn't been defined yet.

# This will cause an error
total += 10  # NameError: name 'total' is not defined

# Do this instead
total = 0
total += 10  # Now it works

Try It Yourself!

Experiment with assignment operators directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
ASSIGNMENT OPERATORS
========================================

1. SIMPLE ASSIGNMENT (=)
x = 100, y = 100

2. ADDITION ASSIGNMENT (+=)
a += 5: 15

3. SUBTRACTION ASSIGNMENT (-=)
b -= 3: 7

4. MULTIPLICATION ASSIGNMENT (*=)
c *= 3: 30

5. DIVISION ASSIGNMENT (/=)
d /= 3: 3.3333333333333335

6. MODULUS ASSIGNMENT (%=)
e %= 3: 1

7. EXPONENTIATION ASSIGNMENT (**=)
f **= 4: 81

8. REAL-WORLD EXAMPLE (Shopping Cart)
Total: $51.25

9. REAL-WORLD EXAMPLE (Banking)
Current Balance: ₹1300

āœ… Assignment operators make your code cleaner!
šŸ†

šŸŽ‰ You've Mastered Python Assignment Operators!

You understand simple assignment (=) and all compound assignment operators (+=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=). These are essential for writing efficient Python code.

Quick Quiz – Test Your Knowledge

Let's see what you've learned about Python assignment operators:

1. What is the result of x = 5; x += 3; print(x)?
2. What does x *= 2 mean?
3. What is the result of a = 7; a %= 2; print(a)?

Frequently Asked Questions

šŸ¤” What's the difference between = and ==? ā–¼

= is the assignment operator used to assign values to variables. == is the equality operator used to compare two values. Never confuse them!

šŸ”§ Can I chain assignment operators in Python? ā–¼

Yes! You can chain assignments like x = y = z = 10. This assigns the value 10 to all three variables.

šŸ“ What's the difference between /= and //=? ā–¼

/= performs true division and returns a float. //= performs floor division and returns an integer rounded down.

šŸ“Š Are compound assignment operators faster? ā–¼

Yes! Compound assignment operators like += are not only more concise but also slightly faster because they modify the variable in place rather than creating a new object.

šŸ“š Where to Go From Here

Now that you understand Python assignment operators, here are some related topics to explore:

šŸ”¢ Arithmetic Operators

Learn about arithmetic operators

šŸ“Š Relational Operators

Learn about comparison operators

🧠 Logical Operators

Learn about logical operators

šŸ“– Related Tutorials
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
šŸ“– Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Arithmetic Operators Next: Shorthand Assignment →