Tutorials Python Variables & Data Types
Ch 2 / 58
Python Beginner 8 min read Chapter 2 of 58

Variables & Data Types

Variables are the building blocks of every Python program — they store the data your code works with. Python's rich set of built-in data types handles everything from whole numbers and decimals to text, booleans, lists, and dictionaries. This chapter gives you a complete, hands-on mastery of all of them.

What you'll learn in this chapter
How to declare and name variables
All built-in Python data types
Dynamic typing and type() function
Type conversion (casting)
Multiple assignment & constants
Mutable vs immutable types
Advertisement

What are Variables?

A variable is a named container that stores a value in memory. You create a variable simply by assigning a value to a name using the = operator — no keyword, no type declaration needed.

In Python, variables are dynamically typed: the interpreter figures out the type from the value you assign. You can even reassign a variable to a completely different type later, which is valid Python.

Python — variables.py
# Creating variables — just assign a value
name    = "Alice"        # str
age     = 25             # int
height  = 5.6            # float
is_pro  = True           # bool

print(name, age, height, is_pro)
# Alice 25 5.6 True

# Dynamic typing — reassign to a different type
x = 10        # x is int
x = "hello"   # x is now str — valid in Python
print(type(x)) # <class 'str'>
No declaration needed Unlike Java (int x = 5;) or C++ (int x = 5;), Python requires no type keyword. Just write x = 5 and Python handles the rest.
📦
Named Storage
A label pointing to data in memory
🔄
Reassignable
Change value or type anytime
⚡
No Declaration
Just assign — Python infers type
🔍
type() Check
Use type() to inspect any variable

Variable Naming Rules

Python has strict rules for naming variables. Breaking them causes a SyntaxError. Follow the conventions below to write clean, professional code:

✅ Must start with a letter or underscore
name, _private, myVar are all valid. 1name is not.
✅ Letters, digits, underscores only
user_age, score2 are fine. Spaces, hyphens, or symbols like @ are not allowed.
✅ Case-sensitive
age, Age, and AGE are three different variables. Be consistent.
❌ Cannot be a Python keyword
Words like for, if, while, class, True, None are reserved and cannot be variable names.
Python — naming conventions
# ✅ Valid names — snake_case (recommended for variables)
user_name = "Alice"
total_score = 99
_internal = True
item2 = "laptop"

# ❌ Invalid names — cause SyntaxError
# 2user = "Bob"      ← starts with digit
# my-name = "Eve"   ← hyphen not allowed
# for = 10          ← reserved keyword

# Constants — by convention use ALL_CAPS
MAX_SPEED = 300
PI = 3.14159
Convention tip Python's official style guide (PEP 8) recommends snake_case for variable and function names (total_price) and PascalCase for class names (ShoppingCart). Constants use ALL_CAPS.

Python Built-in Data Types

Python has a rich set of built-in types grouped into categories. Every value in Python is an object with a type, attributes, and methods. Use type(x) to inspect any variable's type at runtime.

int
Integer

Whole numbers of any size — positive, negative, or zero. No decimal point. Example: age = 25

float
Decimal

Numbers with a decimal point. Stored as 64-bit IEEE 754. Example: price = 19.99

str
String

Sequence of Unicode characters enclosed in quotes. Example: name = "Alice"

bool
Boolean

Only two values: True or False. Used in conditions and comparisons.

list
Mutable

Ordered, changeable collection. Allows duplicates. Example: scores = [90, 85, 92]

tuple
Immutable

Ordered, unchangeable collection. Faster than lists. Example: coords = (10, 20)

dict
Key-Value

Collection of key-value pairs. Keys must be unique. Example: {"name":"Alice","age":25}

set
Unique

Unordered collection with no duplicates. Useful for membership testing. Example: {1, 2, 3}

Python — all basic types at a glance
# Checking types with type()
x = 42
print(type(x))           # <class 'int'>

y = 3.14
print(type(y))           # <class 'float'>

