Python Series track

Week 02 · Basic Track

Week 2 — Variables & Data Types

Explore Python's four core data types, learn how to assign variables, use type() to inspect values, and perform basic type conversions.

Basic Track3 min readFree lesson

Level: Beginner | Prerequisite: Week 1 (Environment Setup, print())

Learning Goals

  • Understand the concept of variables and assignment syntax
  • Distinguish the four basic data types (int, float, str, bool)
  • Check the type of a variable using type()
  • Perform type conversion using int(), float(), str()
  • Understand the meaning of None

1. What is a Variable

A variable is a name given to a value. It stores data in a certain location in memory and allows you to access that location using the name.

age = 20         #Store 20 in the variable called age
name = "Hong Gil-dong"  #Store a string in name
print(age)       #Print 20

= is not the mathematical 'equals' but an assignment. It means putting the value on the right into the variable on the left.

Variable Naming Rules

  • Can only use letters, numbers, and _. The first character cannot be a number.
  • Case-sensitive (age ≠ Age)
  • Cannot use reserved words like if, for
  • Convention: snake_case (user_name, total_score)

2. Basic Data Types

Type Example Description
int 10, -3, 0 Integer
float 3.14, -0.5 Float (decimal)
str "hello", 'Hello' String (both Single/Double-Quotes are possible)
bool True, False True/False (starts with a capital letter!)
NoneType None Indicates "no value"

→ Refer to examples/01_variables.py, 02_types.py.

3. Type Casting

Forces a type change. The input value is always a string, so it must be converted to a number to perform calculations.

num_str = "123"
num_int = int(num_str)
print(num_int + 7)   # 130
Function Description
int(x) Converts x to an integer
float(x) Converts x to a float
str(x) Converts x to a string
bool(x) Converts x to a boolean

Impossible conversions result in ValueError:

int("abc")     # ValueError: invalid literal for int() with base 10: 'abc'

4. type() Function

print(type(10))            # <class 'int'>
print(type(3.14))          # <class 'float'>
print(type("hi"))          # <class 'str'>
print(type(True))          # <class 'bool'>
print(type(None))          # <class 'NoneType'>

Key Examples (examples/)

File Content
01_variables.py Variable declaration and usage
02_types.py Check type with type()
03_casting.py Successful type conversion
04_casting_error.py Type conversion failure (intentional error)

⚠️ Common Mistakes

  1. Variable names starting with a number
    2nd_player = "Bob"  # SyntaxError
    

→ Change to second_player or player2.

  1. True/False in lowercase
    is_ok = true   # NameError
    

→ First letter capitalized: True, False, None.

  1. Missing quotes in a string

name = Hong Gil-dong #NameError: name 'Hong Gil-dong' is not defined

→ Should be enclosed in quotes like `name = "Hong Gil-dong"` to be a string.

4. **Integer/String mixed addition**
```python
age = 20
print("Age:" + age)   # TypeError

→ Either print("Age: " + str(age)) or f-string f"Age: {age}".

  1. Calculate input() result as is
    n = input("Number:")   #Always a string!
    print(n + 1)          # TypeError
    

→ Convert to n = int(input("Number: ")).

❓ Frequently Asked Questions (FAQ)

Q1. Is there a difference between ' (single quote) and " (double quote)? A. Functionally, they are the same. However, it is convenient to use the other type if you want to include quotes inside the string ("It's me").

Q2. Can any type be reassigned to a variable? A. Yes. Python is a dynamically typed language, so you can x = 10 and then x = "hello". However, it is not recommended for readability.

Q3. Are 0 and False the same? A. Comparing (==) returns True, but the types are different. int vs bool. Detailed equality will be studied later.

Q4. Can you put commas in numbers? (1,000,000) A. No. You can use underscores instead of commas: 1_000_000 (for readability).

📝 Exercises (exercises/)

  • exercise1.md — Age calculator
  • exercise2.md — Output 5 variables + type
  • exercise3.md — A short program that uses all four data types

Answers (solutions/)

First try to solve it yourself and refer only when stuck.

Next Week

Week 3. Operators and Input/Output — Receiving user input and arithmetic operations

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_variables.pyPython
name = "Hong Gil-dong"
age = 20
height = 175.5
is_student = True

print(name, age, height, is_student)

age = 21  #The variable can be reassigned
print("Age next year:", age)
examples/02_types.pyPython
print(type(10))         # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type("hello"))    # <class 'str'>
print(type(True))       # <class 'bool'>
print(type(None))       # <class 'NoneType'>
examples/03_casting.pyPython
num_str = "123"
num_int = int(num_str)
print(num_int + 7)             # 130

pi_str = "3.14"
pi_float = float(pi_str)
print(pi_float * 2)            # 6.28

age = 20
print("Age:" + str(age))      #Age: 20

print(int(3.9))                 #3 (rounded down to the nearest decimal)
print(bool(0), bool(1), bool("")) # False True False
examples/04_casting_error.pyPython
#Example that deliberately causes an error
#When executed, a ValueError message appears — this is normal

print("Attempting to convert 'abc' to an integer...")
try:
    int("abc")
except ValueError as e:
    print("Error occurred:", e)

print("Attempting to directly convert '1.5' to an integer...")
try:
    int("1.5")
except ValueError as e:
    print("Error occurred:", e)
    print("In this case, convert twice using float() then int():")
    print(int(float("1.5")))   # 1

Assignment

Goal

Receive the birth year from the user and output the age in full years.

Requirements

  • Define the current year as a constant in the code (e.g., CURRENT_YEAR = 2026)
  • Input birth year using input()
  • Convert the input value to an integer and calculate age in full years
  • Output the result

Input/Output Example

$ python age.py
Year of Birth: 2005
Age: 21

Grading

  • Input receiving — 30%
  • Type conversion — 30%
  • Accurate calculation and output — 40%

Assignment 2. 5 Variables + Type Output

Goal

Declare 5 variables of different data types and print their values along with their types.

Requirements

  • 5 variables (each with a different meaningful name)
  • Include at least 3 different data types (int, float, str, bool)
  • Print the value and type of each variable in one line

Input/Output Example

name = Hong Gil-dong (<class 'str'>)
age = 20 (<class 'int'>)
height = 175.5 (<class 'float'>)
is_student = True (<class 'bool'>)
country = South Korea (<class 'str'>)

Grading

  • 5 or more variables — 50%
  • At least 3 types of data — 30%
  • Output format — 20%

Assignment 3. Using All 4 Data Types

Goal

Use int, float, str, bool at least once each in a short program.

Requirements

  • Free topic (e.g., my computer specs, favorite cafe info, dog info)
  • All 4 data types appear
  • Output results neatly

Input/Output Example

$ python pet.py
[Dog Information]
Name: Choco (str)
Age: 3 years (int)
Weight: 4.2kg (float)
Neutered: True (bool)

Grading

  • Using all 4 data types — 60%
  • Meaningful output — 40%
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
CURRENT_YEAR = 2026
birth_year = int(input("Year of Birth:"))
age = CURRENT_YEAR - birth_year
print(f"Age: {age}")
solution2.pyPython
name = "Hong Gil-dong"
age = 20
height = 175.5
is_student = True
country = "Korea"

print(f"name = {name} ({type(name)})")
print(f"age = {age} ({type(age)})")
print(f"height = {height} ({type(height)})")
print(f"is_student = {is_student} ({type(is_student)})")
print(f"country = {country} ({type(country)})")
solution3.pyPython
print("[Dog Information]")
print(f"Name: {'Choco'} (str)")
print(f"Age: {3} years (int)")
print(f"Weight: {4.2} kg (float)")
print(f"Neutered: {True} (bool)")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now