This guide is tailored for developers coming from C# and PHP backgrounds who want to learn Python efficiently. We’ll focus on the syntax and concepts unique to Python and how they differ from your current experience.
✅ 1. Python Syntax is Clean and Indentation-Based
if x > 5:
print("Greater")
else:
print("Smaller or Equal")
- ❌ No curly braces
{}
- ✅ Indentation determines blocks (like scope)
✅ 2. Variables: No Type Declaration
x = 10
name = "John"
is_valid = True
- ❌ No
int
,string
, orbool
required - ✅ Dynamic typing
✅ 3. Function Definitions Are Simpler
def greet(name):
return f"Hello, {name}"
- ❌ No
public
,void
,function
keywords - ✅ Uses
def
and optional type hints:
def add(a: int, b: int) -> int:
return a + b
✅ 4. String Formatting with f-Strings
name = "Alice"
print(f"Hello, {name}!")
- Replaces
string.Format()
(C#) or"Hello $name"
(PHP)
✅ 5. List, Tuple, Set, Dictionary
my_list = [1, 2, 3] # Like array
my_tuple = (1, 2, 3) # Immutable list
my_set = {1, 2, 3} # No duplicates
my_dict = {"a": 1, "b": 2} # Like associative array or Dictionary
✅ 6. None
Instead of null
value = None
- ✅ Python’s equivalent to
null
(PHP/C#)
✅ 7. Loops: for
in Collections
for item in ["a", "b", "c"]:
print(item)
- ✅ No classic
for (int i=0; ...)
- Use
range()
for index-based iteration:
for i in range(5):
print(i) # 0 to 4
✅ 8. elif
, is
, in
, not in
, with
elif
Chained else if
condition:
if x == 0:
pass
elif x == 1:
print("One")
else:
print("Other")
is
Checks identity (not just equality):
if x is None:
print("x is None")
in
/ not in
Used to check membership:
if "a" in ["a", "b", "c"]:
print("found")
with
Used for context managers (e.g., opening files):
with open("file.txt") as f:
contents = f.read()
✅ 9. pass
Statement
The pass
keyword is a placeholder for future code. It does nothing when executed, but it lets you write empty blocks that won’t throw errors.
def future_feature():
pass # To be implemented later
if condition:
pass # Reserved for logic
✅ 10. try/except
Instead of try/catch
try:
risky_function()
except Exception as e:
print(e)
✅ 11. No Semi-Colons
print("Hello")
✅ 12. List Comprehension (Powerful Python Feature)
squares = [x * x for x in range(10)]
✅ 13. Importing Libraries
import math
print(math.sqrt(16))
✅ 14. Built-in Data Types in Python
# Numbers
num = 42 # int
pi = 3.14 # float
z = 2 + 3j # complex
# Sequence
s = "hello" # str
b = b"hello" # bytes
l = [1, 2, 3] # list
t = (1, 2, 3) # tuple
r = range(5) # range
# Sets
myset = {1, 2, 3} # set
fset = frozenset([1, 2, 3])
# Mapping
mydict = {"key": "value"}
# Boolean
flag = True
# NoneType
empty = None
✅ 15. Defining Classes and Objects
class Person:
species = "Human" # Class variable
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
self.status = "active"
def greet(self):
print(f"Hello, I am {self.name}, {self.age} years old")
def is_active(self):
return self.status == "active"
p = Person("Alice", 30)
print(p.species)
print(p.name)
p.greet()
- ✅ Uses
__init__
as constructor - ✅
self
is likethis
in C#/PHP - ✅ Supports both class-level and instance-level variables
✅ 16. Inheritance and Interface-Like Behavior
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof")
# Polymorphism
animal = Dog()
animal.speak() # Woof
Python does not have a built-in interface
keyword. Instead, it uses duck typing: “If it walks like a duck and quacks like a duck…”
For strict interface enforcement:
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def authenticate(self):
pass
@abstractmethod
def process_payment(self, amount):
pass
class PayPal(PaymentGateway):
def authenticate(self):
print("Authenticating PayPal user...")
def process_payment(self, amount):
print(f"Processing ${amount} via PayPal")
class Stripe(PaymentGateway):
def authenticate(self):
print("Authenticating Stripe user...")
def process_payment(self, amount):
print(f"Processing ${amount} via Stripe")
# Example usage
gateway: PaymentGateway = Stripe()
gateway.authenticate()
gateway.process_payment(100)
- ✅
ABC
is the base class for defining abstract base classes - ✅
@abstractmethod
ensures method is overridden
🔧 Popular Python Libraries for Beginners
Library | Purpose |
---|---|
math | Basic math functions |
random | Random number generation |
datetime | Date/time manipulation |
os | Operating system commands |
sys | System-level operations |
json | JSON encode/decode |
requests | HTTP requests |
pandas | Data analysis (like Excel) |
numpy | Scientific computing (arrays) |