Skip to content

Latest commit

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Learn Python

Welcome to the comprehensive Python course. Python is a versatile, beginner-friendly programming language.

Table of contents

What is Python?

Python is a high-level, interpreted programming language known for its readability and versatility. Created by Guido van Rossum in 1991.

Key Characteristics

  • Easy to Learn: Simple syntax similar to English
  • Interpreted: No compilation needed
  • Dynamically Typed: No type declarations required
  • Multi-paradigm: Supports OOP, functional, and procedural programming
  • Huge Ecosystem: Extensive standard library and third-party packages

Why learn Python?

1. Beginner Friendly

Python's syntax is clean and easy to understand.

print("Hello, World!")

2. Versatile

Used in web development, data science, AI/ML, automation, and more.

3. High Demand

Python developers are in high demand across industries.

4. Strong Community

Massive ecosystem with extensive documentation and libraries.

Installation and Setup

Download

Download from python.org or use a distribution like Anaconda.

Verify Installation

python --version
python3 --version

Running Python

python script.py
python -c "print('Hello')"
python -i # Interactive mode

IDE Setup

Recommended: VS Code with Python extension, PyCharm, or Jupyter Notebook.

Hello World

print("Hello, World!")

Variables:

name="Python"version=3.12print(f"Welcome to {name}{version}!")

Variables and Data Types

Variables

name="John"# Stringage=30# Integerheight=5.9# Floatis_active=True# Booleannothing=None# None

Basic Types

# Integersx=42binary=0b1010hexadecimal=0xFF# Floatspi=3.14159scientific=2.5e6# Stringssingle='Hello'double="World"multi="""Multiplelines"""# Booleansis_valid=Trueis_empty=False

Type Checking

print(type("hello")) # <class 'str'>print(type(42)) # <class 'int'>print(type(3.14)) # <class 'float'>print(type(True)) # <class 'bool'>

Type Conversion

int("42") # 42str(42) # "42"float("3.14") # 3.14bool(1) # Truebool(0) # False

Operators

Arithmetic

a, b=10, 3print(a+b) # 13print(a-b) # 7print(a*b) # 30print(a/b) # 3.333...print(a//b) # 3 (floor division)print(a%b) # 1 (modulus)print(a**b) # 1000 (exponent)

Comparison

print(5==5) # Trueprint(5!=3) # Trueprint(5>3) # Trueprint(5>=5) # Trueprint(5<3) # Falseprint(5<=5) # True

Logical

print(TrueandFalse) # Falseprint(TrueorFalse) # Trueprint(notTrue) # False

Bitwise

print(5&3) # 1 (AND)print(5|3) # 7 (OR)print(5^3) # 6 (XOR)print(~5) # -6 (NOT)print(4<<1) # 8 (left shift)print(4>>1) # 2 (right shift)

Assignment

x=10x+=5# 15x-=3# 12x*=2# 24x/=4# 6.0

Flow Control

If/Elif/Else

score=85ifscore>=90:
print("A grade")
elifscore>=80:
print("B grade")
elifscore>=70:
print("C grade")
else:
print("Need improvement")

Ternary Operator

age=20status="adult"ifage>=18else"minor"

For Loop

# Rangeforiinrange(5):
print(i) # 0, 1, 2, 3, 4# Sequencefruits= ["apple", "banana", "cherry"]
forfruitinfruits:
print(fruit)
# With indexfori, fruitinenumerate(fruits):
print(f"{i}: {fruit}")

While Loop

count=0whilecount<5:
print(count)
count+=1

Break and Continue

foriinrange(10):
ifi==5:
break# Exit loopifi==2:
continue# Skip iterationprint(i)

Match (Python 3.10+)

status="success"matchstatus:
case"success":
print("Operation succeeded")
case"error":
print("Operation failed")
case _:
print("Unknown status")

Functions

Basic Function

defgreet(name):
returnf"Hello, {name}!"print(greet("World"))

Parameters

# Default parametersdefgreet(name, greeting="Hello"):
returnf"{greeting}, {name}!"print(greet("John")) # Hello, John!print(greet("John", "Hi")) # Hi, John!# *argsdefsum(*args):
total=0fornuminargs:
total+=numreturntotalprint(sum(1, 2, 3, 4, 5)) # 15# **kwargsdefprint_info(**kwargs):
forkey, valueinkwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=30)

Return Values

defdivide(a, b):
ifb==0:
returnNonereturna/b# Multiple returnsdefget_stats(numbers):
returnmin(numbers), max(numbers), sum(numbers)
min_val, max_val, total=get_stats([1, 2, 3, 4, 5])

Lambda Functions

square=lambdax: x**2print(square(5)) # 25add=lambdaa, b: a+bprint(add(3, 4)) # 7

Type Hints

defgreet(name: str) ->str:
returnf"Hello, {name}!"defprocess(items: list[int], multiplier: int=2) ->list[int]:
return [x*multiplierforxinitems]

Strings

Creating Strings

s1="Hello"s2='World's3="""Multi-linestring"""s4="Hello "+"World"

String Methods

s=" Hello, World! "s.upper() # " HELLO, WORLD! "s.lower() # " hello, world! "s.strip() # "Hello, World!"s.replace("World", "Python")
s.split(",") # [" Hello", " World! "]s.find("World") # 9s.count("l") # 3s.startswith(" H") # Trues.endswith("! ") # True

String Formatting

name="John"age=30# f-strings (Python 3.6+)print(f"My name is {name} and I'm {age}")
# format()print("My name is {} and I'm {}".format(name, age))
print("My name is {n} and I'm {a}".format(n=name, a=age))
# % operatorprint("My name is %s"%name)

Slicing

s="Hello World"s[0] # "H"s[0:5] # "Hello"s[6:] # "World"s[-5:] # "World"s[::2] # "HloWrd" (every 2nd char)s[::-1] # "dlroW olleH" (reversed)

Lists

Creating Lists

numbers= [1, 2, 3, 4, 5]
mixed= [1, "hello", True, 3.14]
nested= [[1, 2], [3, 4]]
empty= []

Accessing Elements

fruits= ["apple", "banana", "cherry"]
fruits[0] # "apple"fruits[-1] # "cherry"fruits[0:2] # ["apple", "banana"]

Modifying Lists

fruits= ["apple", "banana", "cherry"]
fruits.append("orange") # Add to endfruits.insert(1, "mango") # Insert at indexfruits.extend(["grape"]) # Add multiplefruits.remove("banana") # Remove by valuefruits.pop() # Remove and return lastfruits.pop(0) # Remove at indexfruits.clear() # Remove all

List Methods

numbers= [3, 1, 4, 1, 5, 9, 2, 6]
len(numbers) # 8sorted(numbers) # Returns sorted copynumbers.sort() # Sorts in placenumbers.reverse() # Reverses in placenumbers.count(1) # Count occurrencesnumbers.index(4) # Find indexnumbers.copy() # Shallow copy"cherry"infruits# Membership test

List Comprehension

# Basicsquares= [x**2forxinrange(10)]
# With conditionevens= [xforxinrange(10) ifx%2==0]
# Nestedmatrix= [[i*jforjinrange(3)] foriinrange(3)]

Tuples

Creating Tuples

point= (10, 20)
single= (42,) # Comma required for single elementmixed= (1, "hello", True)

Accessing Elements

point= (10, 20, 30)
point[0] # 10point[-1] # 30point[0:2] # (10, 20)

Tuple Methods

point= (10, 20, 30)
point.count(10) # 1point.index(20) # 1

Unpacking

point= (10, 20, 30)
x, y, z=point# Extended unpackingfirst, *middle, last= [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5

Named Tuples

fromcollectionsimportnamedtuplePoint=namedtuple('Point', ['x', 'y'])
p=Point(10, 20)
print(p.x, p.y)

Sets

Creating Sets

numbers= {1, 2, 3, 4, 5}
from_list=set([1, 2, 2, 3]) # {1, 2, 3}empty=set() # Note: {} creates dict

Set Operations

a= {1, 2, 3, 4}
b= {3, 4, 5, 6}
a.union(b) # {1, 2, 3, 4, 5, 6}a.intersection(b) # {3, 4}a.difference(b) # {1, 2}a.symmetric_difference(b) # {1, 2, 5, 6}# In-placea.update(b)
a.intersection_update(b)

Set Methods

s= {1, 2, 3}
s.add(4) # Add elements.remove(2) # Remove (raises error if missing)s.discard(10) # Remove (no error)s.pop() # Remove arbitrary elements.clear() # Remove alllen(s) # 32ins# True