s = "hello"
print(type(s))           # <class 'str'>

b = True
print(type(b))           # <class 'bool'>

lst = [1, 2, 3]
print(type(lst))         # <class 'list'>

tup = (10, 20)
print(type(tup))         # <class 'tuple'>

d = {"name": "Alice"}
print(type(d))           # <class 'dict'>

st = {1, 2, 3}
print(type(st))          # <class 'set'>

Numeric Types — int, float & complex

Python has three numeric types: int (whole numbers), float (decimal numbers), and complex (numbers with a real and imaginary part). You'll use int and float most often.

Python — numeric types
# int — whole numbers (no size limit in Python 3)
population = 1_400_000_000   # underscores improve readability
negative   = -50
binary     = 0b1010           # binary → 10
hexa       = 0xFF             # hexadecimal → 255

# float — decimal numbers
pi     = 3.14159
sci    = 1.5e3              # scientific notation → 1500.0
tiny   = 2.5e-4             # → 0.00025

# complex — real + imaginary
z = 3 + 4j
print(z.real, z.imag)      # 3.0  4.0

# Arithmetic operators
print(10 + 3)    # 13   — addition
print(10 - 3)    # 7    — subtraction
print(10 * 3)    # 30   — multiplication
print(10 / 3)    # 3.333... — true division (always float)
print(10 // 3)   # 3    — floor division
print(10 % 3)    # 1    — modulus (remainder)
print(2 ** 8)    # 256  — exponentiation
Float precision Floating-point arithmetic can produce small rounding errors: 0.1 + 0.2 gives 0.30000000000000004. For financial calculations, use the decimal module instead.

Strings (str)

Strings are sequences of Unicode characters enclosed in single, double, or triple quotes. Python strings are immutable — you can't change a character in place, but you can create new strings with operations.

Python — strings.py
# Single, double, and triple quotes
a = 'hello'
b = "world"
c = """This is a
multi-line string"""

# String indexing and slicing
s = "Python"
print(s[0])      # P   — first character
print(s[-1])     # n   — last character
print(s[0:3])    # Pyt — slice from 0 up to (not including) 3
print(s[::-1])   # nohtyP — reverse

# Common string methods
print(s.upper())          # PYTHON
print(s.lower())          # python
print(s.replace("P","J")) # Jython
print(len(s))             # 6

# f-strings (Python 3.6+) — best practice
name  = "Alice"
score = 98.5
print(f"Hello, {name}! Your score is {score:.1f}")
# Hello, Alice! Your score is 98.5
s[i]
Access a single character by index. Negative indexes count from the end: s[-1] is the last character.
s[start:stop:step]
Slice a portion of the string. stop is exclusive. s[::-1] reverses the string.
f"...{expr}..."
F-strings embed expressions inline. Use :.2f for 2 decimal places, :, for thousands separator.
in operator
"Py" in "Python" returns True. The in keyword tests substring membership.

Booleans & None

bool has only two values: True and False. Booleans are a subclass of int — True equals 1 and False equals 0. Python also has a special value None (like null in other languages).

Python — booleans and None
# Boolean values
is_active = True
is_admin  = False

# Comparison operators return bool
print(10 > 5)    # True
print(10 == 5)   # False
print(10 != 5)   # True

# bool() — convert to boolean
print(bool(0))       # False  — zero is falsy
print(bool(""))      # False  — empty string is falsy
print(bool(42))      # True   — any non-zero number is truthy
print(bool("hi"))   # True   — non-empty string is truthy

# None — represents absence of value
result = None
print(result is None)  # True — use "is" not "==" to check None
Falsy values in Python The following evaluate to False in a boolean context: 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), () (empty tuple), None. Everything else is truthy.

Multiple Assignment

Python allows assigning multiple variables on a single line — great for swapping values without a temp variable:

Python — multiple assignment
# Assign multiple variables at once
x, y, z = 1, 2, 3
print(x, y, z)     # 1 2 3

