Aller au contenu principal

01.1 - Variables, Data Types & Literals

Theory 25 min Beginner

What is a Variable?

A variable is a named reference to a value stored in memory. In Python, you never declare a type — you simply assign a value.

name = "Alice"      # str
age = 30 # int
height = 1.75 # float
is_student = True # bool
nothing = None # NoneType

Python uses dynamic typing: the type of a variable is determined by the value it holds, not by a declaration.

x = 10        # x is int
x = "hello" # now x is str — valid in Python!
x = [1, 2, 3] # now x is list

Python's Built-in Data Types


Numeric Types

Integer (int)

Integers are whole numbers — no size limit in Python 3.

a = 42
b = -7
c = 1_000_000 # underscores improve readability
big = 10 ** 100 # Python handles arbitrarily large integers

print(type(a)) # <class 'int'>

Float (float)

Floats represent real numbers (64-bit IEEE 754).

pi = 3.14159
temperature = -2.5
scientific = 1.5e-3 # 0.0015

print(type(pi)) # <class 'float'>

⚠️ Floating-point precision warning:

0.1 + 0.2
# 0.30000000000000004 — NOT 0.3!

# Use round() or decimal module for financial calculations
round(0.1 + 0.2, 2) # 0.3

Complex (complex)

z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0

String Type (str)

Strings are immutable sequences of Unicode characters.

s1 = "Hello, World!"     # double quotes
s2 = 'Python is fun' # single quotes — equivalent
s3 = """Multi-line
string spanning
multiple lines""" # triple quotes

# String length
len("Hello") # 5

# Access characters (0-indexed)
s = "Python"
s[0] # 'P'
s[-1] # 'n' (negative index = from end)
s[1:4] # 'yth' (slice)

String Methods

MethodExampleResult
.upper()"hello".upper()"HELLO"
.lower()"HELLO".lower()"hello"
.strip()" hi ".strip()"hi"
.split()"a,b,c".split(",")["a","b","c"]
.join()",".join(["a","b","c"])"a,b,c"
.replace()"cat".replace("c","b")"bat"
.startswith()"hello".startswith("he")True
.find()"hello".find("ll")2

Boolean Type (bool)

Booleans have only two values: True and False.

is_active = True
is_deleted = False

# Booleans are subclass of int
True == 1 # True
False == 0 # True
True + True # 2

Truthy and Falsy Values

Every Python object has a boolean value:

Falsy (evaluates to False)Truthy (evaluates to True)
FalseTrue
0, 0.0, 0jAny non-zero number
"" (empty string)Any non-empty string
[], (), {}, set()Any non-empty collection
NoneAny object
bool("")      # False
bool("hi") # True
bool(0) # False
bool([]) # False
bool([0]) # True (list is non-empty!)

None Type

None is Python's null value. It represents "no value" or "missing".

result = None
print(type(None)) # <class 'NoneType'>

# Check for None with `is`, not `==`
if result is None:
print("No result yet")

Type Conversion (Casting)

FunctionConverts toExample
int()Integerint("42")42
float()Floatfloat("3.14")3.14
str()Stringstr(100)"100"
bool()Booleanbool(0)False
list()Listlist("abc")["a","b","c"]
# Common pattern: input() always returns str
age = int(input("Your age: "))
price = float(input("Price: "))

Checking Types

x = 42
type(x) # <class 'int'>
isinstance(x, int) # True
isinstance(x, (int, float)) # True — checks multiple types

Variable Naming Rules (PEP 8)

RuleExample
Lowercase with underscoresuser_name, total_price
Constants in UPPER_CASEMAX_SIZE = 100
Classes in PascalCaseclass BankAccount:
Private variables with _ prefix_internal_count
Avoid single letters (except loops)Use index not i where meaningful
# Good
user_age = 25
MAX_RETRIES = 3

# Bad
A = 25 # unclear
UserAge = 25 # PascalCase is for classes

Key Vocabulary

TermDefinition
VariableA named reference to a value in memory
Dynamic typingType is determined at runtime, not at declaration
LiteralA fixed value written directly in code (42, "hello", True)
ImmutableCannot be changed after creation (str, int, tuple)
NonePython's null value — represents absence of a value
CastingConverting a value from one type to another (int("42"))
Truthy/FalsyWhether a value evaluates to True or False in a boolean context
isinstance()Function to check if an object is of a given type

Summary

  • Python has 5 core scalar types: int, float, str, bool, NoneType
  • Variables are dynamically typed — no declaration needed
  • Strings are immutable sequences with rich methods
  • Every object is truthy or falsy — key for conditions
  • Use isinstance() to check types, is to compare with None
  • Follow PEP 8: snake_case for variables, UPPER_CASE for constants