Dictionaries

Creating Dictionaries

person= {"name": "John", "age": 30}
from_tuples=dict([("a", 1), ("b", 2)])
comprehension= {x: x**2forxinrange(5)}

Accessing Elements

person= {"name": "John", "age": 30}
person["name"] # "John"person.get("name") # "John"person.get("email", "not found") # Default valueperson.keys() # dict_keys(['name', 'age'])person.values() # dict_values(['John', 30])person.items() # dict_items([('name', 'John'), ...])

Modifying

person= {"name": "John", "age": 30}
person["email"] ="john@example.com"# Addperson["age"] =31# Updatedelperson["age"] # Deleteperson.pop("email") # Remove and return# Update with another dictperson.update({"city": "NYC", "age": 32})

Dictionary Methods

person= {"name": "John", "age": 30}
len(person) # 2person.clear() # Remove allperson.copy() # Shallow copyperson.setdefault("country", "USA") # Set if not exists

Dictionary Comprehension

squares= {x: x**2forxinrange(5)}
word_lengths= {word: len(word) forwordin ["apple", "banana"]}

Comprehensions

List Comprehension

squares= [x**2forxinrange(10)]
evens= [xforxinrange(20) ifx%2==0]
matrix= [[i*jforjinrange(3)] foriinrange(3)]

Set Comprehension

numbers= [1, 2, 2, 3, 3, 4, 5]
unique_squares= {x**2forxinnumbers}

Dictionary Comprehension

words= ["apple", "banana", "cherry"]
word_lengths= {word: len(word) forwordinwords}

Conditional Expressions

# If-else in comprehension
[xifx>0else-xforxin [-1, 2, -3]]
# [1, 2, 3]

Classes

Basic Class

classPerson:
def__init__(self, name, age):
self.name=nameself.age=agedefgreet(self):
returnf"Hello, I'm {self.name}"defbirthday(self):
self.age+=1person=Person("John", 30)
print(person.greet())
person.birthday()

Instance vs Class Variables

classDog:
species="Canis familiaris"# Class variabledef__init__(self, name, breed):
self.name=name# Instance variableself.breed=breedd1=Dog("Rex", "German Shepherd")
d2=Dog("Buddy", "Labrador")

Access Modifiers

classPerson:
def__init__(self, name, age):
self.name=name# Publicself._age=age# Protected (convention)self.__ssn="123-45-6789"# Private (name mangling)person=Person("John", 30)
print(person.name) # OKprint(person._age) # Works but discouragedprint(person._Person__ssn) # Name mangling

Properties

classCircle:
def__init__(self, radius):
self._radius=radius@propertydefradius(self):
returnself._radius@radius.setterdefradius(self, value):
ifvalue<0:
raiseValueError("Radius cannot be negative")
self._radius=value@propertydefarea(self):
return3.14159*self._radius**2

Class Methods and Static Methods

classMath:
@staticmethoddefadd(a, b):
returna+b@classmethoddeffrom_string(cls, s):
returncls(*map(int, s.split(",")))
Math.add(2, 3) # 5Math.from_string("1,2,3") # Math instance

Inheritance

Basic Inheritance

classAnimal:
def__init__(self, name):
self.name=namedefspeak(self):
raiseNotImplementedErrorclassDog(Animal):
defspeak(self):
returnf"{self.name} says Woof!"classCat(Animal):
defspeak(self):
returnf"{self.name} says Meow!"dog=Dog("Rex")
print(dog.speak()) # Rex says Woof!

Multiple Inheritance

classFlyable:
deffly(self):
return"Flying!"classSwimmable:
defswim(self):
return"Swimming!"classDuck(Flyable, Swimmable):
passduck=Duck()
print(duck.fly())
print(duck.swim())

Method Resolution Order (MRO)

classA:
defmethod(self):
return"A"classB(A):
defmethod(self):
return"B"classC(A):
defmethod(self):
return"C"classD(B, C):
passprint(D().method()) # B (MRO: D -> B -> C -> A)

Super Function

classAnimal:
def__init__(self, name):
self.name=nameclassDog(Animal):
def__init__(self, name, breed):
super().__init__(name)
self.breed=breed

