DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Variables and Basic Data Types Explained Simply

Variables are one of the first core concepts in Python. Understanding how they work makes writing and reading code much easier.

What is a variable?

A variable is like a named box that holds a value. You create a variable by giving it a name and assigning a value with the = sign.

age = 25
name = "Alex"
price = 9.99
is_student = True
Enter fullscreen mode Exit fullscreen mode

Here:

  • age holds the number 25
  • name holds the text "Alex"
  • price holds the decimal number 9.99
  • is_student holds the boolean value True

Variable names should be clear and descriptive. Use lowercase letters and underscores for multiple words (this is called snake_case in Python).

user_name = "Alex"
total_price = 100.50
Enter fullscreen mode Exit fullscreen mode

Why do data types matter?

Every value in Python has a type. The type decides what you can do with the value.

Python has four basic built-in data types that beginners use most:

  • int → whole numbers (no decimal): 5, -10, 0
  • float → numbers with decimals: 3.14, -0.5, 10.0
  • str → text (always in quotes): "hello", 'Python', ""
  • bool → only two possible values: True or False

Python is a dynamically typed language, which means the type is determined automatically when the value is assigned.

You can check the type of any value with the type() function:

print(type(age))        # <class 'int'>
print(type(name))       # <class 'str'>
print(type(price))      # <class 'float'>
print(type(is_student)) # <class 'bool'>
Enter fullscreen mode Exit fullscreen mode

Common mistake: mixing types

You cannot always combine different types directly. For example, adding a string and an integer causes an error:

score = 95
message = "Your score is " + score  # TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode Exit fullscreen mode

Fix it by converting the number to a string first:

message = "Your score is " + str(score)  # Works: "Your score is 95"
Enter fullscreen mode Exit fullscreen mode

Or use an f-string (easier and cleaner):

message = f"Your score is {score}"  # "Your score is 95"
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Use variables to store values with meaningful names.
  • The four basic types are int, float, str, and bool.
  • Use type() to check a value's type.
  • Convert types when needed to avoid errors.

This basic understanding of variables and data types is essential for writing clear and correct Python programs.

Top comments (0)