Python Variables

What Is a Variable?

A variable is a named container used to store data. In Python, you don’t need to declare the type of variable — it’s inferred automatically:

x = 5
name = "Alice"
pi = 3.14

Variable Naming Rules

  • Must start with a letter or underscore _
  • Cannot start with a number
  • Only letters, numbers, and underscores are allowed
  • Case-sensitive (e.g., myVarMyVar)
# Valid:
name = "John"
_age = 30
user1 = "Admin"

# Invalid:
1name = "Error"
user-name = "Error"

Dynamic Typing

Python allows variables to change type dynamically:

x = 42       # int
x = "hello"  # now a string

Type Checking and Casting

Use type() to check the type, and int(), str(), float() to convert:

x = 5
print(type(x))     # <class 'int'>

x = str(5)
y = float(3)

Multiple Assignments

a, b, c = "Apple", "Banana", "Cherry"
x = y = z = 0

Best Practices

  • Use descriptive names like user_name over x
  • Single-letter names are okay in loops (e.g., for i in range(5))
  • Stick to a consistent naming style (e.g., snake_case)

Practice Question

What will be the output of the following code?

Loading...
Output:

Hint: What type does Python assign to a after reassignment?

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic