Python Tutorial — Learn Python Step by Step
Key takeaway: Master Python programming from scratch — variables, loops, functions, OOP, file handling, and libraries — with clear human-readable explanations and runnable code examples.
Polymorphism in Python
Polymorphism means "many forms" — the same interface works with different types. In Python, polymorphism is natural because of duck typing: if an object has the right method, it works regardless of its class.
Built-in Polymorphism
# len() works on any object with __len__
print(len("hello")) # 5 (string)
print(len([1, 2, 3])) # 3 (list)
print(len({"a": 1})) # 1 (dict)
# + operator behaves differently based on type
print(3 + 5) # 8 (addition)
print("Hello" + " World") # "Hello World" (concatenation)
print([1, 2] + [3, 4]) # [1, 2, 3, 4] (list merge)
# for loop works on any iterable
for item in [1, 2, 3]: pass # list
for char in "Python": pass # string
for key in {"a": 1, "b": 2}: pass # dict keysPolymorphism with Inheritance
# Different classes share the same method name
class Shape:
def area(self):
raise NotImplementedError
def describe(self):
return f"{type(self).__name__}: area = {self.area():.2f}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# Polymorphic function — works with ANY shape
def total_area(shapes):
return sum(s.area() for s in shapes)
shapes = [Circle(5), Rectangle(3, 4), Triangle(6, 8)]
for s in shapes:
print(s.describe())
# Circle: area = 78.54
# Rectangle: area = 12.00
# Triangle: area = 24.00
print(f"Total: {total_area(shapes):.2f}") # Total: 114.54Duck Typing
# "If it walks like a duck and quacks like a duck, it is a duck"
# Python does not check the class — it checks if the method exists
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Robot:
def speak(self):
return "Beep boop!"
# No common parent class needed — just the same method name
def make_them_speak(things):
for thing in things:
print(thing.speak())
make_them_speak([Dog(), Cat(), Robot()])
# Woof!
# Meow!
# Beep boop!
# Practical: anything with .read() works as a "file-like object"
class StringStream:
def __init__(self, text):
self.text = text
self.pos = 0
def read(self, n=-1):
if n == -1:
result = self.text[self.pos:]
self.pos = len(self.text)
else:
result = self.text[self.pos:self.pos + n]
self.pos += n
return result
# Works with any function expecting a file-like object
def process_stream(stream):
content = stream.read()
return content.upper()
print(process_stream(StringStream("hello world"))) # HELLO WORLDPolymorphism with Protocols (Python 3.8+)
# Protocols formalize duck typing with type hints
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> str: ...
class Button:
def draw(self) -> str:
return "[Button]"
class TextBox:
def draw(self) -> str:
return "[____TextBox____]"
class Checkbox:
def draw(self) -> str:
return "[x] Checkbox"
# Type-safe polymorphism — no inheritance needed
def render_ui(widgets: list[Drawable]) -> None:
for widget in widgets:
print(widget.draw())
render_ui([Button(), TextBox(), Checkbox()])
# [Button]
# [____TextBox____]
# [x] CheckboxMethod Overriding vs Overloading
# OVERRIDING: child replaces parent method (Python supports this)
class Animal:
def sound(self):
return "..."
class Dog(Animal):
def sound(self): # overrides Animal.sound()
return "Woof!"
# OVERLOADING: same method name, different parameters
# Python does NOT support traditional overloading
# Instead, use default arguments or *args
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(1, 2)) # 3
print(calc.add(1, 2, 3, 4)) # 10
# Or use singledispatch for type-based dispatch
from functools import singledispatch
@singledispatch
def format_value(value):
return str(value)
@format_value.register(int)
def _(value):
return f"{value:,}"
@format_value.register(float)
def _(value):
return f"{value:.2f}"
@format_value.register(list)
def _(value):
return f"[{len(value)} items]"
print(format_value(1000000)) # 1,000,000
print(format_value(3.14159)) # 3.14
print(format_value([1,2,3])) # [3 items]- Polymorphism lets the same code work with different types — write flexible, reusable functions.
- Python uses duck typing: the object's methods matter, not its class hierarchy.
- Use method overriding in child classes to customize behavior while keeping the same interface.
- Use
Protocol(typing module) to formalize duck typing with type hints. - Use
@singledispatchfor type-based function overloading in Python.
Python Programming Tutorial — Learn Python in a practical, step-by-step way. According to the official Python documentation, Python emphasizes code readability and simplicity, making it ideal for beginners.
Related tools: Python Online Compiler | Python Examples | JavaScript Tutorial | Java Tutorial
Python Career & Learning Guide
Python is the world's most popular programming language for beginners, data science, AI/ML, web development, and automation. This tutorial teaches Python step-by-step with clear explanations and runnable code examples in our free Python Compiler.
Why Learn Python in 2026?
- #1 Most Popular Language: Ranked first on TIOBE, Stack Overflow, and GitHub.
- AI and Data Science: The primary language for machine learning (TensorFlow, PyTorch, scikit-learn) and data analysis (Pandas, NumPy).
- Web Development: Django and Flask power scalable backends at companies like Instagram and Spotify.
- Automation & Scripting: Automate files, emails, web scraping, and data processing in minutes.
Python vs Other Languages
| Feature | Python | Java | JavaScript | C++ |
|---|---|---|---|---|
| Syntax | Very clean, readable | Verbose | Moderate | Complex |
| Typing | Dynamic, strong | Static, strong | Dynamic, weak | Static, strong |
| Best For | AI/ML, Data, Web | Enterprise, Android | Web Frontend/Backend | Systems, Games |
| Learning Time | 2–4 weeks basics | 4–6 weeks basics | 3–4 weeks basics | 8–12 weeks basics |
Frequently Asked Questions
Do I need prior programming experience to learn Python?
No! Python is specifically designed to be beginner-friendly. This tutorial starts from zero and builds up gradually.
Which Python version should I use?
Python 3.10+ is recommended. All examples in this tutorial use Python 3 syntax.
Is this Python tutorial completely free?
Yes, 100% free with no registration or sign-up required. Access all lessons and code examples anytime.