Python Variables and Data Types: Your Digital Storage System
In our first article, you installed Python 3.14 and ran your very first program. Now it's time to explore the building blocks every Python program relies on: Python variables and data types. Think of a variable as a labeled box. You put information inside it, and your program can open that box again later whenever it needs that information.
What Is a Variable?
A variable is simply a name that points to a piece of data stored in your computer's memory. Instead of remembering complex memory addresses, Python lets you use human readable names:
age = 25
name = "Chrisnov"
is_learning = True
Here, age, name, and is_learning are variables. The equals sign (=) is called the assignment operator. It stores the value on the right side into the variable on the left side. Once a variable is created, you can use its name anywhere in your program instead of retyping the value.
Python's Core Data Types
Strings (Text)
Strings hold text and are wrapped in quotes, either single or double:
city = "Ruteng"
greeting = 'Selamat pagi'
full_message = f"{greeting} from {city}!"
print(full_message)
That last line uses an f-string, a modern and readable way to insert variables directly into text. Just place an f right before the opening quote, then wrap any variable name in curly braces {} inside the string.
Strings also come with useful built-in methods you can call with a dot. Try these in the REPL:
food = " Nasi Goreng "
print(food.strip()) # removes extra spaces: "Nasi Goreng"
print(food.upper()) # " NASI GORENG "
print(food.lower()) # " nasi goreng "
print(food.replace("Nasi", "Mie")) # swaps one word for another
One important detail: strings in Python are immutable. This means these methods never change the original string. They always return a brand new string, so you usually need to save the result in a variable if you want to keep it, like food = food.strip().
Numbers: Integers and Floats
temperature = 18 # integer, a whole number
rainfall_mm = 24.5 # float, a number with a decimal point
total = temperature + rainfall_mm
print(total) # 42.5
Integers are whole numbers with no decimal point. Floats have a decimal point. Python handles the math between the two types automatically, and the result becomes a float whenever a float is part of the calculation.
Beyond simple addition and subtraction, Python has a few number operators that often confuse beginners:
print(17 / 5) # 3.4 normal division, always returns a float
print(17 // 5) # 3 floor division, drops the decimal part
print(17 % 5) # 2 modulo, gives the remainder of the division
print(2 ** 3) # 8 exponent, means 2 to the power of 3
The modulo operator (%) is especially useful later on, for example to check if a number is even (number % 2 == 0).
Booleans (True or False)
is_raining = True
has_finished_tutorial = False
print(5 > 3) # True
print(5 == 3) # False
Booleans represent a simple yes or no, on or off answer. They are the foundation of decision making in code, a topic we will build on heavily in the next article. Python gives you six comparison operators to produce a boolean result: > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to), == (equal to), and != (not equal to).
None: Representing Nothing
middle_name = None # no value yet
None represents the intentional absence of a value. It is different from an empty string "" or the number 0. Programmers often use None as a starting placeholder for a variable that will get its real value later, for example a search result that has not been found yet.
Variable Naming Best Practices
- Use lowercase with underscores:
user_age, notUserAge - Be descriptive:
total_priceis much clearer thantp - Never start a name with a number:
2nd_placeis invalid and causes aSyntaxError - Avoid Python's reserved keywords as variable names, such as
print,class,if, orTrue
Dynamic Typing: Python Figures It Out
Unlike some languages, Python does not require you to declare a variable's type in advance. It automatically detects the type based on the value you assign. You can check any variable's type with the built-in type() function:
score = 95
print(type(score)) # <class 'int'>
score = "Excellent"
print(type(score)) # <class 'str'>
Notice that the same variable, score, held an integer first and then held a string. Python allows this because it checks the type of the value, not the name of the variable. This flexibility is convenient, but it also means a small typo or a reused variable name can quietly change the type your program is working with, so use clear and separate names for different kinds of data.
Type Conversion
Sometimes you need to convert a value from one type to another. A common example is reading numeric input, since input() always returns a string, even if the user types digits:
age_text = input("Enter your age: ")
age_number = int(age_text)
print(f"Next year you'll be {age_number + 1}")
The most common conversion functions are int(), float(), str(), and bool(). Be careful with int() and float(): if the text cannot actually be read as a number, Python raises a ValueError. For example, int("twenty") fails, but int("20") works fine.
Practical Project: Personal Information Collector
name = input("What's your name? ")
age = int(input("How old are you? "))
city = input("Which city do you live in? ")
likes_python = input("Are you enjoying Python so far? (yes/no) ")
is_enjoying = likes_python.lower() == "yes"
print("n--- Your Profile ---")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Enjoying Python: {is_enjoying}")
print(f"In 10 years, you'll be {age + 10} years old.")
This small program uses every data type covered today. Let's look at the two lines that do the most work:
age = int(input(...)): this line does two things at once, from the inside out. Firstinput()collects text from the user, thenint()immediately converts that text into a whole number, and the result is stored inage. Withoutint(), the lineage + 10later would crash with aTypeError, because you cannot add a number to a string.is_enjoying = likes_python.lower() == "yes": here,.lower()converts whatever the user typed to lowercase first, so"Yes","YES", and"yes"all match. The==then compares the result to the text"yes"and produces a boolean,TrueorFalse, which is saved inis_enjoying.
Common Beginner Mistakes
- Mixing strings and numbers directly:
"Age: " + 25raises aTypeError. Usestr(25)or an f-string instead. - Forgetting that
input()returns text: always convert withint()orfloat()before doing math on user input. - Converting text that is not a number:
int("twenty")raises aValueError. Only digits (and an optional minus sign or decimal point) can be converted. - Reassigning variables accidentally: reusing the same variable name for a different type of data can cause confusing bugs later in a longer program.
Try It Yourself
Practice these three short exercises in a new file called practice_vars.py before moving on:
- Create three variables for a favorite food's name, price, and whether it is spicy. Print all three using one f-string.
- Ask the user for two numbers with
input(), convert both tofloat, then print their sum, their difference, and which one is larger. - On purpose, try to run
int("hello")and read the error message Python shows you. Then fix it so the program does not crash.
Frequently Asked Questions
Can I change a variable's data type later?
Yes. Python variables are dynamically typed, so you can reassign a variable to hold a completely different type of value at any point in your program.
What's the difference between = and ==?
= assigns a value to a variable. == compares two values and returns True or False. Mixing these up is one of the most common beginner typos.
Why did my program crash with a TypeError?
This usually happens when you combine incompatible types, such as adding a string to an integer. Check that both sides of an operation use compatible types, and convert one side if needed.
What is the difference between a TypeError and a ValueError?
A TypeError means you used two types that do not work together, like a string plus an integer. A ValueError means the type is correct, but the actual content is not usable, like trying to convert the text "hello" into a number.
Do variable names matter for performance?
No. Variable names have no real effect on speed. Choose names for readability, not performance.
Ready to make your programs think and react? In our next article, we will explore Python conditional statements: if, elif, and else. You will discover how to build programs that make smart decisions based on the data you just learned to store, and you will build a grade calculator that puts these concepts into action.
Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you get stuck converting between data types, run into a confusing error message, or discover an interesting twist on the personal information collector project, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other's discoveries and solutions.
You Might Also Like
Python Dictionaries: Storing Data with Purpose
Master Python dictionaries — key-value pairs, nesting, and comprehensions — with a hands-o...
Python Lists: Your First Data Structure Adventure
Master Python lists — creation, indexing, slicing, methods, and comprehensions — with a ha...
Python Loops: Automating Repetitive Tasks Like a Pro
Master Python for loops, while loops, break, continue, and nested loops with a multiplicat...
Making Smart Decisions: Python Conditional Statements Mastered
Master Python if, elif, and else statements with comparison operators, logical operators, ...
Comments
No comments yet — be the first to start the conversation!