Python Basics
Python Variables
Master Python variable assignment, naming rules, multiple assignment, and variable types.
Python Variables
Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
Variable Naming Rules
- A variable name must start with a letter or underscore
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores
- Variable names are case-sensitive (
age,Age, andAGEare three different variables) - A variable name cannot be a Python keyword
Multiple Assignment
Python allows you to assign values to multiple variables in one line.
Python as a Dynamic Language
Python is dynamically typed — you can assign different types to the same variable. Use the type() built-in to check a variable's type.
Variable Scope
Variables created outside of functions are global variables. Variables created inside functions are local variables.
Example
python
# Basic assignment
x = 5
name = "DevForge"
is_cool = True
# Multiple assignment
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Same value to multiple variables
x = y = z = 0
# Type checking
print(type(x)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(is_cool)) # <class 'bool'>
# Dynamic typing
var = 42
print(type(var)) # <class 'int'>
var = "now a string"
print(type(var)) # <class 'str'>
# Global vs local
count = 0 # global
def increment():
global count # reference global
count += 1
increment()
print(count) # 1Try it yourself — PYTHON