# Assign same value to multiple variables
a = b = c = 0
print(a, b, c)     # 0 0 0

# Swap variables without a temp variable
p, q = 10, 20
p, q = q, p
print(p, q)        # 20 10
Advertisement
🐍
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Type Conversion (Casting)

Type conversion lets you convert a value from one type to another using built-in functions. Python has two kinds: implicit (done automatically) and explicit (you do it manually with casting functions).

Python — type casting
# Implicit conversion — Python promotes int to float
result = 5 + 2.0
print(result, type(result))  # 7.0 <class 'float'>

# Explicit conversion — int(), float(), str(), bool()
print(int(3.9))       # 3     — truncates, does NOT round
print(int("42"))      # 42    — string to int
print(float("3.14")) # 3.14  — string to float
print(str(100))       # "100" — int to string
print(bool(0))        # False — 0 is falsy

# Common use-case: reading user input
age_str = input("Enter your age: ")  # returns str
age_int = int(age_str)               # cast to int for math
print(f"You will be {age_int + 1} next year.")
Function Converts from Example Result
int() float, str (numeric) int("42") 42
float() int, str (numeric) float("3.14") 3.14
str() int, float, bool str(100) "100"
bool() any type bool(0) False
list() tuple, set, str list("abc") ['a','b','c']
ValueError Converting an invalid string raises a ValueError: int("hello") → ValueError: invalid literal for int(). Always validate user input before casting.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Variables are created by assignment (x = 5) — no type declaration needed. Python infers the type from the value.
  • Use snake_case for variables and functions, PascalCase for classes, and ALL_CAPS for constants (PEP 8).
  • Python's main data types: int, float, complex, str, bool, list, tuple, dict, set.
  • Use type(x) to check any variable's type at runtime.
  • Strings are immutable sequences. Use f-strings for formatting: f"Hello, {name}!"
  • Falsy values: 0, "", [], {}, (), None. Everything else is truthy.
  • Type casting: use int(), float(), str(), bool(). Always validate input before casting.
  • Swap two variables elegantly: a, b = b, a — no temporary variable needed.
⚡
Free Resource
Download our Python Cheat Sheet
Variables, data types, loops, functions, OOP — all on one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Mutable objects can be changed after creation: list, dict, and set are mutable — you can add, remove, or modify elements. Immutable objects cannot be changed: int, float, str, bool, and tuple are immutable. When you "modify" an immutable value, Python creates a new object in memory. This distinction matters for performance and when passing arguments to functions.

✓ Answer

input() always returns a str because the terminal can't know whether the user means a number or text — it only captures characters. To use the input as a number, you must explicitly cast it: age = int(input("Age: ")). Always wrap in a try/except ValueError block if the input might not be a valid number, to prevent your program from crashing on bad input.

✓ Answer

== checks value equality — whether two objects have the same value. is checks identity — whether two variables point to the exact same object in memory. Example: a = [1, 2]; b = [1, 2] — a == b is True (same values) but a is b is False (different objects). Always use is when checking for None: if x is None:

✓ Answer

int(3.9) returns 3, not 4. The int() function truncates (cuts off) the decimal part — it does not round. This means int(3.1), int(3.5), and int(3.9) all return 3. If you need rounding, use round(3.9) which returns 4, or math.floor() / math.ceil() for explicit floor/ceiling.

✓ Answer
  • 0 (int) — numeric zero represents "nothing" in mathematics, so Python treats it as False.
  • 0.0 (float) — same reasoning as integer zero.
  • "" (empty string) — an empty sequence has no content, so it's falsy.
  • [] (empty list) — an empty collection contains no elements, treated as False.
  • None — explicitly represents the absence of a value; always falsy.
MCQ 1 of 3
What does type(3.0) return in Python?
MCQ 2 of 3
Which of the following variable names is invalid in Python?
MCQ 3 of 3
What is the output of print(bool([]))?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel