Many people who are just starting to learn coding immediately jump to tutorials on creating web applications or training artificial intelligence models. His enthusiasm is indeed commendable. Who doesn't want to quickly see the results of their own work in action? But, believe me, building a weak foundation will sooner or later make the learning process stall. When you encounter a seemingly trivial error, you will spend hours just because you don't understand the basic concept.
Python is known as a very beginner-friendly programming language. The syntax is clean, close to everyday English, and doesn't force us to write lengthy code just to do simple things. However, this convenience can sometimes be a double-edged sword. Because Python does a lot of things "automatically" behind the scenes, many beginners ignore fundamental concepts like variables and data types.
Let's disassemble the engine a bit. We will discuss the very first foundations that every prospective software engineer, student, or anyone who wants to get serious about programming: how Python stores information.
Variable: Storage Box in Computer Memory
Before we can manipulate data, we have to know how to store it. This is where variables come into play. Imagine your computer memory is a giant empty warehouse. When you want to store an item, for example a book, you put it in an empty cardboard box, then you stick a name tag on the cardboard with the words "Notebook".
In the programming world, the box is the memory allocation, the name label is the "variable", and the contents of the book are the "values" or data.
In older or more restrictive programming languages such as C or Java, before you can use cardboard, you must first report to the warehouse keeper: "Hello, I need a special cardboard to store numbers, it's called cardboard_numbers!". This is called static typing.
Python is much more relaxed. He uses the dynamic typing system. You don't need to report. Just write down the name of the variable and enter the value. Python will automatically create the box and adjust its size.
Python
age = 20
name = "Budi"
learning_learning = True
It's that simple. Python sees you enter the number
20, then the variable age is immediately understood as a number store. When you enter the text "Budi", the variable name is immediately recognized as a text store.But remember, this freedom requires responsibility. Because Python doesn't lock the box type, you could accidentally change the contents of the
age variable which was previously a number to text in the next line of code.This is a source of bug that is very often experienced by fresh graduates when they have just joined a large-scale project.Why Should We Care About Python Data Types?
If Python is so good at recognizing the data we enter, why do we still bother learning data types?
The answer lies in how computers treat information. You can add two numbers, but what happens if you try to add text and numbers? The computer will be confused. Do you want to perform a mathematical operation, or do you want to combine letters?
An understanding of Python data types will save you from the error message saying
TypeError which appears very often on the terminal screen. Each data type has its own characteristics, limitations and behavior. Knowing when to use the right data type is the difference between slow running code and efficient code.Let's dissect one by one the basic data types that you use most often every day.
Integer (int): Infinite Integer
The first and most intuitive data type is
int, short for integer. Simply put, it is a whole number. No commas, no decimals. You use int when dealing with data that is discrete or can be calculated one by one. For example, the number of items in a shopping cart, a person's age, or year of birth.Python
stok_shoes = 150
production_year = 2024
minus_temperature = -5
There is an interesting secret about integers in Python that often makes software engineers from other languages jealous. In many programming languages, the size of a number is limited by the system architecture (for example the 32-bit limit is stuck at around 2.1 billion). If you pass that number, the program could crash or return an incorrect value.
In Python 3, the
int data type can hold any number, as long as your computer's RAM still fits. You can multiply trillions by trillions, and Python will calculate it quietly without complaining integer overflow. This is one of the reasons why Python is so loved by mathematicians and data scientists.Float: Decimal Numbers and the Illusion of Precision
If
int is an integer, then float (floating point) is the place to fractional or decimal numbers. You will rely heavily on this type of data when creating financial applications, calculating distances, or performing physics calculations that require a high level of accuracy.The main characteristic of
float in Python is the use of a dot (.) as a decimal separator, not a comma (,) as is standard Indonesian spelling.Python
body_weight = 65.5
phi_value = 3.14159
wallet_balance = 150000.75
It sounds simple, but
float holds the Batman trap that traps almost all computer science students in their first semester. Try opening your Python terminal and typing this simple mathematical operation: 0.1 + 0.2.Our human logic quickly answered
0.3. But Python will answer 0.30000000000000004.Why is that? Is Python stupid? No. This happens because computers basically only understand the numbers 0 and 1 (binary). Not all base 10 decimal numbers can be translated perfectly into the base 2 fraction system. As a result, there is a very small amount of rounding left at the end of the calculation.
As a practitioner, you should know that the
float data type is not suitable for systems that require absolute precision, such as core banking systems. For such cases, software engineers usually use special modules such as decimal or store monetary values in the form of int (e.g. Rp. 10,000 is saved as 1000000 cents).String (str): The Art of Text Manipulation
Any text you enter into the program—from the name of a user, the content of a tweet on social media, to a response from a server—is handled by the
str or string.To tell Python that something is text, you have to wrap it in quotes. You are free to choose to use single quotes ('...') or double quotes ("...").
Python
morning_message = "Good morning, world!"
city_name = 'Jakarta'
Why does Python provide two quotation options? This is purely for practicality. If the text you write contains single quotes, you can wrap it in double quotes, and vice versa. For example:
"Holiday Friday". Imagine if you had to use single quotes, Python would be confused about reading 'Friday off'.One of the most important things to remember about strings in Python is that they are immutable, or cannot be changed once created. When you try to combine two strings or change one of the letters in them, Python behind the scenes is actually discarding the old string box and creating a new, modified string box. If you process millions of lines of text, understanding this concept of immutability is very helpful in writing memory-efficient code.
For those of you who use Python 3.6 and above, get used to using f-string (formatted string literals).This is a magic feature that makes combining variables and text feel very natural. Just add the letter 'f' before the quotation marks, and you can enter the variable name directly inside the curly braces.
Python
name = "Rina"
age = 22
print(f"Hello, my name is {name} and I am {age} years old.")
The print results will be immediately clean without the hassle of using the plus sign (+) repeatedly.
Boolean (bool): Black and White Computer Logic
Behind all the sophistication of the applications you use, from shopping recommendation algorithms to automatic braking systems in electric cars, it all comes down to small decisions: Right or Wrong.Yes or No.
The data type
bool (Boolean) has only two possible values: True or False. Note that the first letter must be capitalized.Python
already_login = True
blocked_account = False
Boolean is the backbone of control flow such as
if and while. But what makes Python unique are concepts called truthy and falsy.Under certain conditions, Python can evaluate other data types like a Boolean. Almost all values that have "body" are considered
True. Otherwise, an "empty" value is considered False.For example, the number
0 is considered falsy. Missing strings "" are also falsy. Meanwhile, the number 1 or the text "Hello" is truthy.Python
user_name = ""
if user_name:
print("Welcome!")
else:
print("Please fill in your name.")
The above code will print "Please enter your name." because
user_name is empty, so Python sees it as False. This trick is very often used by professional programmers to make code more concise and elegant.Interesting fact for curious students: in the structure of the Python language, the data type
bool is actually a "child" (subclass) of int. True has exactly the same memory value as the number 1, and False exactly matches the number 0. So, you could technically add True + True and the result would be 2. Of course don't do this in production code if you don't want to get scolded by your teammates!None Type (None): Indicates Absence
The final concept of data type fundamentals is perhaps the most philosophical:
None.For beginners,
None is often equated with the number 0 or the empty string "". Even though they are very different. The number 0 is a value. An empty string is text that has no characters.None means absence. Something that has not been defined at all or is intentionally left blank.Imagine you are creating a registration form. Users are required to fill in their name and age, but their telephone number is optional.When the user does not enter a phone number, it makes more sense to store the variable
phone_number = None rather than phone_number = 0. A zero is an invalid number, whereas None clearly tells the system: "This user did not provide phone number information".Python
search_results = None
# ... program searches for data ...
if search_results is None:
print("Sorry, no data found.")
Using the keyword
is when comparing a variable with None is a best practice standard agreed upon by the global Python community. This is safer and more accurate than using the equal sign twice (==).Time to Put the Puzzle Together
At this point, you might be thinking, "Okay, I already know the types of boxes. So what?"
Understanding the fundamentals of data types is not the end goal. This is the language you will use to communicate with your computer every day. When you later specialize, say in the field of artificial intelligence or data science, you will process millions of rows of data every second.
You will receive random data from the internet, where numbers are often written as text (e.g.
"1500"). Since you already understand that text cannot be calculated mathematically, your first instinct is to perform a conversion (type casting) with the command int("1500") before inserting it into the prediction model you created.When your prediction algorithm produces a probability number
0.8543, you know that it is float and you can format it as a percentage easily. When a problem occurs, and the screen displays a message that the system received the value NoneType, you no longer panic. You know exactly that there is a function in the code that forgot to return a value, so the variable became empty.All high-level problem solving skills are always rooted in a clear understanding of the fundamentals. There are no instant tricks or shortcuts. Great code isn't always about complex mathematical logic; often, great code is code written by someone who truly understands how each byte of their data is treated by the machine.
Don't rush into jumping into a sophisticated framework or library before you feel completely comfortable manipulating
int, float, str, bool, and None. Open your text editor, try experimenting. Try mixing different data types, look at the error message that appears, and understand why Python is protesting. The more often you make mistakes at this stage, the sharper your instincts as a software engineer will be.
Sigit Wasis Subekti
Software Engineer & Tech Educator
Software Engineer and Tech Educator sharing insights on web development and software architecture.