Python Basics
Python Variables
Variables are named containers that store data your program can reuse. In Python you create one just by assigning a value with =.
Creating a Variable
You create a variable by writing a name, an equals sign, and a value. Python figures out the data type automatically, so there is no need to declare a type up front like in Java or C.
name = "Aarav"
age = 21
height = 5.9
print(name, age, height)Use clear, lowercase names with underscores, like first_name, so your code reads like plain English.
Variable Naming Rules
| Rule | Example |
|---|---|
| Start with a letter or _ | score, _count |
| No spaces | first_name not first name |
| Case sensitive | Age and age are different variables |
| Cannot use keywords | class = 5 is invalid, since class is reserved |
| Can contain letters, digits, underscores | user_1, total2 |
Dynamic Typing
Python is dynamically typed, which means a variable can hold a value of any type, and you can even reassign it to a completely different type later in the same program.
value = 10
print(type(value))
value = "now I'm a string"
print(type(value))Multiple Assignment
Python lets you assign values to several variables in a single line, which keeps setup code short and readable.
x, y, z = 1, 2, 3
print(x, y, z)
# Assign the same value to multiple variables
a = b = c = 0
print(a, b, c)Once you are comfortable creating variables, the next step is learning about the different data types they can hold, such as numbers, strings and booleans.