Abstract Classes

fromabcimportABC, abstractmethodclassShape(ABC):
@abstractmethoddefarea(self):
passdefdescribe(self):
returnf"Area: {self.area()}"classCircle(Shape):
def__init__(self, radius):
self.radius=radiusdefarea(self):
return3.14159*self.radius**2

Modules

Importing

# Import entire moduleimportmathprint(math.sqrt(16))
# Import specific itemsfrommathimportsqrt, piprint(sqrt(16))
# Import with aliasimportnumpyasnpfromdatetimeimportdatetimeasdt# Import everything (not recommended)frommathimport*

Creating Modules

# my_module.pydefgreet(name):
returnf"Hello, {name}!"PI=3.14159# main.pyfrommy_moduleimportgreet, PIprint(greet("World"))

Module Search Path

importsysprint(sys.path)

Packages

Structure

my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py

init.py

# Expose package contentsfrom .module1importfunction1from .module2importfunction2__all__= ["function1", "function2"]

Relative Imports

# From subpackage/module3.pyfrom . importmodule1# Same packagefrom .. importmodule2# Parent package

File Handling

Reading Files

# Read entire filewithopen("file.txt", "r") asf:
content=f.read()
# Read lineswithopen("file.txt", "r") asf:
lines=f.readlines()
# orforlineinf:
print(line)
# Read all lines as listwithopen("file.txt", "r") asf:
lines=f.read().splitlines()

Writing Files

# Write (overwrites)withopen("output.txt", "w") asf:
f.write("Hello, World!")
# Appendwithopen("output.txt", "a") asf:
f.write("\nNew line")
# Write multiple lineswithopen("output.txt", "w") asf:
f.writelines(["line1\n", "line2\n"])

JSON Files

importjson# Write JSONdata= {"name": "John", "age": 30}
withopen("data.json", "w") asf:
json.dump(data, f, indent=2)
# Read JSONwithopen("data.json", "r") asf:
data=json.load(f)

Exception Handling

Basic Try/Except

try:
result=10/0exceptZeroDivisionError:
print("Cannot divide by zero!")
exceptExceptionase:
print(f"Error: {e}")
else:
print("No errors occurred")
finally:
print("Always executes")

Raising Exceptions

defvalidate_age(age):
ifage<0:
raiseValueError("Age cannot be negative")
returnagetry:
validate_age(-5)
exceptValueErrorase:
print(e)

Custom Exceptions

classValidationError(Exception):
def__init__(self, message, field):
super().__init__(message)
self.field=fieldraiseValidationError("Invalid input", "email")

Exception Hierarchy

BaseException
├── SystemExit
├── KeyboardInterrupt
└── Exception
├── ValueError
├── TypeError
├── KeyError
└── ...

Decorators

Basic Decorator

defmy_decorator(func):
defwrapper(*args, **kwargs):
print("Before function")
result=func(*args, **kwargs)
print("After function")
returnresultreturnwrapper@my_decoratordefsay_hello(name):
print(f"Hello, {name}!")
say_hello("World")

Decorator with Arguments

defrepeat(times):
defdecorator(func):
defwrapper(*args, **kwargs):
for_inrange(times):
result=func(*args, **kwargs)
returnresultreturnwrapperreturndecorator@repeat(3)defgreet():
print("Hello!")
greet() # Prints "Hello!" 3 times

Class Decorators

classCountCalls:
def__init__(self, func):
self.func=funcself.count=0def__call__(self, *args, **kwargs):
self.count+=1print(f"Called {self.count} times")
returnself.func(*args, **kwargs)
@CountCallsdefsay_hello():
print("Hello!")

Built-in Decorators

classMyClass:
@propertydefvalue(self):
returnself._value@staticmethoddefstatic_method():
print("Static method")
@classmethoddefclass_method(cls):
print("Class method")

Generators

Basic Generator

defcount_up_to(n):
count=1whilecount<=n:
yieldcountcount+=1fornumincount_up_to(5):
print(num) # 1, 2, 3, 4, 5

Generator Expression

# Like list comprehension but lazysquares= (x**2forxinrange(10))
forsqinsquares:
print(sq)

Generator Methods

defmy_gen():
yield1yield2yield3gen=my_gen()
print(next(gen)) # 1print(next(gen)) # 2print(next(gen)) # 3# print(next(gen)) # StopIteration

