1. Variables
Now, let's examine how to create variables and assign them to values of different data types.
Let us use a real-world phone book example to understand what a variable is. In a phonebook, we save the numbers of people based on their names.
For example, We can save a number under the name "Mom" with her phone number and quickly retrieve it later by searching for "Mom."
Variables in Python work very similarly: they are words we use to point to and store specific values we can retrieve anytime.
Whole numbers in Python are classified as integers, while numbers with decimals are classified as floats.
Let’s create a variable called customer_age and assign a value of 25, representing an age in years. As a whole number, customer_age is classified as integer.
Variables help us avoid typing the same information repeatedly. We can reuse and reset a variable anywhere in our script.
In our example, If a customer grows older, we can change their age from 25 to 26.
We can also set variables to decimals. Let's create a new variable, account_balance, and set it to 58.50. In Python, numbers with decimals like account_balance are classified as floats.
Whenever we create a variable, Python assigns it the correct data type behind the scenes based on our set value. Both the integer and float classifications are data types that exist in Python.
Python is a programming language that does not require us to specify a variable's data type explicitly, and it also provides a built-in "type()" function to check what data type a variable is.
We can pass any variable into the type() function and then use the print() function to display the result. The type() function will typically return a text that starts with the less than symbol (<) and the word class followed by the data type, ending with the greater than symbol(>).
Our example shows that the customer_age variable has the data type int, which is a short form for integer.
We also see that the account_balance variable has the data type float.
Now that we know how to work with number-based variables, let’s look at the Boolean data type in Python. A Boolean can only have two possible values: True or False. If we create a variable is_active_customer with the value True and use the type() function to check its type, we see that "bool" is displayed, denoting that our variable is a boolean.
Note that `True` and `False` must be capitalized; otherwise, they will not work in Python!
Now, it is your turn to work with variables.
2. Let's practice!