0% found this document useful (0 votes)
2 views22 pages

Python Complete Guide

This document is a comprehensive guide to Python, covering core language concepts, essential functions, and detailed instructions for building a desktop/mobile app and a website. It includes sections on Python fundamentals, control flow, data structures, functions, error handling, and object-oriented programming. The guide serves as both a personal learning resource and a project-planning reference for developers.

Uploaded by

princekporvi71
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Python Complete Guide

This document is a comprehensive guide to Python, covering core language concepts, essential functions, and detailed instructions for building a desktop/mobile app and a website. It includes sections on Python fundamentals, control flow, data structures, functions, error handling, and object-oriented programming. The guide serves as both a personal learning resource and a project-planning reference for developers.

Uploaded by

princekporvi71
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

A Complete Practical Guide

Core language, essential functions, and two full step-by-step build projects: a real desktop/mobile app and a
real website — both made with Python.

Prepared as a personal learning and project-planning reference.

Python: A Complete Practical Guide Page 1 of 22


Table of Contents
1. Introduction to Python
2. Setting Up Python
3. Python Fundamentals (syntax, variables, data types, operators)
4. Control Flow (if/else, loops)
5. Data Structures (lists, tuples, dicts, sets)
6. Functions in Python — In Depth
7. Essential Built-In Functions (reference tables)
8. Modules, Packages & the Standard Library
9. Object-Oriented Programming Basics
10. Error Handling & File I/O
11. Step-by-Step: Building a Real App With Python
12. Step-by-Step: Building a Real Website With Python
13. Taking Either Project From 'Working' to 'Legit'
14. Quick-Reference Cheat Sheet

Python: A Complete Practical Guide Page 2 of 22


1. Introduction to Python
Python is a general-purpose, high-level programming language known for readable syntax and a massive
ecosystem of libraries. It is used for web development, automation/scripting, data analysis, machine learning,
desktop apps, and increasingly for mobile apps.

Why people choose Python for real projects:


• Readable syntax — close to plain English, faster to learn and maintain.
• Huge ecosystem — Flask/Django for web, Kivy/BeeWare for apps, Pandas/NumPy for data.
• Cross-platform — the same code runs on Windows, macOS, and Linux.
• Strong community — almost any problem has already been solved and documented.
• Great for both prototypes and production systems (Instagram, Spotify, and Dropbox all use Python in
production).

Python: A Complete Practical Guide Page 3 of 22


2. Setting Up Python
1 Download Python from [Link]/downloads (get the latest 3.x version).
2 During install on Windows, check 'Add Python to PATH'.
3 Verify the install by opening a terminal and running:
python --version
pip --version

Recommended editor: VS Code (free) with the official Python extension. For quick experiments, use the built-in
IDLE or Jupyter notebooks.

Virtual environments (use these for every real project):


A virtual environment keeps each project's libraries isolated so projects don't conflict with each other.
python -m venv venv # create environment
venv\Scripts\activate # activate on Windows
source venv/bin/activate # activate on macOS/Linux
pip install <package_name> # install packages inside it
deactivate # leave the environment

Python: A Complete Practical Guide Page 4 of 22


3. Python Fundamentals
Variables & Data Types
Python is dynamically typed — you don't declare a type, Python infers it.
name = "Alex" # str
age = 27 # int
price = 19.99 # float
is_active = True # bool
skills = ["Py", "SQL"] # list
profile = {"age": 27} # dict

Core Data Types


Function What it does Example

str Text data, immutable sequence of "hello"


characters

int Whole numbers 42

float Decimal numbers 3.14

bool True / False True

list Ordered, changeable collection [1, 2, 3]

tuple Ordered, unchangeable collection (1, 2, 3)

dict Key-value pairs {"a": 1}

set Unordered, unique values {1, 2, 3}

NoneType Represents 'no value' None

Operators
Function What it does Example

+ - * / Arithmetic operators 5 + 2 -> 7

// % ** Floor division, modulo, exponent 7 // 2 -> 3

== != > < Comparison, returns bool 5 == 5 -> True

and or not Logical operators True and False -> False

in not in Membership test 'a' in 'cat' -> True

+= -= *= Shorthand assignment x += 1

Python: A Complete Practical Guide Page 5 of 22


4. Control Flow
If / Elif / Else
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

Loops
# for loop
for i in range(5):
print(i)

# while loop
count = 0
while count < 5:
print(count)
count += 1

# loop control
for i in range(10):
if i == 3:
continue # skip this iteration
if i == 7:
break # stop the loop entirely
print(i)

Python: A Complete Practical Guide Page 6 of 22


5. Data Structures
Lists
fruits = ["apple", "banana"]
[Link]("cherry") # add item
[Link]("banana") # remove item
fruits[0] # access by index -> 'apple'
fruits[-1] # last item -> 'cherry'
[Link]() # sort in place
squares = [x**2 for x in range(5)] # list comprehension

Dictionaries
user = {"name": "Alex", "age": 27}
user["email"] = "alex@[Link]" # add/update key
[Link]("age") # safe access -> 27
for key, value in [Link]():
print(key, value)

Tuples & Sets


coords = (10, 20) # tuple: fixed, cannot change
unique_ids = {1, 2, 2, 3} # set: {1, 2, 3} — duplicates auto-removed

Python: A Complete Practical Guide Page 7 of 22


6. Functions in Python — In Depth
A function is a reusable, named block of code. Functions are the single most important tool for keeping a real
project organized, testable, and free of repeated code.

Basic Function Definition


def greet(name):
"""Return a greeting for the given name."""
return f"Hello, {name}!"

print(greet("Alex")) # Hello, Alex!

Default & Keyword Arguments


def create_user(name, role="member", active=True):
return {"name": name, "role": role, "active": active}

create_user("Alex")
create_user("Sam", role="admin")

*args and **kwargs (flexible arguments)


def total(*numbers): # collects extra positional args into a tuple
return sum(numbers)

total(1, 2, 3, 4) # -> 10

def build_profile(**details): # collects extra keyword args into a dict


return details

build_profile(name="Alex", age=27) # -> {'name': 'Alex', 'age': 27}

Return Values
def divide(a, b):
if b == 0:
return None, "Cannot divide by zero"
return a / b, None

result, error = divide(10, 2)

Lambda (anonymous) Functions


Small, single-expression functions, often used inline with functions like sorted() or map().
square = lambda x: x ** 2
square(5) # -> 25

users = [{"name": "Sam", "age": 31}, {"name": "Alex", "age": 27}]


[Link](key=lambda u: u["age"]) # sort by age

Scope: Local vs Global

Python: A Complete Practical Guide Page 8 of 22


count = 0 # global variable

def increment():
global count
count += 1 # modifies the global variable

increment()

■ Avoid global where possible in real projects — pass values in and return values out instead. It keeps functions
predictable and easy to test.

Decorators (functions that wrap other functions)


Common in real frameworks — Flask uses decorators to turn a function into a web route, for example.
def log_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper

@log_call
def add(a, b):
return a + b

add(2, 3) # prints 'Calling add', then returns 5

Recursive Functions
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)

factorial(5) # -> 120

Python: A Complete Practical Guide Page 9 of 22


7. Essential Built-In Functions
These come with Python — no import needed.

General Purpose
Function What it does Example

print() Display output to the console print('hi')

len() Number of items in a sequence len([1,2,3]) -> 3

type() Show the data type of a value type(5) -> int

input() Get text typed by the user name = input('Name: ')

range() Generate a sequence of numbers range(0, 10)

isinstance() Check if a value is a given type isinstance(5, int) -> True

id() Unique memory identifier of an object id(x)

help() Show documentation for an object help(str)

Type Conversion
Function What it does Example

int() Convert to integer int('5') -> 5

float() Convert to decimal number float('3.14') -> 3.14

str() Convert to text/string str(5) -> '5'

list() Convert to a list list('abc') -> ['a','b','c']

dict() Build a dictionary dict(a=1, b=2)

bool() Convert to True/False bool(0) -> False

Math & Numbers


Function What it does Example

sum() Add up all items in a sequence sum([1,2,3]) -> 6

min() / max() Smallest / largest value max([4,9,2]) -> 9

round() Round a number round(3.14159, 2) -> 3.14

Python: A Complete Practical Guide Page 10 of 22


Function What it does Example

abs() Absolute value abs(-7) -> 7

pow() Power (a to the b) pow(2, 3) -> 8

Working With Sequences


Function What it does Example

sorted() Return a new sorted list sorted([3,1,2]) -> [1,2,3]

reversed() Reverse the order list(reversed([1,2,3]))

enumerate() Get index + value while looping for i, v in enumerate(list)

zip() Pair up items from multiple lists zip([1,2],['a','b'])

map() Apply a function to every item map(str, [1,2,3])

filter() Keep only items that pass a test filter(lambda x: x>2,


[1,2,3])

any() / all() True if any/all items are truthy any([False, True]) -> True

Python: A Complete Practical Guide Page 11 of 22


8. Modules, Packages & the Standard Library
A module is a single .py file. A package is a folder of modules. Python ships with a large standard library, and
pip installs anything beyond that.
import math
[Link](16) # -> 4.0

from datetime import datetime


[Link]()

import random
[Link](["heads", "tails"])

# your own module


# file: [Link]
def double(x):
return x * 2

# file: [Link]
import helpers
[Link](5)

Frequently used standard-library modules: os, sys, json, datetime, random, re (regex), math,
collections, pathlib.

Installing third-party packages:


pip install requests
pip install flask
pip freeze > [Link]

Python: A Complete Practical Guide Page 12 of 22


9. Object-Oriented Programming Basics
Classes bundle data and behavior together — the backbone of most real applications and frameworks.
class User:
def __init__(self, name, email):
[Link] = name
[Link] = email

def greet(self):
return f"Hi, I'm {[Link]}"

class AdminUser(User): # inheritance


def delete_post(self, post_id):
return f"Post {post_id} deleted"

u = User("Alex", "alex@[Link]")
print([Link]())

Python: A Complete Practical Guide Page 13 of 22


10. Error Handling & File I/O
Try / Except
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This always runs")

Reading & Writing Files


with open("[Link]", "w") as f:
[Link]("Hello file!")

with open("[Link]", "r") as f:


content = [Link]()

import json
with open("[Link]", "w") as f:
[Link]({"key": "value"}, f)

■ The with statement automatically closes the file for you, even if an error happens — always prefer it over
open()/close().

Python: A Complete Practical Guide Page 14 of 22


11. Step-by-Step: Building a Real App With Python
"App" can mean a desktop app or a mobile app. This walkthrough covers both paths so you can pick the one
that fits your project, then converge on packaging and distribution.

Choosing your path


Function What it does Example

Desktop app Runs on Windows/macOS/Linux Tkinter (built-in), PyQt6 /


PySide6, Kivy

Mobile app Runs on Android/iOS Kivy + Buildozer, or BeeWare

Cross-platform One codebase, many platforms Kivy or Flet


hybrid

■ Recommendation for a first real project: build a desktop app with PyQt6 (professional look, huge community) or a
lightweight app with Flet (Python-only, compiles to web/desktop/mobile from one codebase).

STEP 1 Plan the app

Before writing code, write down: (a) what problem it solves, (b) the 3-5 core screens/features, (c) what data it
needs to store. Keep the first version (MVP) small.

STEP 2 Set up the project

mkdir my_app && cd my_app


python -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install PyQt6

STEP 3 Build the main window

# [Link]
import sys
from [Link] import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton

class MainWindow(QWidget):
def __init__(self):
super().__init__()
[Link]("My App")
[Link](100, 100, 400, 250)

layout = QVBoxLayout()
[Link] = QLabel("Welcome!")
button = QPushButton("Click me")
[Link](self.on_click)

Python: A Complete Practical Guide Page 15 of 22


[Link]([Link])
[Link](button)
[Link](layout)

def on_click(self):
[Link]("Button clicked!")

app = QApplication([Link])
window = MainWindow()
[Link]()
[Link]([Link]())

STEP 4 Add real functionality

Wire your core feature into the UI. Store data with SQLite (built into Python) for anything that needs to persist
between runs.
import sqlite3

conn = [Link]("app_data.db")
cursor = [Link]()
[Link]("""CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER DEFAULT 0)""")
[Link]()

[Link]("INSERT INTO tasks (title) VALUES (?)", ("Buy milk",))


[Link]()

STEP 5 Test it

Write simple tests for your core logic (not the UI) using Python's built-in unittest or the popular pytest
package.
# test_logic.py
def add_task(tasks, title):
[Link]({"title": title, "done": False})
return tasks

def test_add_task():
result = add_task([], "Buy milk")
assert result == [{"title": "Buy milk", "done": False}]

STEP 6 Package it into a real installable app

Turn your script into a standalone .exe / .app / .apk so people can run it without installing Python themselves.

Function What it does Example

Windows/macOS/L Standalone executable pyinstaller --onefile


inux desktop --windowed [Link]

Python: A Complete Practical Guide Page 16 of 22


Function What it does Example

Android/iOS Mobile install package buildozer android debug


(from Kivy)

Flet apps Web, desktop, or mobile build flet build apk / flet build
macos

STEP 7 Distribute it

• Desktop: share the .exe/.app directly, or list it on [Link], GitHub Releases, or your own site.
• Android: publish the .apk/.aab to the Google Play Console (one-time developer fee).
• iOS: requires an Apple Developer account and building on macOS with Xcode (BeeWare/Kivy support this,
but it's the most involved path).
• Add auto-update checks and a version number once you have real users.

Python: A Complete Practical Guide Page 17 of 22


12. Step-by-Step: Building a Real Website With Python
This path uses Flask (lightweight, great for learning and small-to-medium sites) with notes on when to graduate
to Django (batteries-included, better for larger sites with many features like auth, admin panels, and
permissions out of the box).

STEP 1 Plan the site

List your pages (Home, About, Login, Dashboard, etc.), what data each page needs, and which pages require a
logged-in user.

STEP 2 Set up the project

mkdir my_site && cd my_site


python -m venv venv
source venv/bin/activate
pip install flask flask-sqlalchemy flask-login python-dotenv

STEP 3 Create the basic Flask app

# [Link]
from flask import Flask, render_template, request, redirect

app = Flask(__name__)

@[Link]("/")
def home():
return render_template("[Link]")

@[Link]("/contact", methods=["GET", "POST"])


def contact():
if [Link] == "POST":
name = [Link]["name"]
return f"Thanks, {name}!"
return render_template("[Link]")

if __name__ == "__main__":
[Link](debug=True)

Project layout:
my_site/
[Link]
templates/
[Link]
[Link]
static/
[Link]
[Link]

STEP 4 Add a database (store real data)

Python: A Complete Practical Guide Page 18 of 22


# [Link]
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User([Link]):
id = [Link]([Link], primary_key=True)
email = [Link]([Link](120), unique=True, nullable=False)
password_hash = [Link]([Link](200), nullable=False)

STEP 5 Add user login (authentication)

Use flask-login for sessions and [Link] to hash passwords — never store plain-text
passwords.
from [Link] import generate_password_hash, check_password_hash

hashed = generate_password_hash("user_password")
check_password_hash(hashed, "user_password") # -> True

STEP 6 Style the site

Use Jinja2 templating (built into Flask) to reuse layout across pages, and plain CSS or a framework like
Bootstrap/Tailwind for styling.
&lt;!-- templates/[Link] --&gt;
{% extends "[Link]" %}
{% block content %}
&lt;h1&gt;Welcome, {{ user_name }}&lt;/h1&gt;
{% endblock %}

STEP 7 Test locally

python [Link]
# visit [Link] in your browser

STEP 8 Deploy it to the real internet

Function What it does Example

Beginner-friend Free/cheap tiers, simple deploy Render, Railway,


ly PythonAnywhere

Production-grad More control, scales further AWS, DigitalOcean, [Link]


e

Server setup Production web server + app server Nginx + Gunicorn in front of
Flask

pip install gunicorn


gunicorn app:app # production-ready server instead of [Link]()

Python: A Complete Practical Guide Page 19 of 22


STEP 9 Make it a real, legit domain

• Buy a domain (Namecheap, Google Domains, Cloudflare) and point its DNS to your host.
• Enable HTTPS — most hosts (Render, Railway, Cloudflare) issue free SSL certificates automatically.
• Set environment variables for secrets (API keys, DB passwords) — never hard-code them.

Python: A Complete Practical Guide Page 20 of 22


13. Taking Either Project From 'Working' to 'Legit'
These are the details that separate a script from a real product:

• Version control: use Git and push to GitHub from day one (git init, git add, git commit, git push).
• [Link]: run pip freeze > [Link] so anyone (or any server) can install the
exact same dependencies.
• Environment variables: keep secrets out of your code using a .env file and the python-dotenv
package.
• Error logging: use Python's built-in logging module instead of scattered print() statements.
• Testing: a small pytest suite catches bugs before your users do.
• README: document what the project does and how to run it — for others, and for future you.
• License: add an open-source license (MIT is common) if you plan to share the code publicly.
• Backups: for any app storing user data, schedule regular database backups.

Python: A Complete Practical Guide Page 21 of 22


14. Quick-Reference Cheat Sheet
Function What it does Example

Create venv Isolate project dependencies python -m venv venv

Install package Add a library pip install <name>

Run a script Execute a .py file python [Link]

Define function Reusable code block def name(params): ...

List Build a list in one line [x*2 for x in range(5)]


comprehension

Open a file Read/write safely with open('[Link]') as f: ...

Run tests Check your logic works pytest

Freeze Save exact package versions pip freeze >


dependencies [Link]

Run Flask dev Preview a website locally python [Link]


server

Build desktop Package a Python app pyinstaller --onefile


exe [Link]

End of guide. Build small, test often, and ship an MVP before adding extra features — that's the fastest real
path from idea to a legit, working project.

Python: A Complete Practical Guide Page 22 of 22

You might also like