Welcome to the fundamental building blocks of programming! In this lesson, you will discover how to harness the power of variables to store information in Python, allowing your programs to "remember" data for later use.
Think of a variable as a labeled box stored in your computer's memory. When you assign a value to a variable, you are effectively placing an objectโlike a number or a piece of textโinside that box. In Python, you don't need to specify the type of data beforehand; the language is dynamically typed, meaning it figures out what is inside the box automatically.
To create a variable, you use the assignment operator (=). It is vital to understand that this is not a mathematical equality, but an instruction to "store the value on the right into the name on the left."
# Creating variables
user_age = 25
user_name = "Alice"
A common pitfall for beginners is confusing the variable name with the value itself. Always think of the variable name as a pointer to the data. If you reassign the variable, the old data is discarded by Pythonโs garbage collector.
Python categorizes data into different data types. Two of the most essential types are integers (whole numbers) and strings (text). An integer is any whole number, such as , , or . A string, on the other hand, is a sequence of characters wrapped in quotes, such as "Hello World".
Because Python is smart about types, you can add two integers together and get a new integer, but if you try to add an integer to a string, Python will raise a TypeError. Knowing the "identity" of your data is the first step toward writing bug-free code.
Variables become powerful when you use them in calculations. Python supports all standard arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/). You can perform these operations on variables just as you would with literal numbers.
For instance, if you have a variable representing the price of an item and another for tax, you can calculate the total as:
Python also follows the standard order of operations (PEMDAS/BODMAS). When writing complex expressions, it is best practice to use parentheses to ensure the calculation happens in the order you intend.
Note: When you use the
/operator, Python always produces a float (a number with a decimal point), even if the numbers divide evenly.
When naming your variables, readability is everything. While a = 15 works, item_price = 15 tells anyone reading your code (including your future self) exactly what that number represents. This is known as using descriptive variables.
In Python, there are a few strict rules:
Age and age are different).Follow the PEP 8 style guide by using snake_case for your variables (e.g., user_email_address instead of userEmailAddress or useremailaddress). This makes your code professional and consistent with the wider Python community.
=.