Python Basics
Comprehensive guide on Python Basics.
Python Basics
Overview#
This notebook covers the foundational building blocks of Python: syntax and indentation, variables and naming, the core built-in data types, operators, type conversion, strings and string formatting, and reading input from users. Everything in the rest of the core Python series builds on these fundamentals, so it's worth understanding them thoroughly before moving on to data structures, control flow, and beyond.
1. Python Syntax and Indentation#
Unlike many languages that use curly braces {} to group code, Python
uses indentation to define blocks of code. This isn't just a style
preference — it's a hard requirement of the language.
Python 3.12 (WASM)if True:
print("This is inside the if block")
print("So is this")
print("This is outside the if block")
Indentation must be consistent within a block — mixing tabs and spaces, or
using inconsistent spacing, raises an IndentationError. The standard
convention (per PEP 8, Python's official style guide) is 4 spaces per
indentation level.
Python 3.12 (WASM)# Comments start with # and are ignored by Python
# This is a single-line comment
"""
This is a multi-line string, often used as a
comment block or a docstring at the start of a
function, class, or module.
"""
2. Variables and Assignment#
Python variables don't need an explicit type declaration — a variable's type is determined by the value assigned to it, and can change.
Python 3.12 (WASM)name = "Alice" # str
age = 30 # int
height = 5.6 # float
is_student = False # bool
age = "thirty" # completely valid — age is now a string instead
Naming rules and conventions#
Python 3.12 (WASM)# Valid names
user_name = "Bob"
_private_var = 42
total2 = 100
# Invalid names (would raise SyntaxError)
# 2total = 100 # cannot start with a digit
# user-name = "Bob" # hyphens aren't allowed
# class = "test" # can't use reserved keywords
| Convention | Used for |
|---|---|
snake_case | Variables and function names (user_name, calculate_total) |
UPPER_SNAKE_CASE | Constants (MAX_RETRIES, PI) |
PascalCase | Class names (BankAccount, HttpRequest) |
_leading_underscore | Convention for "internal use" |
Multiple assignment#
Python 3.12 (WASM)x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
a = b = c = 0 # all three point to the same initial value, 0
3. Core Built-in Data Types#
Python 3.12 (WASM)# Integer — whole numbers, no size limit in Python (beyond available memory)
count = 42
big_number = 123_456_789 # underscores allowed as visual separators
# Float — decimal numbers
price = 19.99
scientific = 1.5e3 # 1500.0, scientific notation
# String — text, single or double quotes both work
greeting = "Hello"
name = 'Alice'
# Boolean — True or False (capitalized, these are keywords)
is_active = True
has_errors = False
# NoneType — represents "no value" or "nothing"
result = None
Checking a value's type#
Python 3.12 (WASM)print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(isinstance(42, int)) # True — preferred way to check types in conditions
4. Numbers and Arithmetic Operators#
Python 3.12 (WASM)a, b = 10, 3
print(a + b) # 13 addition
print(a - b) # 7 subtraction
print(a * b) # 30 multiplication
print(a / b) # 3.333... true division, always returns a float
print(a // b) # 3 floor division, rounds down to the nearest integer
print(a % b) # 1 modulo, the remainder after division
print(a ** b) # 1000 exponentiation
Order of operations#
Python follows standard mathematical precedence (PEMDAS): parentheses, exponents, multiplication/division, addition/subtraction.
Python 3.12 (WASM)result = 2 + 3 * 4 # 14, not 20 — multiplication happens first
result = (2 + 3) * 4 # 20 — parentheses override default precedence
Augmented assignment operators#
Python 3.12 (WASM)count = 0
count += 1 # equivalent to: count = count + 1
count -= 1
count *= 2
count /= 2
5. Booleans and Comparison#
Python 3.12 (WASM)print(5 > 3) # True
print(5 == 5) # True
print(5 != 3) # True
print(5 >= 5) # True
print(True and False) # False
print(True or False) # True
print(not True) # False
Python's bool is technically a subtype of int — True behaves as 1
and False as 0 in arithmetic contexts, though relying on this too
heavily can hurt readability.
Python 3.12 (WASM)print(True + True) # 2
print(sum([True, True, False, True])) # 3 — counts the True values
6. Strings in Depth#
Strings are sequences of characters, and support indexing, slicing, and a large set of built-in methods.
Python 3.12 (WASM)message = "Hello, World!"
print(message[0]) # H
print(message[-1]) # !
print(message[0:5]) # Hello
print(message[7:]) # World!
print(message[::-1]) # !dlroW ,olleH (reversed)
print(len(message)) # 13
Common string methods#
Python 3.12 (WASM)text = " Python Programming "
print(text.strip()) # "Python Programming" (removes leading/trailing whitespace)
print(text.lower()) # " python programming "
print(text.upper()) # " PYTHON PROGRAMMING "
print(text.strip().replace("Python", "Java")) # "Java Programming"
print(text.strip().split(" ")) # ['Python', 'Programming']
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
print("hello".find("ll")) # 2 (index where "ll" starts)
print(",".join(["a", "b", "c"])) # "a,b,c"
Strings are immutable — none of these methods modify the original string; they all return a new string.
Python 3.12 (WASM)original = "hello"
upper = original.upper()
print(original) # "hello" — unchanged
print(upper) # "HELLO" — a new string
String formatting#
Python 3.12 (WASM)name = "Alice"
age = 30
# f-strings (Python 3.6+) — the modern, preferred approach
print(f"My name is {name} and I am {age} years old")
print(f"Next year I'll be {age + 1}") # expressions work inside {}
print(f"Pi is approximately {3.14159:.2f}") # formatting: 2 decimal places
# .format() method (older, still common)
print("My name is {} and I am {} years old".format(name, age))
# % operator (oldest style, rarely used in new code)
print("My name is %s and I am %d years old" % (name, age))
f-strings are the recommended approach for new code — they're the most readable and the fastest at runtime.
7. Type Conversion#
Python 3.12 (WASM)# Converting between types explicitly
num_str = "42"
num_int = int(num_str) # 42 (int)
num_float = float(num_str) # 42.0 (float)
x = 3.99
y = int(x) # 3 — int() truncates toward zero, doesn't round
# Converting to string
age = 30
message = "I am " + str(age) + " years old"
# Converting to boolean — see truthiness rules in the Control Flow notebook
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("text")) # True
Handling invalid conversions#
Python 3.12 (WASM)try:
value = int("not a number")
except ValueError as e:
print(f"Conversion failed: {e}")
8. Reading Input and Printing Output#
Python 3.12 (WASM)name = input("What is your name? ") # input() always returns a string
print(f"Hello, {name}!")
age_str = input("How old are you? ")
age = int(age_str) # must convert manually if you need a number
print() in more detail#
Python 3.12 (WASM)print("a", "b", "c") # a b c (space-separated by default)
print("a", "b", "c", sep="-") # a-b-c (custom separator)
print("Hello", end=" ") # no newline after this...
print("World") # ...so this continues on the same line
print(f"Name: {name}, Age: {age}")
9. Comments and Docstrings#
Python 3.12 (WASM)# Single-line comment explaining the next line
total = price * quantity # inline comment
def calculate_discount(price, percent):
"""
Calculate the discounted price.
A docstring like this describes what a function does,
and is accessible via calculate_discount.__doc__ or help().
"""
return price * (1 - percent / 100)
Docstrings (triple-quoted strings immediately following a def, class,
or module) are more than comments — tools like help(), IDEs, and
documentation generators read them automatically.
Notes#
- Python has no separate "character" type — a single character is just a string of length 1.
- Both single (
'...') and double ("...") quotes work identically for strings; pick one convention and stay consistent, and use the other when the string itself contains a quote character. /always returns a float in Python 3, even when dividing two integers evenly (10 / 2is5.0, not5) — use//for integer (floor) division.- Variable names are case-sensitive:
age,Age, andAGEare three distinct variables. Noneis not the same as0,False, or an empty string, even though all are "falsy" —Nonespecifically represents the absence of a value.
Best Practices Checklist#
- Use 4 spaces for indentation, never tabs mixed with spaces
- Follow
snake_casefor variables/functions,PascalCasefor classes,UPPER_SNAKE_CASEfor constants - Prefer f-strings for string formatting over
.format()or% - Remember
input()always returns a string — convert explicitly when you need a number - Use
isinstance()rather thantype(x) ==for type checks - Write clear docstrings for functions, classes, and modules
- Use
//for integer division, not/followed by manual rounding - Choose descriptive variable names over short, cryptic ones