Docsity

Python Programming Notes, Study Guides, Projects, Research of Computer science

Toggle sidebar
bg1
CodeWithNishchal
Python Programming
Roadmap: Python Roadmap
Chapter 1: Introduction to Python
1.1 History of Python
1.2 What is Python?
1.3 Why Learn Python?
1.4 Main Features of Python
1.5 Python Version
1.6 How Python Code Runs
1.7 Compiler vs Interpreter Basics
Chapter 2: Environment Setup
2.1 Installing Python
2.2 Checking Python Version
2.3 Installing VS Code
2.4 Terminal and Command Line Basics
2.5 Python Interpreter
2.6 Python REPL
2.7 Creating and Running .py Files
2.8 Virtual Environments Using venv
2.9 Installing Packages Using pip
2.10 requirements.txt
Chapter 3: Python Syntax Basics
3.1 First Python Code
3.2 Python File Structure
3.3 Comments
3.4 Indentation Rules
3.5 Variables
3.6 Naming Conventions
3.7 Keywords
3.8 Print Statements
3.9 Input from Users
3.10 Basic Program Structure
3.11 Common Syntax Errors
3.12 Quick Revision Table
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Python Programming Notes and more Study Guides, Projects, Research Computer science in PDF only on Docsity!

CodeWithNishchal

Python Programming

Roadmap: Python Roadmap

Chapter 1: Introduction to Python

1.1 History of Python 1.2 What is Python? 1.3 Why Learn Python? 1.4 Main Features of Python 1.5 Python Version 1.6 How Python Code Runs 1.7 Compiler vs Interpreter Basics

Chapter 2: Environment Setup

2.1 Installing Python 2.2 Checking Python Version 2.3 Installing VS Code 2.4 Terminal and Command Line Basics 2.5 Python Interpreter 2.6 Python REPL 2.7 Creating and Running .py Files 2.8 Virtual Environments Using venv 2.9 Installing Packages Using pip 2.10 requirements.txt

Chapter 3: Python Syntax Basics

3.1 First Python Code 3.2 Python File Structure 3.3 Comments 3.4 Indentation Rules 3.5 Variables 3.6 Naming Conventions 3.7 Keywords 3.8 Print Statements 3.9 Input from Users 3.10 Basic Program Structure 3.11 Common Syntax Errors 3.12 Quick Revision Table

CodeWithNishchal

Chapter 4: Data Types

4.1 Numbers 4.1.1 int 4.1.2 float 4.1.3 complex 4.2 Strings 4.2.1 String Creation 4.2.2 String Indexing 4.2.3 String Slicing 4.2.4 String Immutability 4.3 Boolean Data Type 4.3.1 True 4.3.2 False 4.4 None Type 4.5 Type Checking with type() 4.6 Type Conversion 4.7 Mutable vs Immutable Data Types 4.8 Simple Memory Understanding 4.9 Quick Revision

Chapter 5: Operators

5.1 Arithmetic Operators 5.2 Comparison Operators 5.3 Logical Operators 5.4 Assignment Operators 5.5 Membership Operators 5.6 Identity Operators 5.7 Bitwise Operators 5.8 Operator Precedence

Chapter 6: String Operations

6.1 String Creation 6.2 String Indexing 6.3 String Slicing 6.4 String Methods 6.5 String Formatting 6.5.1 f-strings 6.5.2 format() Method 6.5.3 Old % Formatting 6.6 String Concatenation 6.7 Escape Characters 6.8 Raw Strings 6.9 String Multiplication

CodeWithNishchal

9.2.5 Named Tuples 9.2.6 Tuple vs List 9.2.7 Tuple methods 9.2.8 Tuple operations 9.2.9 Tuple packing 9.2.10 Tuple unpacking 9.2.11 Extended Tuple Unpacking 9.2.12 Named Tuples 9.2.13 Tuple vs List

9.3 Dictionaries

