Skip to content
beginner Phase 1 · Python Basics

Variables & Data Types

Understand Python variables, int, float, string, bool, and type conversion.

1h
0 problems
Topic Progress 0%

Variables Fundamentals

What Are Variables?

Variables are names that reference objects in memory. Unlike C/Java, Python variables don't have fixed types.

# Variable assignment
name = 'Alice'       # str
age = 30             # int
height = 5.7         # float
is_student = True    # bool

# Multiple assignment
x, y, z = 1, 2, 3

# Same value to multiple variables
a = b = c = 0

Naming Rules

# Valid names
count = 10
_private = 'secret'
MAX_SIZE = 100
user_name = 'Alice'
# Invalid names
2count = 10      # SyntaxError: can't start with number
my-var = 'test'  # SyntaxError: can't use hyphen
class = 'A'     # SyntaxError: reserved keyword

Python is Strongly Typed

# Python won't implicitly convert types
'Age: ' + 30  # TypeError: can only concatenate str to str
'Age: ' + str(30)  # Correct: 'Age: 30'

Memory Model

a = [1, 2, 3]
b = a        # b references the SAME list
b.append(4)
print(a)     # [1, 2, 3, 4] - a is also modified!

# To create a copy
a = [1, 2, 3]
b = a.copy() # b is a new list
b.append(4)
print(a)     # [1, 2, 3] - a is unchanged

Numeric Types

Integers (int)

# Integers have unlimited precision
big_number = 10 ** 100  # No overflow!

# Different bases
binary = 0b1010    # 10 in decimal
octal = 0o17       # 15 in decimal
hexa = 0xFF        # 255 in decimal

# Underscores for readability
million = 1_000_000

Floats (float)

# Floats are IEEE 754 doubles
pi = 3.14159
speed_of_light = 3e8  # Scientific notation

# ⚠️ Floating point precision issue!
0.1 + 0.2  # 0.30000000000000004

# Solution: Use decimal module for precision
from decimal import Decimal
Decimal('0.1') + Decimal('0.2')  # Decimal('0.3')

Type Conversion

# Implicit conversion (Python does this automatically)
result = 10 + 3.14  # 13.14 (int converted to float)

# Explicit conversion
int('42')      # 42
float('3.14')  # 3.14
str(42)        # '42'

# ⚠️ Common errors
int('3.14')    # ValueError: can't convert float to int
int('hello')   # ValueError: invalid literal

Numeric Functions

abs(-5)        # 5
round(3.14159, 2)  # 3.14
pow(2, 10)     # 1024
max(1, 2, 3)   # 3
min(1, 2, 3)   # 1

import math
math.ceil(3.2)   # 4
math.floor(3.8)  # 3
math.sqrt(16)    # 4.0

Strings

String Basics

# Strings are immutable sequences of characters
name = 'Alice'
greeting = "Hello, World!"

# Multi-line strings
poem = """Roses are red,
Violets are blue,"""

# f-strings (formatted string literals)
age = 30
print(f'I am {age} years old')  # I am 30 years old
print(f'{2 + 2 = }')           # 2 + 2 = 4

String Methods

s = 'Hello, World!'

# Case methods
s.upper()      # 'HELLO, WORLD!'
s.lower()      # 'hello, world!'
s.title()     # 'Hello, World!'
s.capitalize() # 'Hello, world!'

# Search methods
s.find('World')  # 7
s.count('l')     # 3
s.startswith('He')  # True
s.endswith('!')     # True

# Transformation
s.replace('World', 'Python')  # 'Hello, Python!'
s.strip()  # Remove whitespace
s.split(', ')  # ['Hello', 'World!']

String Slicing

s = 'Hello, World!'

# s[start:stop:step]
s[0:5]     # 'Hello'
s[7:12]    # 'World'
s[::-1]    # '!dlroW ,olleH' (reversed)
s[::2]     # 'Hlo ol!' (every other char)

Common String Patterns

# Check if string contains only digits
'12345'.isdigit()  # True

# Check if string is alphanumeric
'abc123'.isalnum()  # True

# Join list of strings
', '.join(['apple', 'banana', 'cherry'])
# 'apple, banana, cherry'

# Check if all characters meet condition
'hello'.islower()  # True
'HELLO'.isupper()  # True

Booleans

Boolean Basics

is_active = True
is_admin = False

# Booleans are a subclass of int
True + True   # 2
True * 10     # 10
bool(1)       # True
bool(0)       # False

Truthy and Falsy Values

# Falsy values (evaluate to False in boolean context)
bool(None)      # False
bool(0)         # False
bool(0.0)       # False
bool('')        # False
bool([])        # False
bool({})        # False
bool(set())     # False

# Everything else is truthy
bool(1)         # True
bool(-1)        # True
bool('hello')   # True
bool([1, 2])    # True

Logical Operators

# and, or, not
True and False   # False
True or False    # True
not True         # False

# Short-circuit evaluation
# 'and' returns first falsy value or last value
0 and 'hello'    # 0
'hello' and 'world'  # 'world'

# 'or' returns first truthy value or last value
'' or 'default'  # 'default'
'hello' or 'world'  # 'hello'

Comparison Operators

# == vs is
a = [1, 2, 3]
b = [1, 2, 3]
a == b   # True (value equality)
a is b   # False (different objects)

# is should be used for singletons
x = None
x is None  # True (correct)
x == None  # True (works but not Pythonic)

Common Pitfalls

# ⚠️ Don't use '==' to check None
if x == None:  # Wrong
    pass

if x is None:  # Correct
    pass

# ⚠️ Mutable default arguments

def append_to(item, target=[]):  # Wrong!
    target.append(item)
    return target

append_to(1)  # [1]
append_to(2)  # [1, 2] - not [2]!

# Correct:
def append_to(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target