Python for Beginners: A Complete Getting Started Guide
Learn Python from scratch — variables, data types, control flow, functions, lists, dictionaries, file I/O, and your first real project. No prior programming experience needed.
DevToolsHub Team28 min read1,007 words
Why Python?
Python is the most popular programming language in the world (as of 2024-2026). It's used for:
- Web development (Django, Flask, FastAPI)
- Data science & AI (pandas, NumPy, TensorFlow, PyTorch)
- Automation & scripting (file processing, web scraping)
- DevOps (Ansible, infrastructure tools)
- Education (most universities teach Python first)
Python's syntax is clean and readable — it reads almost like English.
Your First Python Program
print("Hello, World!")
That's it. No boilerplate, no semicolons, no curly braces.
Variables and Data Types
Python is dynamically typed — you don't declare types:
# Strings
name = "Alice"
greeting = 'Hello'
multiline = """This is
a multiline string"""
# Numbers
age = 30 # int
height = 5.9 # float
big_number = 1_000_000 # underscores for readability
# Booleans
is_active = True
is_admin = False
# None (like null in other languages)
result = None
Type Checking
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type("hello") # <class 'str'>
type(True) # <class 'bool'>
type([1, 2]) # <class 'list'>
isinstance(42, int) # True
isinstance("hi", str) # True
Type Conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(0) # False
bool(1) # True
bool("") # False
bool("hello") # True
list("abc") # ["a", "b", "c"]
Strings
name = "Alice"
# String methods
name.upper() # "ALICE"
name.lower() # "alice"
name.strip() # Remove whitespace
name.replace("A", "B") # "Blice"
name.startswith("Al") # True
name.split(",") # Split into list
",".join(["a", "b"]) # "a,b"
# f-strings (formatted strings) — the modern way
age = 30
print(f"My name is {name} and I am {age} years old")
print(f"Next year I'll be {age + 1}")
print(f"Pi is approximately {3.14159:.2f}") # "3.14"
# String indexing and slicing
text = "Hello, World!"
text[0] # "H"
text[-1] # "!"
text[0:5] # "Hello"
text[7:] # "World!"
text[::-1] # "!dlroW ,olleH" (reversed)
len(text) # 13
Lists (Arrays)
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []
# Accessing elements
fruits[0] # "apple"
fruits[-1] # "cherry"
fruits[1:3] # ["banana", "cherry"]
# Modifying lists
fruits.append("date") # Add to end
fruits.insert(1, "avocado") # Insert at index
fruits.remove("banana") # Remove by value
fruits.pop() # Remove and return last
fruits.pop(0) # Remove and return at index
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
# List comprehensions — Python's superpower
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
# ["ALICE", "BOB", "CHARLIE"]
Dictionaries (Objects/Maps)
# Creating dictionaries
user = {
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"is_active": True,
}
# Accessing values
user["name"] # "Alice"
user.get("name") # "Alice"
user.get("phone", "N/A") # "N/A" (default if key missing)
# Modifying
user["age"] = 31
user["phone"] = "555-1234"
del user["is_active"]
# Iterating
for key in user:
print(f"{key}: {user[key]}")
for key, value in user.items():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Control Flow
# If/elif/else
age = 18
if age >= 21:
print("Can drink")
elif age >= 18:
print("Can vote")
else:
print("Minor")
# Ternary expression
status = "adult" if age >= 18 else "minor"
# For loops
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
for i, fruit in enumerate(["apple", "banana"]):
print(f"{i}: {fruit}")
# While loops
count = 0
while count < 5:
print(count)
count += 1
# Break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
Functions
# Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # "Hello, Alice!"
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Alice", "Hi") # "Hi, Alice!"
# Multiple return values
def get_user():
return "Alice", 30, "alice@example.com"
name, age, email = get_user()
# *args and **kwargs
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4) # 10
def create_user(**kwargs):
return kwargs
create_user(name="Alice", age=30)
# {"name": "Alice", "age": 30}
# Lambda functions
square = lambda x: x**2
square(5) # 25
# Map, filter, reduce
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
File I/O
# Writing to a file
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Reading a file
with open("output.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("output.txt", "r") as f:
for line in f:
print(line.strip())
# JSON files
import json
data = {"name": "Alice", "age": 30}
# Write JSON
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON
with open("data.json", "r") as f:
loaded = json.load(f)
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")
else:
print("Success!") # Runs if no exception
finally:
print("Always runs")
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
Next Steps
Once you're comfortable with the basics:
- Learn OOP — Classes, inheritance, methods
- Explore the standard library — os, sys, datetime, collections, itertools
- Try a web framework — Flask (simple) or Django (full-featured)
- Learn data tools — pandas, matplotlib, NumPy
- Practice — Build projects, solve coding challenges
Related Tools
- Python Formatter — Format Python code with PEP 8
- JSON Formatter — Format JSON data
- Regex Tester — Test Python regex patterns
- Hash Generator — Generate hashes (Python uses hashlib)
- Base64 Encoder — Python's base64 module
- Fake Data Generator — Generate test data for Python projects
pythonpython tutorialpython beginnerlearn pythonpython basicspython programmingpython guide