9.3.1 Creating Dictionaries 9.3.2 Accessing Dictionary Values 9.3.3 Updating Dictionary Values 9.3.4 Dictionary Methods 9.3.5 get() Method 9.3.6 Nested Dictionaries 9.3.7 Dictionary Comprehensions 9.3.8 Merging Dictionaries 9.3.9 Real-World Dictionary Use Cases 9.3.10 Nested Dictionaries 9.3.11 Dictionary Comprehensions 9.3.12 Merging Dictionaries 9.3.13 Copying Dictionaries 9.3.14 Dictionary vs List 9.3.15 Important Dictionary Operations

9.4 Sets

9.4.1 Creating Sets 9.4.2 Unique Values 9.4.3 Set Elements Must Be Immutable 9.4.4 Accessing Set Values 9.4.5 Checking Membership 9.4.6 Adding Set Items 9.4.7 Removing Set Items 9.4.8 Set Operations 9.4.9 Union 9.4.10 Intersection 9.4.11 Difference 9.4.12 Symmetric Difference 9.4.13 Subset, Superset, & Disjoint Sets 9.4.14 Set Methods 9.4.15 Set Operators 9.4.16 Updating Sets with Operations 9.4.17 Copying Sets 9.4.18 Frozen Sets 9.4.19 Set Comprehensions

CodeWithNishchal

9.4.20 Set Conversion 9.4.21 Set vs List vs Tuple

9.5 Collections Module

9.5.1 Counter 9.5.2 defaultdict 9.5.3 OrderedDict 9.5.4 deque 9.5.5 ChainMap

Chapter 10: Functions

10.1 What is a Function? 10.2 Defining Functions 10.3 Calling Functions 10.4 Parameters 10.5 Arguments 10.6 Positional Arguments 10.7 Return Values 10.8 Returning Multiple Values 10.9 Default Parameters 10.10 Keyword Arguments 10.11 *args 10.12 **kwargs 10.13 *args vs **kwargs 10.14 Function Parameter Order 10.15 Docstrings 10.16 Function Naming Rules

Chapter 11: Advanced Functions

11.1 Functions as First-Class Objects 11.2 Lambda Functions 11.3 map() 11.4 filter() 11.5 reduce() 11.6 Recursion 11.7 Nested Functions 11.8 Closures 11.9 Function Annotations 11.10 Higher-Order Functions

CodeWithNishchal

14.1.8 Class Variables 14.1.9 Methods vs Functions

14.2 OOP Principles

14.2.1 Encapsulation 14.2.2 Inheritance 14.2.3 Method Overriding 14.2.4 Polymorphism 14.2.5 Duck Typing 14.2.6 Abstraction 14.2.7 Composition

14.3 Special Methods

14.3.1 str 14.3.2 repr 14.3.3 len 14.3.4 getitem 14.3.5 add 14.3.6 sub 14.3.7 call 14.3.8 enter & exit 14.3.9 Context Manager Real Use 14.3.10 Operator Overloading 14.3.11 Magic Methods / Dunder Methods 14.3.12 Reverse and In-place Operator Methods 14.3.13 bool 14.3.14 iter and next 14.3.15 contains

Chapter 15: Advanced OOP in Python

15.1 @classmethod 15.2 Class Method as Alternate Constructor 15.3 @staticmethod 15.4 Instance Method vs Class Method vs Static Method 15.5 @property 15.6 @property Setter 15.7 Read-only Property 15.8 Abstract Base Classes 15.9 Why Abstract Base Classes Are Used 15.10 Mixins 15.11 Mixin vs Normal Parent Class 15.12 Metaclasses 15.13 Data Classes 15.14 Normal Class vs Data Class 15.15 Default Values in Data Classes 15.16 Mutable Defaults in Data Classes 15.17 Frozen Data Classes

CodeWithNishchal

Chapter 16: File Handling and Error Management

16.1 File Operations

16.1.1 File Handling 16.1.2 Opening Files 16.1.3 Closing Files 16.1.4 Reading Files 16.1.5 Reading Line by Line 16.1.6 Writing Files 16.1.7 Appending Files 16.1.8 File Modes 16.1.9 with Statement 16.1.10 File Object Methods 16.1.11 Binary Files 16.1.12 File Paths 16.1.13 Basic os Module 16.1.14 Basic pathlib Module 16.1.15 Encoding

16.2 Exception Handling

16.2.1 try-except 16.2.2 Catching Exception Object 16.2.3 Multiple except Blocks 16.2.4 Handling Multiple Exceptions Together 16.2.5 else in Exception Handling 16.2.6 finally 16.2.7 try-except-else-finally Flow 16.2.8 Raising Exceptions 16.2.9 Re-raising Exceptions 16.2.10 Custom Exceptions 16.2.11 Exception Hierarchy 16.2.12 Bare except Warning 16.2.13 File Handling with Exception Handling

15.3 File Formats

16.3.1 Text Files 16.3.2 CSV Files 16.3.3 csv.reader vs csv.DictReader 16.3.4 JSON Files 16.3.5 json.load() vs json.loads() 16.3.6 XML Files

CodeWithNishchal

Chapter 17: Concurrent and Asynchronous

Programming

17.1 Multithreading

17.1.1 threading Module 17.1.2 Creating Threads 17.1.3 Managing Threads 17.1.4 Race Conditions 17.1.5 Locks 17.1.6 Synchronization

17.2 Multiprocessing

17.1.1 Managing Processes 17.1.2 Process Pools 17.1.3 Memory Sharing Basics 17.1.4 Concurrent Futures

17.3 Concurrent Futures

17.3.1ThreadPoolExecutor 17.3.2 ProcessPoolExecutor 17.3.3Futures 17.3.4Async Programming

17.4 Async Programming

17.4.1 asyncio 17.4.2 async and Coroutines 17.4.3 await 17.4.4 Event Loop 17.4.5 Tasks 17.4.6 asyncio.gather() 17.4.7 Async Futures 17.4.8 Async Context Managers 17.4.9 Async vs Threading vs Multiprocessing

CodeWithNishchal

Chapter 1: Python Overview

1.1 History of Python

Python was created by Guido van Rossum. He started working on Python in the late 1980s, and Python was first released in 1991. The language was designed to be simple, readable, and easy to use. Guido wanted Python code to look clean and understandable, so programmers could focus more on solving problems instead of writing complicated syntax. Python’s name does not come from the snake. It was inspired by a British comedy show called “Monty Python’s Flying Circus.” Over time, Python became popular because it was easy for beginners and powerful for professionals. Today, Python is used in many fields like: ● Web development ● Automation ● Data science ● Artificial intelligence ● Machine learning ● Testing ● Scripting ● Backend development

1.2 What is Python?

Python is a high-level, general-purpose programming language. It is used to write programs for automation, web development, data handling, artificial intelligence, machine learning, scripting, testing, and many other tasks.Python is popular because its syntax is simple and easy to read. Example: PYTHON CODE print("Hello, World!") Output: Hello, World! Python files are saved with the .py extension. Example: main.py, app.py, hello.py

CodeWithNishchal

1.6 How Python Code Runs

Basic flow: Python Code → Python Interpreter → Output More accurate flow: Source Code → Bytecode → Python Virtual Machine → Output For now, remember: ● Python code is written in .py files. ● Python interpreter reads and runs the code. ● Python runs code from top to bottom. ● Output is shown on the screen.

1.7 Compiler vs Interpreter Basics

Before code runs, it must be translated into a form the computer can understand. There are two common translators: ● Compiler ● Interpreter

Compiler

A compiler translates the whole program before running it. Flow: Source Code → Compiler → Executable File → Run Program Examples of compiled languages: ● C ● C++ ● Go ● Rust

Interpreter

An interpreter runs code more directly. Flow: Source Code → Interpreter → Output Python is commonly called an interpreted language.

Compiler vs Interpreter

Point Compiler Interpreter Translation Translates full code before running Runs code more directly Speed Usually faster after compilation Usually slower Error checking Many errors found before running Errors can appear while running Examples C, C++, Go, Rust Python, JavaScript, Ruby

CodeWithNishchal

Chapter 2: Environment Setup

Environment setup means preparing your computer so you can write, run, and manage Python programs properly. For Python development, we mainly need:

  1. Python installed on the system
  2. A code editor like VS Code
  3. Terminal/Command Prompt basics
  4. Package manager pip
  5. Virtual environment setup using venv Basic setup flow: Install Python ↓ Check Python Version ↓ Install VS Code ↓ Write Python Code ↓ Run Python File ↓ Use venv and pip for Projects

