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 must be understood by 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 bugs 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
stock_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. Sesuatu yang sama sekali belum didefinisikan atau sengaja dikosongkan.Bayangkan kamu sedang membuat formulir pendaftaran. Pengguna wajib mengisi nama dan umur, tapi nomor telepon sifatnya opsional. Saat pengguna tidak mengisi nomor telepon, lebih masuk akal menyimpan variabel
nomor_telepon = None daripada nomor_telepon = 0. Angka nol adalah nomor yang tidak valid, sedangkan None dengan jelas memberitahu sistem: "Pengguna ini memang tidak memberikan informasi nomor telepon".Python
hasil_pencarian = None
# ... program mencari data ...
if hasil_pencarian is None:
print("Maaf, data tidak ditemukan.")
Menggunakan kata kunci
is saat membandingkan suatu variabel dengan None adalah standar praktik terbaik (best practice) yang disepakati oleh komunitas Python global. Ini lebih aman dan akurat dibandingkan menggunakan tanda sama dengan dua kali (==).Saatnya Merangkai Puzzle
Sampai di sini, kamu mungkin berpikir, "Oke, saya sudah tahu jenis-jenis kotaknya. Lalu apa?"
Memahami fundamental tipe data bukanlah tujuan akhir. Ini adalah bahasa yang akan kamu gunakan untuk berkomunikasi dengan komputermu setiap hari. Ketika kamu nanti mengambil spesialisasi, katakanlah di bidang artificial intellegent atau ilmu data, kamu akan memproses jutaan baris data setiap detik.
Kamu akan menerima data acak dari internet, di mana angka seringkali tertulis sebagai teks (misalnya
"1500"). Karena kamu sudah paham bahwa teks tidak bisa dihitung secara matematis, insting pertamamu adalah melakukan konversi (type casting) dengan perintah int("1500") sebelum memasukkannya ke dalam model prediksi yang kamu buat.Ketika algoritma prediksimu menghasilkan angka probabilitas
0.8543, kamu tahu bahwa itu adalah float dan kamu bisa memformatnya menjadi persentase dengan mudah. Saat terjadi masalah, dan layar menampilkan pesan bahwa sistem menerima nilai NoneType, kamu tidak lagi panik. Kamu tahu persis bahwa ada fungsi di kodenya yang lupa mengembalikan nilai, sehingga variabel tersebut menjadi kosong.Semua keahlian problem solving tingkat tinggi selalu berakar pada pemahaman yang jernih tentang hal-hal fundamental. Tidak ada trik instan atau jalan pintas. Kode yang hebat tidak selalu tentang logika matematika yang kompleks; seringkali, kode yang hebat adalah kode yang ditulis oleh seseorang yang benar-benar memahami bagaimana setiap byte datanya diperlakukan oleh mesin.
Jangan terburu-buru melompat ke framework atau library canggih sebelum kamu merasa benar-benar nyaman memanipulasi
int, float, str, bool, dan None. Buka text editor-mu, cobalah bereksperimen. Coba campurkan tipe data yang berbeda, lihat pesan error yang muncul, dan pahami mengapa Python memprotes hal tersebut. Semakin sering kamu berbuat salah di tahap ini, semakin tajam instingmu sebagai software engineer nantinya.
Sigit Wasis Subekti
Software Engineer & Tech Educator
Software Engineer and Tech Educator sharing insights on web development and software architecture.