A good coding practice is to give meaningful names to a variable. While i, x, a, b, c, d, etc are valid variable names, they are not meaningful. You or someone who reviews/uses your code later can't figure out what was the purpose of such variables. Instead, give meaningful names such as current_year, temperature, temp, first_week, etc that are readable and meaningful.
For constants, we should use all upper cases to distinguish them from variables. YEAR = 2020 rather than year = 2020 is easier to realize that it is a constant. In this example, we declared YEAR as constant assuming that our code only deals with the current year. If our program uses different years, we should use a variable for the same.
Just Like Data, Variables Have Types
Now that we have learned about variables and their naming conventions, let’s learn about the different types of data.
Data comes in certain types such as strings or numbers or Booleans or dates. For example, age is a number whereas our DOB is a date. Our names are strings. Remember that:
- Strings store characters and numbers.
- Booleans store True or False.
- Numeric data types store only numbers (whole or fraction or mixed).
- Dates store date values such as today’s date or birthdays.
Memory Allocation:
The type of data is important because it decides what size of memory it will occupy. A boolean takes only 1 byte whereas numbers and strings can take many bytes depending on the value of the variable. Going back to our hotel example, not all rooms are made equal. Some have 1 bed, some have 2, some have 3, some are suites, some are executive suites, etc. It all depends on the number of guests in the group/party.
What's important to remember is that by using the correct data type, we efficiently manage memory. You don't want to allocate suites to every family or person – you will run out of suites quickly and on the other side, you will have lots of empty 1-bedrooms.
One of the best parts of Python is that we don’t have to declare the data type of variables. Consider Python a smart language for automatically figuring out data types based on values. The hotel manager is smart enough to give the right size room to guests.
age = 10 is enough to let Python allocate memory for a variable ‘age’ and assign 10 to it. Python will internally ask the RAM to allocate appropriate memory for this variable which can hold a number (10).
In other programming languages, we may need to declare int age = 10 (explicitly telling the computer to create a memory for data type integer). Also, numeric data types are of two types – integer (whole number) and double (fractions).
No comments:
Post a Comment