This tutorial covers the core building blocks of Python: variables, data types, control flow, functions, and error handling. You'll use these in every project.
1. Variables
A variable is a name that refers to a value. In Python you assign with =:
name = "Anacodic" count = 42 rate = 3.14
You don't declare types; Python infers them. Use descriptive names and snake_case by convention.
2. Data Types
Common built-in types:
- int - integers:
0,-5,100 - float - decimals:
3.14,-0.1 - str - text:
"hello",'world' - bool -
True,False - list - ordered, mutable:
[1, 2, 3] - dict - key-value:
{"a": 1, "b": 2}
Use type(x) to inspect a value's type.
3. Control Flow
Conditionals - branch with if / elif / else:
if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C"
Loops - iterate with for or while:
for i in range(5): print(i * 2)
4. Functions
Define a function with def. Use return to send a value back:
def greet(name): return f"Hello, {name}!" result = greet("World") # "Hello, World!"
Use default arguments and type hints as you advance:
def add(a: int, b: int = 0) -> int: return a + b
5. Error Handling
Catch and handle errors with try / except:
try: value = int(user_input) except ValueError: value = 0
Raise errors with raise ValueError("message"). Use specific exception types instead of bare except.
6. Practice Questions
Test your understanding with the five questions below. Choose an answer and click Check Answer; you’ll see your score at the end.