Python Basics — A Practical Introduction to Python 3
Everything you need to start coding in Python — on one page. Variables, data types, operators, strings, lists, conditions, loops, and functions with practical examples. No fluff, just code you can run immediately.
⚡ Quick Reference
🐍 Python 3.12+
💻 Run Immediately
This is your Python cheat sheet in article form. Every concept has a code example you can copy and run. Bookmark this page — you'll come back to it often during your first month of learning Python.
Variables & Data Types
# No type declaration needed
name = "Rahul" # str
age = 20 # int
height = 5.8 # float
is_student = True # bool
# Check type
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
# Type conversion
num = int("42") # str → int
text = str(100) # int → str
decimal = float("3.14") # str → float
Strings
name = "Python"
# Methods
print(name.upper()) # PYTHON
print(name.lower()) # python
print(name[0]) # P (indexing)
print(name[1:4]) # yth (slicing)
print(len(name)) # 6
print(name.replace("P","J")) # Jython
# f-strings (formatting)
age = 20
print(f"I am {age} years old")
print(f"Next year: {age + 1}")
Lists
fruits = ["Mango", "Apple", "Banana"]
print(fruits[0]) # Mango
print(fruits[-1]) # Banana
fruits.append("Grapes") # Add item
fruits.remove("Apple") # Remove item
print(len(fruits)) # 3
# List comprehension
squares = [x**2 for x in range(1,6)]
print(squares) # [1, 4, 9, 16, 25]
If / Else
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# One-liner
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
Loops
# For loop
for i in range(1, 6):
print(i) # 1 2 3 4 5
# Loop through list
for fruit in ["Mango", "Apple"]:
print(fruit)
# While loop
count = 0
while count < 3:
print(count)
count += 1 # 0 1 2
# Print 1 to 10
print(*range(1, 11))
Functions
def greet(name):
return f"Hello, {name}!"
print(greet("Rahul")) # Hello, Rahul!
# Default parameter
def add(a, b=10):
return a + b
print(add(5)) # 15
print(add(5, 20)) # 25
# Lambda
square = lambda x: x**2
print(square(4)) # 16
Dictionaries
student = {
"name": "Rahul",
"age": 20,
"marks": 85
}
print(student["name"]) # Rahul
student["city"] = "Pune" # Add key
# Loop
for key, val in student.items():
print(f"{key}: {val}")
File Handling
# Write
with open("data.txt", "w") as f:
f.write("Hello Python!")
# Read
with open("data.txt", "r") as f:
content = f.read()
print(content) # Hello Python!