← Previous

Lesson 2 · Python

Variables and data types

~30 min

1. Storing Data: What is a Variable?

A variable is a symbolic name that acts as a reference or pointer to an object or value stored in your computer's memory. In Python, you create a variable by assigning a value using the assignment operator (=). Variables do not need to be declared with a specific type; Python is **dynamically typed**, meaning it determines the data type at runtime based on the value assigned.

2. Standard Variable Naming Rules

When naming variables, you must follow these rules:

  • Names must start with a letter (a-z, A-Z) or an underscore (_).
  • Names cannot start with a number (e.g., 1st_place is invalid).
  • Names can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
  • Names are case-sensitive (age, Age, and AGE are three distinct variables).
  • Python standard style (PEP 8) recommends using **snake_case** for variable names (e.g., user_age).

3. Built-in Core Data Types

Python categorizes data into distinct types. Understanding these types is crucial because they determine what operations you can perform on your data. The four most common types are:

3.1 Integer (int)

What it is: An integer is a whole number without a decimal point. It can be positive (like 42), negative (like -5), or zero.

Simple explanation: Integers represent countable quantities — the number of students in a class, a person's age, or a score on a test.

Beginner-friendly example: If you have 8 apples and get 3 more, you now have 11 apples. The numbers 8, 3, and 11 are all integers.

Python code example:

age = 18
score = 100
temperature = -5
students = 0

print(age)           # Output: 18
print(type(age))     # Output: <class 'int'>
print(score + 5)     # Output: 105 (math works!)

Why it matters: Integers are the foundation for counting, scoring, and calculations. They're fast and memory-efficient compared to other number types.

Mini practice task: Create a variable called my_age and assign it your age. Print it to the console. Then add 10 to your age and print the result.

Key takeaway: Use integers for whole numbers. Python will automatically handle integers of any size.

3.2 Float (float)

What it is: A float (floating-point) is a number with a decimal point. It can have any number of decimal places.

Simple explanation: Floats are used when you need precision beyond whole numbers — like prices, measurements, or scientific data.

Beginner-friendly example: A pizza costs $12.99, water is 3.5 liters, and a student's GPA is 3.85. These are all floats because they have decimal points.

Python code example:

price = 12.99
height = 5.9
pi = 3.14159
temperature = -2.5

print(price)         # Output: 12.99
print(type(price))   # Output: <class 'float'>
print(pi * 2)        # Output: 6.28318 (math works!)

Why it matters: Floats are essential for real-world measurements, calculations, and financial applications where decimal precision matters.

Mini practice task: Create a variable called gpa and assign it a decimal value like 3.75. Add 0.25 to it and print the result.

Key takeaway: Use floats for decimal numbers. Be aware that floats can sometimes have tiny precision issues due to how computers store decimals (but for most beginner tasks, this won't matter).

3.3 String (str)

What it is: A string is a sequence of characters (letters, numbers, symbols, spaces) enclosed in quotes.

Simple explanation: Strings represent text — names, messages, addresses, or any information you'd normally type into a form.

Beginner-friendly example: Your name "Alice", a greeting "Hello, World!", or an address "123 Main Street" are all strings.

Python code example:

name = "Alice"
greeting = "Hello, Infotris!"
email = "student@example.com"
empty_text = ""  # Empty string

print(name)           # Output: Alice
print(type(name))     # Output: <class 'str'>
print(greeting + "!")  # Output: Hello, Infotris!! (concatenation)

Why it matters: Strings are used for user names, messages, labels, and any textual data. They're one of the most frequently used data types in programs.

Mini practice task: Create a variable called city and assign it the name of your favorite city. Create another variable called country. Print both with a comma and space between them (e.g., "Paris, France").

Key takeaway: Use strings for text. You can use single quotes 'text' or double quotes "text" — both work the same way in Python.

3.4 Boolean (bool)

What it is: A boolean is a value that is either True or False. These are the only two boolean values in Python.

Simple explanation: Booleans represent yes/no or on/off states. They answer questions like "Is the light on?" or "Have you finished your homework?"

Beginner-friendly example: A door is either open (True) or closed (False). A student either passed the exam (True) or didn't (False).

Python code example:

is_student = True
is_weekend = False
has_account = True
is_verified = False

print(is_student)       # Output: True
print(type(is_student)) # Output: <class 'bool'>
print(not is_weekend)   # Output: True (opposite)

Why it matters: Booleans are essential for decision-making in programs. They form the basis of conditional statements (if/else) that we'll learn later.

Mini practice task: Create a variable called am_i_learning and set it to True. Create another called is_python_hard and set it to False. Print both.

Key takeaway: Use booleans for yes/no questions. Always capitalize True and False in Python — lowercase versions will cause errors.

3.5 Checking Types with type()

The built-in type() function tells you what data type any variable is. This is extremely useful when debugging or understanding what kind of data you're working with.

name = "Sam"
age = 18
score = 94.5
is_passing = True

print(type(name))         # Output: <class 'str'>
print(type(age))          # Output: <class 'int'>
print(type(score))        # Output: <class 'float'>
print(type(is_passing))   # Output: <class 'bool'>

# You can also check built-in functions
print(type(input))        # Output: <class 'builtin_function_or_method'>

Why use type()? Sometimes you receive data and aren't sure what type it is. The type() function instantly reveals the type, helping you understand what operations are safe to perform.

4. Collecting Inputs & Converting Types

To interact with a user, we use the input() function, which prompts the user for text. **Important**: input() always returns a string. If you need to perform calculations on a user's input, you must cast (convert) it to an integer or float using int() or float().

# Collecting string input
username = input("Enter your username: ")

# Collecting and casting numerical input
birth_year = input("Enter your birth year: ")
birth_year = int(birth_year)  # Convert string to integer

# Perform math operations
current_year = 2026
age = current_year - birth_year
print(username, "is", age, "years old.")

5. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Adding Strings and Numbers: "Age: " + 18 will fail with a TypeError. In Python, you cannot concatenate strings and numbers directly. Use f-strings: f"Age: {age}" or commas in print().
  • Forgetting to Cast input(): birth_year + 5 will crash if birth_year is directly from input() without int() conversion.
  • Using Reserved Keywords: You cannot use Python keywords (like if, else, class, or import) as variable names.
Interactive Practice

Mini Practice: Profile Builder

Write a script that prompts for a user's name, birth year, and favorite programming language. Calculate their age based on the year 2026, and print a formatted summary statement. Paste your output below to verify.

0% complete
Check when done
Quiz

Test Your Understanding

1. What is the data type of the value returned by `input("Enter price: ")`?

2. Which of the following is an INVALID variable name in Python?

3. What is the value of `result` after running: `result = 10 / 2`?

🚀 Progression

Variables and inputs are down. Now, it's time to build your first milestone project: **Project 1 — Personal Greeting Script**!