2. Python Variables
Python Variables
A variable is a named container that holds a value in memory. Think of it like a labeled box — you give the box a name, put something inside it, and you can always refer to that box by name later to get or change what's inside.
In Python, you do not need to declare a variable's type before using it. You simply write the name, an equals sign, and the value. Python figures out the type automatically.
Creating a Variable
Creating a variable in Python requires just one line. The = sign is the assignment operator — it assigns the value on the right to the variable name on the left.
Notice that name holds text (a string), age holds a whole number (an integer), and height holds a decimal number (a float). Python handled all three types automatically.
Variable Naming Rules
Variable names in Python must follow a specific set of rules. Breaking these rules will cause a SyntaxError and your program will not run.
- A variable name must start with a letter or an underscore ( _ )
- A variable name cannot start with a number
- Variable names can only contain letters, numbers, and underscores — no spaces or hyphens
- Variable names are case-sensitive — age, Age, and AGE are three different variables
- Variable names cannot be Python keywords like print, if, for, or True
Casting
Casting means explicitly converting a value from one data type to another. By default Python decides the type, but sometimes you need to force a specific one.
- str() — Converts a value to a string (text)
- int() — Converts a value to an integer (whole number)
- float() — Converts a value to a float (decimal number)
Notice that int(3.9) becomes 3, not 4. Casting to int always truncates (cuts off) the decimal portion — it does not round.
Get the Type
You can check exactly what data type Python has assigned to any variable using the built-in type() function. This is incredibly useful when debugging your programs.
Assigning Multiple Variables
Python gives you two efficient ways to assign multiple variables at once, saving lines and making your code cleaner.
Global vs Local Variables
A variable created inside a function is called a local variable — it only exists within that function. A variable created outside all functions is a global variable — it can be accessed from anywhere in the file.
The function printed its own local x. After the function, the global x is still unchanged. They are completely separate variables that happen to share the same name.
Knowledge Check
Ready to test your understanding of 2. Python Variables?