Infinite Generator

deffibonacci():
a, b=0, 1whileTrue:
yieldaa, b=b, a+bfib=fibonacci()
print([next(fib) for_inrange(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Context Managers

with Statement

withopen("file.txt", "r") asf:
content=f.read()
# File automatically closedwithopen("output.txt", "w") asf:
f.write("Hello")
# File automatically closed

Custom Context Manager

classFileManager:
def__init__(self, filename, mode):
self.filename=filenameself.mode=modeself.file=Nonedef__enter__(self):
self.file=open(self.filename, self.mode)
returnself.filedef__exit__(self, exc_type, exc_val, exc_tb):
ifself.file:
self.file.close()
returnFalse# Don't suppress exceptionswithFileManager("test.txt", "w") asf:
f.write("Hello!")

contextlib

fromcontextlibimportcontextmanager@contextmanagerdeftimer():
importtimestart=time.time()
yieldprint(f"Took {time.time() -start:.2f}s")
withtimer():
# code to timesum(range(1000000))

suppress

fromcontextlibimportsuppresswithsuppress(FileNotFoundError):
os.remove("nonexistent.txt")

Lambdas

Basic Syntax

square=lambdax: x**2print(square(5)) # 25add=lambdaa, b: a+bprint(add(3, 4)) # 7

With Built-in Functions

# mapnumbers= [1, 2, 3, 4, 5]
squares=list(map(lambdax: x**2, numbers))
# filterevens=list(filter(lambdax: x%2==0, numbers))
# reducefromfunctoolsimportreducetotal=reduce(lambdaa, b: a+b, numbers)
# sorteddata= [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]
sorted_data=sorted(data, key=lambdax: x["age"])
# max/minpeople= [("John", 30), ("Jane", 25)]
oldest=max(people, key=lambdax: x[1])

Closure

defmake_multiplier(n):
returnlambdax: x*ndouble=make_multiplier(2)
triple=make_multiplier(3)
print(double(5)) # 10print(triple(5)) # 15

Testing

unittest

importunittestclassTestMath(unittest.TestCase):
deftest_add(self):
self.assertEqual(1+1, 2)
deftest_divide(self):
withself.assertRaises(ZeroDivisionError):
1/0if__name__=="__main__":
unittest.main()

pytest

pip install pytest
# test_math.pydefadd(a, b):
returna+bdeftest_add():
assertadd(1, 1) ==2deftest_add_negative():
assertadd(-1, -1) ==-2
pytest test_math.py
pytest -v # Verbose
pytest -k "test_add"# Run specific tests

Assertions

assertx==5, "x should be 5"assertlist(map(lambdax: x**2, [1,2,3])) == [1, 4, 9]

Virtual Environments

venv

# Create
python -m venv myenv
# Activatesource myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows# Deactivate
deactivate
# Install packages
pip install requests
# Freeze requirements
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txt

pip

pip install package
pip install package==1.2.3
pip install "package>=1.0"
pip uninstall package
pip list
pip show package

poetry (optional)

pip install poetry
poetry init
poetry add requests
poetry install
poetry run python script.py

Common Libraries

requests

importrequestsresponse=requests.get("https://api.example.com/data")
data=response.json()
print(data)

json

importjson# Parse JSON stringdata=json.loads('{"name": "John"}')
# Convert to JSON strings=json.dumps({"name": "John"}, indent=2)

datetime

fromdatetimeimportdatetime, timedeltanow=datetime.now()
future=now+timedelta(days=7)
print(now.strftime("%Y-%m-%d %H:%M:%S"))

os

importosos.getcwd() # Current directoryos.listdir(".") # List filesos.mkdir("new_dir") # Create directoryos.remove("file.txt") # Delete fileos.path.exists("file.txt")

re

importrepattern=r"\d{3}-\d{4}"text="Call 123-4567"match=re.search(pattern, text)
ifmatch:
print(match.group())

Next Steps

Now that you know Python fundamentals:

  • Learn a web framework (Django, Flask, FastAPI)
  • Explore data science (pandas, numpy, matplotlib)
  • Learn machine learning (scikit-learn, TensorFlow)
  • Build APIs and web services
  • Practice with real projects

References

About

A comprehensive Python course.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors