Python is one of the world’s most popular programming languages, known for its simple syntax, readability, and versatility. Whether you’re building web applications, automating tasks, analyzing data, creating AI systems, or developing APIs, Python provides the tools to get the job done.
This guide covers all major Python concepts from beginner to advanced levels in a single article.
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and released in 1991.
Python is widely used for:
- Web Development
- Artificial Intelligence
- Machine Learning
- Data Science
- Automation
- DevOps
- Cybersecurity
- Desktop Applications
- APIs
- Game Development
Example:
print("Hello World")
Variables
Variables store data.
name = "John"
age = 25
salary = 50000
Python automatically determines the variable type.
Data Types
String
name = "Python"
Integer
age = 25
Float
price = 99.99
Boolean
is_active = True
None
value = None
Operators
Arithmetic
+
-
*
/
%
**
//
Example:
a = 10
b = 3
print(a + b)
print(a ** b)
Comparison
==
!=
>
<
>=
<=
Logical
and
or
not
Input and Output
name = input("Enter your name: ")
print(name)
Type Casting
age = "25"
age = int(age)
price = float("10.5")
Strings
name = "Python"
Common Operations:
len(name)
name.upper()
name.lower()
name.replace()
name.split()
String Formatting:
name = "John"
print(f"Hello {name}")
Lists
Lists are ordered and mutable.
fruits = ["Apple", "Banana", "Orange"]
Methods:
append()
remove()
insert()
sort()
reverse()
Example:
fruits.append("Mango")
Tuples
Immutable collections.
colors = ("red", "green", "blue")
Sets
Unordered unique collections.
numbers = {1, 2, 3}
Operations:
add()
remove()
union()
intersection()
Dictionaries
Key-value pairs.
user = {
"name": "John",
"age": 25
}
Access:
print(user["name"])
Conditional Statements
if
age = 18
if age >= 18:
print("Adult")
if-else
if age >= 18:
print("Adult")
else:
print("Minor")
if-elif-else
if score > 90:
print("A")
elif score > 80:
print("B")
else:
print("C")
Loops
For Loop
for i in range(5):
print(i)
While Loop
count = 0
while count < 5:
count += 1
Break and Continue
for i in range(10):
if i == 5:
break
for i in range(10):
if i == 5:
continue
Functions
def greet():
print("Hello")
Function Parameters:
def greet(name):
print(name)
Return Values:
def add(a, b):
return a + b
Lambda Functions
square = lambda x: x * x
Scope
Local Scope
def test():
x = 10
Global Scope
x = 10
Modules
import math
print(math.sqrt(25))
Import Specific Functions:
from math import sqrt
Packages
A package is a collection of modules.
Example:
my_package/
__init__.py
utils.py
Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Error")
Multiple Exceptions:
try:
pass
except ValueError:
pass
except TypeError:
pass
Finally Block:
try:
pass
finally:
print("Always runs")
File Handling
Write:
with open("file.txt", "w") as file:
file.write("Hello")
Read:
with open("file.txt") as file:
print(file.read())
Object-Oriented Programming
Class
class Person:
pass
Object
p = Person()
Constructor
class Person:
def __init__(self, name):
self.name = name
Inheritance
class Animal:
pass
class Dog(Animal):
pass
Polymorphism
class Dog:
def speak(self):
print("Woof")
class Cat:
def speak(self):
print("Meow")
Encapsulation
class User:
def __init__(self):
self.__password = "secret"
Abstraction
from abc import ABC, abstractmethod
Iterators
nums = iter([1, 2, 3])
print(next(nums))
Generators
def count():
yield 1
yield 2
List Comprehension
squares = [x*x for x in range(5)]
Dictionary Comprehension
data = {x: x*x for x in range(5)}
Decorators
def decorator(func):
def wrapper():
print("Before")
func()
return wrapper
Usage:
@decorator
def hello():
print("Hello")
Context Managers
with open("test.txt") as file:
print(file.read())
Regular Expressions
import re
text = "Python123"
re.findall(r"\d+", text)
JSON Handling
import json
Convert Dictionary:
json.dumps(data)
Parse JSON:
json.loads(json_string)
Multithreading
from threading import Thread
thread = Thread(target=my_function)
thread.start()
Multiprocessing
from multiprocessing import Process
Async Programming
import asyncio
async def main():
print("Hello")
Run:
asyncio.run(main())
Virtual Environments
Create:
python -m venv venv
Activate:
source venv/bin/activate
Popular Python Libraries
Data Science
- NumPy
- Pandas
- Matplotlib
- Seaborn
Machine Learning
- Scikit-Learn
- TensorFlow
- PyTorch
Web Development
- Django
- Flask
- FastAPI
Automation
- Selenium
- Requests
- BeautifulSoup
Testing
import unittest
Example:
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 2, 4)
Type Hints
def greet(name: str) -> str:
return name
Dataclasses
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
Python Best Practices
- Follow PEP 8
- Use meaningful variable names
- Write reusable functions
- Handle exceptions properly
- Use virtual environments
- Write tests
- Keep code modular
- Use type hints when possible
Conclusion
Python combines simplicity with powerful capabilities, making it suitable for beginners and professional developers alike. Understanding variables, data structures, control flow, functions, object-oriented programming, file handling, concurrency, testing, and modern development practices provides a solid foundation for building anything from small automation scripts to large-scale production systems.
Master these concepts and you’ll have a complete understanding of Python’s core ecosystem and development workflow.