2.1 Installing Python

The safest way is to download Python from the official Python website. The official Python downloads page provides the latest stable Python release and installers for different operating systems.

For Windows

  1. Go to the official Python website.
  2. Download the latest stable Python 3 installer.
  3. Open the installer.
  4. Select Add python.exe to PATH.
  5. Click Install Now.
  6. Wait for installation to complete.
  7. Open Command Prompt and check the version. Important: Always tick: Add python.exe to PATH This option allows you to run Python from the terminal.

CodeWithNishchal

Creating First Python File in VS Code

Create a file: hello.py Write: print("Hello CodeWithNishchal") Run the file. Output : Hello CodeWithNishchal

Ways to Run Python in VS Code

You can run Python code by:

  1. Clicking the Run button.
  2. Right-clicking and selecting Run Python File in Terminal.
  3. Opening terminal and running: python hello.py or: python3 hello.py VS Code’s Python extension provides multiple ways to run Python files, including the “Run Python File in Terminal” option. Bad file names: random.py, math.py, sys.py Better file names: number_game.py, student_report.py, calculator.py

2.4 Terminal and Command Line Basics

The terminal / command prompt is a place where we type commands to interact with the computer. Task Windows Command macOS/Linux Command Meaning Check current folder pwd pwd Shows the current folder/location in terminal List files and folders dir ls Shows files and folders inside the current folder Change folder cd folder_name cd folder_name Moves into a folder Go back one folder cd .. cd .. Moves one level back Create folder mkdir python-notes mkdir python-notes Creates a new folder named python-notes Clear terminal cls clear Clears the terminal screen

CodeWithNishchal

Running a Python File from Terminal

Suppose your file name is: app.py Run it using: python app.py or: python3 app.py Example file: PYTHON CODE print("Terminal is running Python") Output: Terminal is running Python

2.5 Python Interpreter

The Python interpreter is the program that reads and runs Python code. When we write: print("Hello") the computer does not understand this directly. The Python interpreter reads this code and executes it. Basic flow: Python Code → Python Interpreter → Output

2.6 Python REPL

REPL stands for: ● Read ● Evaluate ● Print ● Loop Python REPL allows us to run Python code line by line. It is useful for quick testing.

Opening Python REPL

Windows: python or: py macOS/Linux: python You may see something like: >>> This means Python REPL is ready.

CodeWithNishchal

Creating a Python File

Steps:

  1. Create a project folder.
  2. Open it in VS Code.
  3. Create a new file.
  4. Save it with the .py extension.
  5. Write Python code.
  6. Run the file.

Example File

File name: hello.py Code: PYTHON CODE print("Hello, Python") print("This is my first Python file") Run: python hello.py OR python3 hello.py Output: Hello, Python This is my first Python file

Python Runs File Top to Bottom

PYTHON CODE print("Start") name = "Nishchal" print("Name:", name) print("End") Output: Start Name: Nishchal End

CodeWithNishchal

Common Mistakes

● Saving file as hello.py.txt. ● Forgetting .py extension. ● Running the wrong file. ● Writing Python code in the terminal instead of a file. ● Not saving file before running. ● Giving file names with spaces. Bad: my first python file.py Good: first_python_file.py

Best Practices

● Use lowercase file names. ● Use underscores for multiple words. ● Keep one project in one folder. ● Save before running. ● Keep file names meaningful.

2.8 Virtual Environments Using venv

A virtual environment is an isolated environment for a Python project. It keeps project packages separate from other projects. Python’s official documentation says venv is the standard tool for creating virtual environments, and each virtual environment has its own independent set of installed Python packages.

Why Virtual Environment is Needed

Suppose you have two projects: Project A needs package version 1. Project B needs package version 2. If both projects use the same global Python environment, package conflicts can happen. Virtual environments solve this problem. Computer Python ↓ Project A → venv → packages for Project A Project B → venv → packages for Project B Project C → venv → packages for Project C