Master Python Basics – Your First Step to Becoming a Programmer
If you're seeing this book's cover or link pointing to Amazon.com (USA marketplace)
Table of Contents
Python Basics – Made Easy, Fun & Practical
Introduction to Python 1.1 What is Python and Why Learn It in 2025? 1.2 Who Uses Python Today? (Real-world Examples) 1.3 Python vs Other Languages – Quick Comparison 1.4 How to Install Python (Windows, Mac, Linux) 1.5 Setting Up VS Code or PyCharm (Recommended Editors) 1.6 Write & Run Your First Python Program: Hello World
Basic Building Blocks 2.1 Variables and Data Types 2.2 Numbers (int, float, complex) 2.3 Strings – Everything You Need to Know 2.4 Boolean (True / False) 2.5 type() function and Type Conversion 2.6 Comments in Python (# and multiline)
Operators in Python 3.1 Arithmetic Operators (+, -, , /, //, %, *) 3.2 Comparison Operators (==, !=, >, <, >=, <=) 3.3 Logical Operators (and, or, not) 3.4 Assignment Operators (=, +=, -=, *=, etc.) 3.5 Membership Operators (in, not in) 3.6 Identity Operators (is, is not)
Taking Input & Showing Output 4.1 print() – All Important Ways to Use It 4.2 input() – Getting Data from User 4.3 Formatting Output (f-strings, .format(), % operator)
Control Flow (Decision Making) 5.1 if, elif, else Statements 5.2 Nested if-else 5.3 One-line if / Ternary Operator 5.4 pass Statement
Loops in Python 6.1 while Loop (with else) 6.2 for Loop (with range(), strings, lists) 6.3 break, continue, and pass Keywords 6.4 Nested Loops 6.5 Infinite Loops – How to Avoid Them
Lists – Most Important Data Structure 7.1 Creating Lists 7.2 Accessing, Slicing & Negative Indexing 7.3 List Methods (append, extend, insert, remove, pop, clear, sort, reverse, etc.) 7.4 List Comprehension (Super Powerful & Short) 7.5 Looping through Lists
Tuples 8.1 What is a Tuple? Why Use It? 8.2 Tuple vs List – Quick Comparison 8.3 Tuple Methods (count, index) 8.4 Packing & Unpacking
Strings (Deep Dive) 9.1 String Slicing & Negative Indexing 9.2 String Methods (upper, lower, strip, replace, split, join, find, etc.) 9.3 Check if String Contains Something 9.4 Escape Characters 9.5 Multiline Strings
Dictionaries 10.1 Creating & Accessing Dictionaries 10.2 Adding, Updating, Removing Items 10.3 Dictionary Methods (keys, values, items, get, update, pop, etc.) 10.4 Looping through Dictionaries 10.5 Nested Dictionaries
Sets 11.1 What is a Set? Unique Values 11.2 Set Operations (union, intersection, difference, symmetric difference) 11.3 Set Methods (add, remove, discard, update, etc.)
Functions – Reusing Code 12.1 Defining & Calling Functions 12.2 Parameters vs Arguments 12.3 Default Arguments 12.4 Keyword Arguments 12.5 args and *kwargs 12.6 Return Statement 12.7 Scope – Local vs Global Variables 12.8 Lambda Functions (Anonymous Functions)
Modules & How to Use Them 13.1 What is a Module? 13.2 import, from … import, as keyword 13.3 Popular Built-in Modules (math, random, datetime) 13.4 Create Your Own Module
Mini Projects & Practice Ideas 14.1 Calculator Program 14.2 Guess the Number Game 14.3 To-Do List (using lists/dictionaries) 14.4 Password Generator 14.5 Rock Paper Scissors Game
Best Practices & Next Steps 15.1 Naming Conventions (PEP 8) 15.2 Writing Readable Code 15.3 Common Beginner Mistakes to Avoid 15.4 What to Learn After Basics (file handling, OOP, libraries…) 15.5 Recommended Resources & Practice Platforms
1. Introduction to Python
1.1 What is Python and Why Learn It in 2026?
Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. It is famous for its simple and readable syntax — code looks almost like plain English!
Key Features of Python:
Easy to read and write (great for beginners)
Free and open-source
Cross-platform (works on Windows, Mac, Linux)
Huge community and thousands of free libraries
Interpreted → No need to compile; run code instantly
Why Learn Python in 2026? In 2026, Python remains the #1 most popular programming language (top in IEEE Spectrum, Stack Overflow Survey, TIOBE Index). Here's why it's still the best choice:
AI & Machine Learning Boom → Libraries like TensorFlow, PyTorch, scikit-learn make Python the king of AI.
Data Science & Analytics → Tools like Pandas, NumPy, Matplotlib are industry standard.
Automation & Scripting → Automate boring tasks (files, emails, web scraping) easily.
Web Development → Frameworks like Django and FastAPI power fast, modern websites.
High Job Demand → Millions of jobs in AI, data, backend, automation — Python skills pay well.
Beginner-Friendly → Learn programming concepts fast without complex rules.
Future-Proof → Used everywhere — from startups to NASA, Google, Netflix.
Example: A simple line in Python does what takes many lines in other languages!
Python
# Print your name — that's it! name = "Anshuman" print(f"Hello, {name}! Welcome to Python in 2026 🎉")
Output:
text
Hello, Anshuman! Welcome to Python in 2026 🎉
Python = Fast learning + Huge opportunities in 2026!
1.2 Who Uses Python Today? (Real-world Examples)
Python powers some of the biggest companies and products in the world:
Google → YouTube search, machine learning systems, internal tools.
Meta (Facebook/Instagram) → Backend services, AI pipelines, recommendation engines.
Netflix → Recommendation algorithms, data analysis for what you watch next.
Spotify → Music recommendations, data pipelines.
Dropbox → File syncing and storage backend.
Reddit → Core platform features and moderation tools.
Uber → Data analysis and routing algorithms.
NASA → Scientific computing and data processing.
Many more → Amazon (parts), JPMorgan Chase (finance AI), Instagram, Quora.
Industries Using Python Heavily in 2026:
Artificial Intelligence / Machine Learning
Data Science & Analytics
Web Development
Automation & DevOps
Finance (FinTech)
Healthcare
Education Tech (EdTech)
Python is everywhere — learning it opens doors to top tech jobs!
1.3 Python vs Other Languages – Quick Comparison
Here’s a simple table comparing Python with popular languages (2026 perspective):
FeaturePythonJavaScriptJavaC++Ease of LearningVery Easy (beginner-friendly)Easy-MediumMedium (strict rules)Hard (complex)TypingDynamic (no need to declare types)DynamicStaticStaticSpeedSlower (good for most tasks)Fast (in browsers/Node)FastVery FastMain UseAI, Data, Web, AutomationWeb (front + back)Enterprise, AndroidGames, Systems, Speed-criticalSyntaxClean & readableFlexible, curly bracesVerboseComplex pointersJob Demand 2026#1 (AI/Data boom)Very High (web)High (enterprise)High (performance)Best For Beginners?Yes – Start here!Yes (if web interest)NoNo
Quick Tip: Start with Python → learn concepts fast → later switch to others if needed (many pros know 2–3 languages).
1.4 How to Install Python (Windows, Mac, Linux)
Step-by-step (2026 current method):
Go to official website: https://www.python.org/downloads/
Download the latest version (Python 3.13 or 3.14+ in 2026)
Windows:
Run the .exe installer
Important: Check "Add python.exe to PATH"
Click "Install Now"
Mac:
Run the .pkg installer
Or use Homebrew: brew install python
Linux (Ubuntu/Debian):
Open terminal and run:
Bash
sudo apt update sudo apt install python3 python3-pip
Verify installation (open Command Prompt / Terminal):
Bash
python --version # or python3 --version
You should see something like: Python 3.14.0
1.5 Setting Up VS Code or PyCharm (Recommended Editors)
Option 1: Visual Studio Code (VS Code) – Free & Lightweight (Most Recommended for Beginners)
Download from: https://code.visualstudio.com/
Install → Open VS Code
Install Python extension:
Click Extensions icon (Ctrl+Shift+X)
Search "Python" by Microsoft → Install
Create a file → Save as hello.py
Select interpreter: Ctrl+Shift+P → "Python: Select Interpreter" → Choose your Python version
Run code: Right-click → "Run Python File in Terminal"
Option 2: PyCharm Community Edition – Free & Powerful
Download from: https://www.jetbrains.com/pycharm/download/
Install → Create New Project
It auto-detects Python or lets you create a virtual environment
Great for bigger projects later
Tip: Start with VS Code — it's fast, free, and used by most developers in 2026.
1.6 Write & Run Your First Python Program: Hello World
Step 1: Open VS Code (or any editor) Step 2: Create a new file → name it hello.py (must end with .py)
Code (copy-paste this):
Python
# This is a comment – Python ignores it # Our first program! print("Hello, World!") # Basic output print("Welcome to Python 2026!") # Another line name = "Anshuman" # Store your name print("Hi", name, "! Let's code!") # Using variables
Step 3: Save the file Step 4: Run it:
In VS Code: Right-click → "Run Python File in Terminal"
Or in terminal/command prompt:
Bash
Expected Output:
text
Hello, World! Welcome to Python 2026! Hi Anshuman ! Let's code!
Congratulations! 🎉 You just wrote and ran your first Python program.
Next Step: Try changing the text inside print() and run again — see the magic!
2. Basic Building Blocks
These are the foundational elements of Python programming. Once you understand them, you can start building real programs!
2.1 Variables and Data Types
Variables are like containers that store data (values). In Python, you don't need to declare the type — it's dynamically typed (Python figures it out automatically).
Syntax to create a variable:
Python
variable_name = value
Rules for variable names:
Start with letter (a-z, A-Z) or underscore (_)
Can contain letters, numbers, underscore
Case-sensitive (age ≠ Age)
Cannot be Python keywords (like if, for, print)
Examples:
Python
# Valid variables name = "Anshuman" # string age = 25 # integer height = 5.9 # float is_student = True # boolean _marks = 98 # starts with underscore (ok) # Invalid examples (will give error) # 1age = 20 # starts with number # my-name = "Test" # has hyphen
Main Data Types in Python (built-in):
int → Whole numbers (e.g., 5, -100, 0)
float → Decimal numbers (e.g., 3.14, -0.5)
str → Text/strings (e.g., "Hello", 'Python')
bool → True or False
complex → Complex numbers (e.g., 3+4j) — used in math/science
Python also has more advanced types like list, tuple, dict, set (covered later).
Quick example program:
Python
name = "Anshuman" age = 25 height = 5.7 is_learning = True print("My name is", name) print("I am", age, "years old") print("Height:", height, "feet") print("Learning Python? Yes!", is_learning)
Output:
text
My name is Anshuman I am 25 years old Height: 5.7 feet Learning Python? Yes! True
Tip: Use meaningful names like total_price instead of x — makes code easier to read!
2.2 Numbers (int, float, complex)
Python handles numbers very easily.
int (Integer): Unlimited size (no overflow like in some languages).
Python
a = 100 b = -45 big_number = 12345678901234567890 # very large – no problem! print(a + b) # 55 print(a * 10) # 1000
float (Floating point): Decimals with approximate precision.
Python
pi = 3.14159 temperature = -2.5 print(pi * 2) # 6.28318
complex (Complex numbers): Used in engineering/math (real + imaginary part).
Python
c = 3 + 4j print(c) # (3+4j) print(c.real) # 3.0 print(c.imag) # 4.0 print(c.conjugate()) # (3-4j)
Common Operations:
Python
x = 10 y = 3 print(x + y) # 13 addition print(x - y) # 7 subtraction print(x y) # 30 multiplication print(x / y) # 3.333... division (always float) print(x // y) # 3 floor division (integer result) print(x % y) # 1 remainder (modulo) print(x * y) # 1000 power (x to the power y)
Tip: // is useful for integer results, % for checking even/odd (num % 2 == 0 → even).
2.3 Strings – Everything You Need to Know
Strings are sequences of characters (text). Defined using single quotes ' ' or double quotes " ".
Basic examples:
Python
greeting = "Hello, World!" name = 'Anshuman' multi_line = """This is a multi-line string in Python!""" print(greeting) # Hello, World! print(multi_line)
String Concatenation (joining):
Python
first = "Hello" second = "Python" print(first + " " + second) # Hello Python print(first * 3) # HelloHelloHello
f-strings (Best way – Python 3.6+): Super easy formatting!
Python
name = "Anshuman" age = 25 print(f"My name is {name} and I am {age} years old.") # My name is Anshuman and I am 25 years old.
Escape Characters: Use \ for special characters.
Python
print("He said, \"Python is fun!\"") # quotes inside print("Line1\nLine2") # new line print("Tab\tHere") # tab space print("Backslash \\") # print backslash
String Length & Access:
Python
text = "Python" print(len(text)) # 6 print(text[0]) # P (first character) print(text[-1]) # n (last character) print(text[1:4]) # yth (slicing: from index 1 to 3)
Tip: Strings are immutable — you can't change a character directly (e.g., text[0] = 'J' → error).
2.4 Boolean (True / False)
Booleans represent truth values — only two possibilities: True or False.
Used heavily in conditions/loops (later sections).
Python
is_adult = True has_python = False print(is_adult) # True print(type(is_adult)) # <class 'bool'> # Comparisons give booleans print(10 > 5) # True print(5 == 10) # False print("a" != "b") # True
Boolean from other types:
Empty string/list → False
Non-empty → True
0 → False, non-zero → True
Python
print(bool(0)) # False print(bool(100)) # True print(bool("")) # False print(bool("hi")) # True
2.5 type() function and Type Conversion
type() tells you the data type of any value/variable.
Python
x = 42 print(type(x)) # <class 'int'> y = 3.14 print(type(y)) # <class 'float'> z = "Hello" print(type(z)) # <class 'str'>
Type Conversion (Casting): Convert one type to another.
Python
# str → int num_str = "100" num = int(num_str) print(num + 50) # 150 # int/float → str age = 25 print("Age: " + str(age)) # Age: 25 # float → int (removes decimal) price = 99.99 print(int(price)) # 99 # str → float height = "5.7" print(float(height)) # 5.7
Common conversions:
int() → to integer
float() → to float
str() → to string
bool() → to boolean
Warning: Invalid conversion gives error, e.g., int("hello") → ValueError.
2.6 Comments in Python (# and multiline)
Comments explain your code — ignored by Python.
Single-line comment:
Python
# This is a single-line comment print("Hello") # This prints Hello (inline comment)
Multi-line comments: Use triple quotes (technically a string, but unused → acts as comment)
Python
""" This is a multi-line comment. You can write many lines here. Useful for explaining functions or sections. """ # OR use # on each line # Line 1 # Line 2
Best Practice:
Use comments to explain why (not what the code does)
Keep code self-explanatory with good variable names
Use docstrings (triple quotes) inside functions/classes later
Example with comments:
Python
# Program to calculate area of rectangle length = 10 # length in cm width = 5 # width in cm area = length * width # calculate area print(f"Area of rectangle: {area} sq cm") # output result
Output:
text
Area of rectangle: 50 sq cm
3. Operators in Python
Operators are special symbols that perform operations on values (called operands). Python has many built-in operators that make calculations, comparisons, and logic super easy.
Let’s learn all types one by one with real examples.
3.1 Arithmetic Operators (+, -, , /, //, %, *)
These are used for mathematical calculations.
OperatorNameExampleResultDescription+Addition10 + 515Adds two numbers-Subtraction10 - 55Subtracts*Multiplication10 550Multiplies/Division10 / 33.333...Always returns float//Floor Division10 // 33Returns integer (removes decimal)%Modulo (Remainder)10 % 31Returns remainder*Exponent (Power)2 ** 382 to the power of 3
Practical Examples:
Python
a = 15 b = 4 print(a + b) # 19 print(a - b) # 11 print(a b) # 60 print(a / b) # 3.75 print(a // b) # 3 print(a % b) # 3 print(a * b) # 50625
Real-life Tip: Use % to check even/odd:
Python
num = 25 print("Even" if num % 2 == 0 else "Odd") # Odd
3.2 Comparison Operators (==, !=, >, <, >=, <=)
These compare two values and return True or False.
OperatorNameExampleResult==Equal to5 == 5True!=Not equal to5 != 3True>Greater than10 > 5True<Less than10 < 5False>=Greater than or equal10 >= 10True<=Less than or equal5 <= 10True
Examples:
Python
age = 20 print(age == 18) # False print(age != 18) # True print(age > 18) # True print(age >= 20) # True print(age < 18) # False
Tip: These are used in if conditions (we will learn in Control Flow).
3.3 Logical Operators (and, or, not)
These combine multiple conditions.
OperatorDescriptionExampleandTrue only if both conditions are True(5>3 and 10>8) → TrueorTrue if at least one is True(5>10 or 10>8) → TruenotReverses the result (True becomes False)not (5>10) → True
Examples:
Python
age = 25 has_license = True print(age > 18 and has_license) # True → can drive print(age > 18 or has_license) # True print(not has_license) # False
Real-life Example:
Python
is_raining = True have_umbrella = False print("Go outside?" if not is_raining or have_umbrella else "Stay home") # Output: Stay home
3.4 Assignment Operators (=, +=, -=, *=, etc.)
Used to assign and update values in one step.
OperatorExampleSame as=x = 10x = 10+=x += 5x = x + 5-=x -= 3x = x - 3*=x = 2x = x 2/=x /= 4x = x / 4//=x //= 2x = x // 2%=x %= 3x = x % 3**=x = 2x = x 2
Live Example:
Python
score = 100 score += 50 # score = 150 score -= 20 # score = 130 score *= 2 # score = 260 score /= 2 # score = 130.0 print("Final score:", score)
3.5 Membership Operators (in, not in)
Check if a value exists in a sequence (string, list, tuple, etc.).
Python
fruits = ["apple", "banana", "mango"] name = "Anshuman" print("apple" in fruits) # True print("grape" in fruits) # False print("grape" not in fruits) # True print("a" in name) # True print("z" not in name) # True
3.6 Identity Operators (is, is not)
Check if two variables point to the same object in memory (not just equal value).
Python
x = 1000 y = 1000 a = [1, 2, 3] b = [1, 2, 3] print(x == y) # True (same value) print(x is y) # False (different objects) print(a == b) # True print(a is b) # False print(x is not y) # True
Important Note: Use == for value comparison and is only for identity (mostly with None, True, False).
Example with None:
Python
result = None print(result is None) # True (correct way)
This completes the full Operators in Python section — super important for all future topics!
4. Taking Input & Showing Output
In Python, showing output to the user and taking input from them are the most common ways programs interact with people. The two main functions are print() and input().
4.1 print() – All Important Ways to Use It
print() displays text, numbers, variables, or anything on the screen (console/terminal).
Basic Syntax:
Python
print(value1, value2, ..., sep=' ', end='\n')
Key Parameters:
sep → separator between values (default: space ' ')
end → what to print at the end (default: new line \n)
Examples – From Basic to Advanced:
Simple print
Python
print("Hello, World!") # Hello, World! print(100) # 100 print(True) # True
Print multiple values
Python
name = "Anshuman" age = 25 print("Name:", name, "Age:", age) # Output: Name: Anshuman Age: 25
Change separator (sep)
Python
print("Python", "is", "fun", sep="---") # Output: Python---is---fun
Change end (no new line)
Python
print("Hello", end=" ") # No new line print("World!") # Continues on same line # Output: Hello World!
Print special characters
Python
print("Line 1\nLine 2") # New line print("Tab\tHere") # Tab space print("Escape \"quotes\"") # Print quotes
Print variables with commas (old style)
Python
marks = 98 print("You scored", marks, "out of 100") # You scored 98 out of 100
Tip: print() automatically adds a space between items and a new line at the end — very convenient!
4.2 input() – Getting Data from User
input() pauses the program and waits for the user to type something and press Enter.
Syntax:
Python
variable = input("Prompt message: ")
Important: input() always returns a string (even if user types a number).
Examples:
Basic input
Python
name = input("Enter your name: ") print("Hello,", name, "!")
Sample run:
text
Enter your name: Anshuman Hello, Anshuman !
Taking number (but remember — it's string)
Python
age = input("Enter your age: ") print("You are", age, "years old") # If user types 25 → You are 25 years old (but age is string!)
Convert input to number (very common)
Python
age = int(input("Enter your age: ")) # Convert to integer height = float(input("Enter your height in cm: ")) # Convert to float print("Next year you will be", age + 1, "years old") print("Your height in meters:", height / 100)
Sample run:
text
Enter your age: 25 Enter your height in cm: 170.5 Next year you will be 26 years old Your height in meters: 1.705
Multiple inputs in one line
Python
# User types: 10 20 30 numbers = input("Enter 3 numbers separated by space: ").split() print("You entered:", numbers) # ['10', '20', '30']
Warning: If user enters wrong type → error on conversion! Example: int("abc") → ValueError Solution: Use try-except later (advanced topic).
Tip for beginners: Always convert input() when you expect numbers:
Python
marks = int(input("Enter marks: "))
4.3 Formatting Output (f-strings, .format(), % operator)
There are 3 main ways to format (make beautiful) output in Python.
1. f-strings (Recommended – Python 3.6+) – Easiest & Fastest
Python
name = "Anshuman" age = 25 city = "Muzaffarpur" print(f"My name is {name}, I am {age} years old, from {city}.") # My name is Anshuman, I am 25 years old, from Muzaffarpur.
Advanced f-string tricks:
Python
price = 999.99 print(f"Price: ₹{price:.2f}") # Price: ₹999.99 (2 decimal places) percentage = 78.456 print(f"Score: {percentage:.1f}%") # Score: 78.5% today = "2026" print(f"Welcome to Python in {today:^20}!") # Center align # Welcome to Python in 2026 !
2. .format() method – Still used a lot
Python
name = "Anshuman" age = 25 print("My name is {}, I am {} years old.".format(name, age)) # My name is Anshuman, I am 25 years old. print("Hello {0}, welcome back {0}! You are {1} now.".format(name, age)) # Hello Anshuman, welcome back Anshuman! You are 25 now.
3. % operator (Old style – Avoid in new code)
Python
name = "Anshuman" marks = 98.5 print("Name: %s, Marks: %.1f" % (name, marks)) # Name: Anshuman, Marks: 98.5
Comparison Table (Quick Guide):
MethodSyntax ExampleBest ForModern?f-stringsf"Hello {name}"Everyday use, clean & fastYes (2016+).format()"Hello {}".format(name)Older code, dynamic stringsYes% operator"Hello %s" % nameVery old codeNo
Recommendation for 2026: Always use f-strings — they are the most readable and fastest.
Mini Project Example – Combining print + input + formatting
Python
name = input("What is your name? ") age = int(input("How old are you? ")) print("-" 40) print(f"Welcome, {name.upper()}!") print(f"You are {age} years old → Next birthday: {age + 1}") print(f"Enjoy learning Python in {2026} 🎉") print("-" 40)
Sample Output:
text
What is your name? Anshuman How old are you? 25 ---------------------------------------- Welcome, ANSHUMAN! You are 25 years old → Next birthday: 26 Enjoy learning Python in 2026 🎉 ----------------------------------------
This completes the full Taking Input & Showing Output section.
5. Control Flow (Decision Making)
Control flow lets your program make decisions — like "if it's raining, take umbrella" or "if age > 18, show adult content". Python uses if, elif, else for this.
5.1 if, elif, else Statements
Syntax (basic structure):
Python
if condition: # code runs if condition is True elif another_condition: # optional, can have many # code runs if previous was False and this is True else: # optional # code runs if all above are False
Important Rules:
Colon : after condition
Indentation (usually 4 spaces) is mandatory — Python uses it to know which code belongs to the block
Conditions must evaluate to True or False
Example 1 – Simple if
Python
age = 20 if age >= 18: print("You are an adult. You can vote!")
Output (if age = 20):
text
You are an adult. You can vote!
Example 2 – if + else
Python
temperature = 15 if temperature > 30: print("It's very hot! Wear light clothes.") else: print("It's cool. Enjoy the weather!")
Output (temperature = 15):
text
It's cool. Enjoy the weather!
Example 3 – if + elif + else (most common)
Python
marks = 85 if marks >= 90: print("Grade: A+") elif marks >= 80: print("Grade: A") elif marks >= 70: print("Grade: B") elif marks >= 60: print("Grade: C") else: print("Grade: Fail")
Output (marks = 85):
text
Grade: A
Real-life Example – Traffic Light
Python
light = "red" if light == "green": print("Go!") elif light == "yellow": print("Slow down!") elif light == "red": print("Stop!") else: print("Invalid light color")
Output:
text
Stop!
Tip: You can have as many elif as you want, but else comes only at the end (and is optional).
5.2 Nested if-else
You can put if inside another if — called nested if.
Syntax:
Python
if condition1: if condition2: # both true else: # condition1 true, condition2 false else: # condition1 false
Example – Check eligibility for driving license
Python
age = 17 has_learner = True if age >= 18: if has_learner: print("You can apply for permanent license!") else: print("You need learner's license first.") else: print("You are too young to drive.")
Output (age = 17):
text
You are too young to drive.
Another Example – Login System (nested)
Python
username = "anshuman" password = "python123" if username == "anshuman": if password == "python123": print("Login successful! Welcome back.") else: print("Incorrect password.") else: print("User not found.")
Tip: Avoid too many levels of nesting (max 2–3) — code becomes hard to read. Use logical operators (and, or) instead when possible.
Better version using and:
Python
if username == "anshuman" and password == "python123": print("Login successful!") else: print("Invalid credentials.")
5.3 One-line if / Ternary Operator
Short way to write simple if-else in one line.
Syntax:
Python
value_if_true if condition else value_if_false
Examples:
Basic
Python
age = 20 status = "Adult" if age >= 18 else "Minor" print(status) # Adult
With print
Python
marks = 75 print("Pass" if marks >= 40 else "Fail") # Pass
Assign value
Python
temperature = 35 message = "Hot day" if temperature > 30 else "Normal day" print(message) # Hot day
Nested ternary (possible but avoid deep nesting)
Python
score = 92 grade = "A" if score >= 90 else "B" if score >= 80 else "C" print(grade) # A
When to use: For very short, simple decisions. When NOT to use: For complex logic — use normal if-else for readability.
5.4 pass Statement
pass is a placeholder — does nothing. Used when Python expects a block of code but you don't want to write anything yet.
Common Uses:
Empty if/else blocks during development
Empty functions/classes (later topics)
Ignore certain conditions temporarily
Example:
Python
age = 15 if age >= 18: print("Adult section") else: pass # do nothing for minors right now (maybe add later)
Another Example – Future function
Python
def calculate_tax(income): if income > 1000000: # complex logic later pass else: print("No tax")
Without pass → IndentationError!
Tip: Use pass as a temporary "TODO" marker. Replace it later with real code.
Mini Project – Simple Decision Maker
Python
print("=== Weather Advisor 2026 ===") temp = int(input("Enter current temperature (°C): ")) if temp >= 35: advice = "Very hot! Stay indoors, drink water." elif temp >= 25: advice = "Warm day. Wear light clothes." elif temp >= 15: advice = "Pleasant weather. Enjoy a walk!" else: advice = "Cold! Wear jacket and stay warm." print(f"Advice: {advice}")
Sample Output:
text
=== Weather Advisor 2026 === Enter current temperature (°C): 28 Advice: Warm day. Wear light clothes.
This completes the full Control Flow (Decision Making) section — now your programs can make smart decisions!
Loops in Python
Loops allow your program to repeat a block of code multiple times — very useful for tasks like printing tables, processing lists, or repeating until a condition is met.
Python has two main loop types: while and for.
6.1 while Loop (with else)
while repeats code as long as a condition is True.
Syntax:
Python
while condition: # code to repeat # update variable (very important!)
Example 1 – Basic while
Python
count = 1 while count <= 5: print("Count:", count) count += 1 # Important: increase count or loop forever!
Output:
text
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
while with else The else block runs only if the loop finishes normally (not stopped by break).
Python
i = 1 while i <= 3: print("i =", i) i += 1 else: print("Loop finished successfully!")
Output:
text
i = 1 i = 2 i = 3 Loop finished successfully!
Real-life Example – Guess Number Game (simple version)
Python
secret = 7 guess = 0 while guess != secret: guess = int(input("Guess a number (1-10): ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") print("You guessed it! 🎉")
6.2 for Loop (with range(), strings, lists)
for loop is used when you know how many times to repeat (or when iterating over a sequence).
Syntax:
Python
for variable in sequence: # code to repeat
Most common ways to use for loop:
for with range() – Repeat a fixed number of times
Python
# range(start, stop, step) stop is exclusive for i in range(5): # 0 to 4 print(i) print("---") for i in range(1, 6): # 1 to 5 print(i) print("---") for i in range(1, 10, 2): # 1,3,5,7,9 print(i)
Output:
text
0 1 2 3 4 --- 1 2 3 4 5 --- 1 3 5 7 9
for with strings
Python
name = "Anshuman" for char in name: print(char)
Output:
text
A n s h u m a n
for with lists (very common)
Python
fruits = ["apple", "banana", "mango", "orange"] for fruit in fruits: print("I like", fruit)
Output:
text
I like apple I like banana I like mango I like orange
Tip: Use range() when you need index numbers:
Python
colors = ["red", "green", "blue"] for i in range(len(colors)): print(f"Color {i+1}: {colors[i]}")
6.3 break, continue, and pass Keywords
These control the flow inside loops.
break → Exit the loop immediately
continue → Skip the rest of current iteration, go to next
pass → Do nothing (placeholder)
Example – All together
Python
for num in range(1, 11): if num == 3: continue # skip 3 if num == 7: break # stop at 7 if num == 5: pass # do nothing special print(num)
Output:
text
1 2 4 5 6
Real Example – Find first even number > 10
Python
numbers = [3, 7, 12, 15, 20, 8] for n in numbers: if n > 10 and n % 2 == 0: print("First even number > 10 is:", n) break
Output:
text
First even number > 10 is: 12
6.4 Nested Loops
A loop inside another loop — used for patterns, tables, grids, etc.
Example 1 – Multiplication Table
Python
for i in range(1, 6): # outer loop for j in range(1, 6): # inner loop print(f"{i} × {j} = {i*j}", end="\t") print() # new line after each row
Output (partial):
text
1 × 1 = 1 1 × 2 = 2 1 × 3 = 3 ... 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6 ... ...
Example 2 – Star Pattern
Python
rows = 5 for i in range(1, rows + 1): for j in range(i): print("*", end=" ") print()
Output:
text
* * * * * * * * * * * * * * *
6.5 Infinite Loops – How to Avoid Them
An infinite loop runs forever (or until you force stop it).
Common Causes:
Forgot to update condition variable
Condition always True
Bad Example (Infinite):
Python
count = 1 while count < 10: print(count) # forgot count += 1 → infinite!
How to Avoid:
Always update the loop variable inside the loop
Use break when needed
Test small cases first
For while True (intentional infinite), add exit condition
Safe Infinite Loop Example (with break):
Python
while True: choice = input("Type 'exit' to quit: ") if choice.lower() == "exit": print("Goodbye!") break print("You typed:", choice)
Tip: In VS Code / terminal → Press Ctrl + C to force stop any infinite loop.
Mini Project – Number Guessing Game (Full)
Python
import random secret = random.randint(1, 100) attempts = 0 print("Guess the number (1-100)") while True: guess = int(input("Your guess: ")) attempts += 1 if guess == secret: print(f"Correct! You took {attempts} attempts. 🎉") break elif guess < secret: print("Too low!") else: print("Too high!")
This completes the full Loops in Python section — now your programs can repeat tasks powerfully!
7. Lists – Most Important Data Structure
A list is an ordered, changeable (mutable), and indexed collection of items. You can store anything in a list: numbers, strings, booleans, other lists, etc.
7.1 Creating Lists
Ways to create a list:
Empty list
Python
my_list = [] empty = list() # same thing
With values
Python
fruits = ["apple", "banana", "mango", "orange"] numbers = [10, 20, 30, 40, 50] mixed = [1, "hello", True, 3.14, [5, 6]] # mixed types allowed!
From other data (using list())
Python
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n'] range_list = list(range(1, 6)) # [1, 2, 3, 4, 5]
Length of list
Python
print(len(fruits)) # 4
Tip: Lists are mutable — you can change them after creation (unlike strings or tuples).
7.2 Accessing, Slicing & Negative Indexing
Lists are zero-indexed (first item = index 0).
Access single item
Python
fruits = ["apple", "banana", "mango", "orange"] print(fruits[0]) # apple print(fruits[2]) # mango print(fruits[-1]) # orange (last item) print(fruits[-2]) # mango (second last)
Slicing (get a part of the list)
Python
print(fruits[1:3]) # ['banana', 'mango'] (start inclusive, end exclusive) print(fruits[:3]) # ['apple', 'banana', 'mango'] (from start) print(fruits[2:]) # ['mango', 'orange'] (to end) print(fruits[::2]) # ['apple', 'mango'] (every 2nd item) print(fruits[::-1]) # ['orange', 'mango', 'banana', 'apple'] (reverse list)
Negative slicing example
Python
print(fruits[-3:-1]) # ['banana', 'mango']
Tip: Slicing creates a new list — original list remains unchanged.
7.3 List Methods (append, extend, insert, remove, pop, clear, sort, reverse, etc.)
Lists have many built-in methods — very powerful!
MethodDescriptionExampleResult after operationappend()Add one item at the endfruits.append("grapes")['apple', ..., 'grapes']extend()Add multiple items (from another list)fruits.extend(["kiwi", "pineapple"])Adds both itemsinsert()Insert at specific positionfruits.insert(1, "cherry")Insert at index 1remove()Remove first occurrence of valuefruits.remove("banana")Removes "banana"pop()Remove & return item (default: last)fruits.pop(2)Removes & returns item at index 2clear()Remove all itemsfruits.clear()[]sort()Sort list in place (ascending)numbers.sort()Sorted numbersreverse()Reverse the list in placefruits.reverse()Reversed orderindex()Find first index of valuefruits.index("mango")Returns index (or error if not found)count()Count occurrencesfruits.count("apple")Number of times "apple" appears
Practical Examples:
Python
# Start with this numbers = [30, 10, 50, 20] numbers.append(60) # [30, 10, 50, 20, 60] numbers.extend([70, 80]) # [30, 10, 50, 20, 60, 70, 80] numbers.insert(1, 15) # [30, 15, 10, 50, 20, 60, 70, 80] numbers.remove(50) # [30, 15, 10, 20, 60, 70, 80] last = numbers.pop() # removes 80, last = 80 print(last) # 80 numbers.sort() # [10, 15, 20, 30, 60, 70] numbers.reverse() # [70, 60, 30, 20, 15, 10] print(numbers.count(20)) # 1 print(numbers.index(30)) # 2 (after sorting & reversing)
Tip: sort() changes the original list. To get a sorted copy without changing original:
Python
sorted_numbers = sorted(numbers) # new sorted list
7.4 List Comprehension (Super Powerful & Short)
List comprehension is a concise way to create lists — very Pythonic and fast!
Basic Syntax:
Python
new_list = [expression for item in iterable if condition]
Examples:
Simple
Python
squares = [x**2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25]
With condition
Python
evens = [x for x in range(1, 11) if x % 2 == 0] print(evens) # [2, 4, 6, 8, 10]
With strings
Python
names = ["anshuman", "rahul", "priya"] upper = [name.upper() for name in names] print(upper) # ['ANSHUMAN', 'RAHUL', 'PRIYA']
Nested comprehension (simple)
Python
pairs = [(x, y) for x in [1,2] for y in ['a','b']] print(pairs) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
Old way vs Comprehension
Python
# Old way (longer) result = [] for num in range(10): if num % 2 == 0: result.append(num 2) # Comprehension (short & clean) result = [num 2 for num in range(10) if num % 2 == 0] print(result) # [0, 4, 8, 12, 16]
Tip: Use comprehensions for readability and speed — but don't make them too complex.
7.5 Looping through Lists
Three common ways to loop through lists:
Direct iteration (recommended most times)
Python
fruits = ["apple", "banana", "mango"] for fruit in fruits: print("I love", fruit)
Using range() + index
Python
for i in range(len(fruits)): print(f"Index {i}: {fruits[i]}")
Using enumerate() – Best for index + value
Python
for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")
Output:
text
1. apple 2. banana 3. mango
Mini Project – To-Do List Manager (using lists)
Python
todo = [] while True: print("\n1. Add task 2. View tasks 3. Remove task 4. Exit") choice = input("Choose: ") if choice == "1": task = input("Enter task: ") todo.append(task) print("Task added!") elif choice == "2": if todo: print("Your To-Do List:") for i, task in enumerate(todo, 1): print(f"{i}. {task}") else: print("No tasks yet!") elif choice == "3": if todo: num = int(input("Task number to remove: ")) if 1 <= num <= len(todo): removed = todo.pop(num - 1) print(f"Removed: {removed}") else: print("Invalid number!") else: print("No tasks!") elif choice == "4": print("Goodbye!") break
This completes the full Lists section — now you know one of Python's most important tools!
8. Tuples
Tuples are very similar to lists, but with one big difference: they are immutable (cannot be changed after creation).
8.1 What is a Tuple? Why Use It?
A tuple is an ordered, immutable collection of items. Defined using parentheses () (or sometimes without them).
Creating a tuple:
Python
# Empty tuple empty = () # Single item tuple (must have comma!) single = (5,) # Note the comma! wrong = (5) # This is just integer 5, not tuple # Multiple items coordinates = (10, 20, 30) person = ("Anshuman", 25, "Muzaffarpur", True) mixed = (1, "hello", 3.14, [10, 20]) # can contain lists (mutable inside)
Why Use Tuples?
Immutable → Data cannot be accidentally changed (safer for fixed data)
Faster than lists (because immutable)
Use as dictionary keys (lists cannot be keys because mutable)
Return multiple values from functions easily
Memory efficient for fixed collections
Common in real-world: coordinates, RGB colors, days of week, database records
Example – Fixed data
Python
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") print(days[0]) # Monday # days[0] = "Sun" # Error! Tuples are immutable
8.2 Tuple vs List – Quick Comparison
FeatureTupleListSyntax(1, 2, 3) or 1, 2, 3[1, 2, 3]Mutable?No (cannot change)Yes (can add/remove/change)SpeedFaster (fixed size)Slightly slowerMemory usageLessMoreCan be dictionary key?YesNoMethods availableVery few (count, index)Many (append, pop, sort, etc.)Use when...Data should never changeData needs to be modifiedCommon examplesCoordinates, config valuesShopping list, to-do items
Quick Tip: If you don’t need to change the collection → use tuple (safer & faster). If you need to modify → use list.
8.3 Tuple Methods (count, index)
Tuples have only two methods because they are immutable.
count(value) → Returns how many times a value appears
Python
numbers = (1, 2, 2, 3, 2, 4) print(numbers.count(2)) # 3 print(numbers.count(5)) # 0
index(value) → Returns first position (index) of value (Raises ValueError if not found)
Python
colors = ("red", "green", "blue", "green") print(colors.index("green")) # 1 print(colors.index("blue")) # 2 # print(colors.index("yellow")) # Error: not in tuple
Tip: To check if item exists first:
Python
if "yellow" in colors: print(colors.index("yellow")) else: print("Not found")
8.4 Packing & Unpacking
Packing → Putting multiple values into a tuple automatically.
Unpacking → Extracting values from a tuple into variables.
Basic Packing & Unpacking
Python
# Packing person_info = "Anshuman", 25, "Muzaffarpur" # tuple created automatically # Unpacking name, age, city = person_info print(name) # Anshuman print(age) # 25 print(city) # Muzaffarpur
Unpacking with * (extended unpacking)
Python
numbers = (1, 2, 3, 4, 5) first, *middle, last = numbers print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5
Swap two variables (classic use of unpacking)
Python
a = 10 b = 20 a, b = b, a # No temporary variable needed! print(a, b) # 20 10
Return multiple values from function
Python
def get_person(): return "Anshuman", 25, "Bihar" # packs into tuple name, age, state = get_person() print(f"{name} is {age} from {state}")
Ignore values during unpacking
Python
data = (100, 200, 300, 400) x, , y, = data # _ means ignore print(x, y) # 100 300
Mini Project Example – Coordinate System
Python
def move(position, direction): x, y = position # unpack tuple if direction == "up": y += 10 elif direction == "down": y -= 10 elif direction == "left": x -= 10 elif direction == "right": x += 10 return (x, y) # pack and return new position current = (0, 0) print("Start:", current) current = move(current, "right") print("After right:", current) # (10, 0) current = move(current, "up") print("After up:", current) # (10, 10)
Output:
text
Start: (0, 0) After right: (10, 0) After up: (10, 10)
This completes the full Tuples section — short but very useful in real Python programming!
9. Strings (Deep Dive)
Strings are sequences of characters (text). They are immutable (cannot be changed after creation, like tuples).
9.1 String Slicing & Negative Indexing
Strings support indexing and slicing — just like lists.
Indexing:
Positive: starts from 0 (left to right)
Negative: starts from -1 (right to left)
Example:
Python
text = "Python Programming" print(text[0]) # P print(text[6]) # P (space is also a character) print(text[-1]) # g print(text[-9]) # r
Slicing Syntax:
Python
text[start:end:step] # start → inclusive # end → exclusive # step → optional (default 1)
Examples:
Python
print(text[0:6]) # Python print(text[7:]) # Programming print(text[:6]) # Python print(text[::2]) # Pto rgamn (every 2nd character) print(text[::-1]) # gnimmargorP nohtyP (reversed string!) print(text[-12:-6]) # Progra (negative slicing) print(text[7:18:3]) # Porm (start 7, step 3)
Tip: Slicing creates a new string — original remains unchanged. Common use: Reverse a string → text[::-1]
9.2 String Methods (upper, lower, strip, replace, split, join, find, etc.)
Strings have many useful built-in methods.
MethodDescriptionExampleResultupper()Convert to uppercase"hello".upper()"HELLO"lower()Convert to lowercase"HELLO".lower()"hello"title()Capitalize first letter of each word"python is fun".title()"Python Is Fun"capitalize()Capitalize first letter only"python is fun".capitalize()"Python is fun"strip()Remove leading/trailing whitespace" hello ".strip()"hello"lstrip() / rstrip()Remove left/right whitespace only" hello ".lstrip()"hello "replace(old, new)Replace substring"I like Java".replace("Java", "Python")"I like Python"split()Split string into list (default: space)"apple banana mango".split()['apple', 'banana', 'mango']split(sep)Split by specific separator"name,age,city".split(",")['name', 'age', 'city']join()Join list elements with separator"-".join(["2026", "03", "05"])"2026-03-05"find(sub)Return first index of substring (or -1)"hello world".find("world")6index(sub)Like find(), but raises error if not found"hello".index("l")2startswith() / endswith()Check prefix/suffix"python.py".endswith(".py")Truecount(sub)Count occurrences"banana".count("a")3
Practical Examples:
Python
sentence = " Python is awesome! Learn Python today. " print(sentence.strip()) # "Python is awesome! Learn Python today." print(sentence.upper()) # " PYTHON IS AWESOME! LEARN PYTHON TODAY. " print(sentence.replace("Python", "Java")) # " Java is awesome! Learn Java today. " words = sentence.split() # ['Python', 'is', 'awesome!', 'Learn', 'Python', 'today.'] print(words) date_parts = ["2026", "March", "05"] print("/".join(date_parts)) # 2026/March/05 print(sentence.find("awesome")) # 10 (first occurrence) print(sentence.count("Python")) # 2
Tip: join() is the opposite of split() — very useful for creating CSV, paths, etc.
9.3 Check if String Contains Something
Several ways to check:
in operator (most common & readable)
Python
text = "I love Python programming" print("Python" in text) # True print("java" in text) # False print("python" in text.lower()) # True (case-insensitive)
find() or index()
Python
if text.find("love") != -1: print("Found 'love' at position:", text.find("love")) # 2
startswith() / endswith()
Python
filename = "report.pdf" print(filename.endswith(".pdf")) # True print(filename.startswith("report")) # True
Tip: For case-insensitive check → convert both to lower/upper first.
9.4 Escape Characters
Use \ (backslash) to include special characters inside strings.
Escape SequenceMeaningExampleOutput\nNew line"Line1\nLine2"Line1 Line2\tTab"Name:\tAnshuman"Name: Anshuman\\Backslash"Path\to\file"Path\to\file\"Double quote inside """He said "Hello""He said "Hello"\'Single quote inside '''It's Python'It's Python
Example:
Python
print("Hello\nWorld!") # Hello # World! print("C:\\Users\\Anshuman") # C:\Users\Anshuman print("She said, \"I love Python!\"") # She said, "I love Python!"
Tip: Use raw strings to ignore escapes → add r before quotes:
Python
print(r"C:\new\test") # C:\new\test (no new line)
9.5 Multiline Strings
Create strings that span multiple lines.
Two ways:
Triple quotes """ """ or ''' '''
Python
message = """ Hello Anshuman, Welcome to Python tutorial 2026! This is a multiline string. Enjoy learning! """ print(message)
Output:
text
Hello Anshuman, Welcome to Python tutorial 2026! This is a multiline string. Enjoy learning!
Using \ at end of each line (inside single/double quotes)
Python
long_text = "Python is great because " \ "it is easy to read " \ "and write." print(long_text)
Tip: Triple quotes preserve newlines and indentation — very useful for:
Docstrings (function/class documentation)
HTML templates
SQL queries
Long messages/emails
Mini Project – Text Cleaner & Analyzer
Python
text = input("Enter some text: ").strip() # Clean and analyze clean_text = text.lower().replace(",", "").replace(".", "") words = clean_text.split() print("Original:", text) print("Lowercase:", text.lower()) print("Word count:", len(words)) print("Contains 'python'?", "python" in clean_text) print("First word:", words[0] if words else "Empty")
This completes the full Strings (Deep Dive) section — now you can handle text like a pro!
Dictionaries. Dictionaries are one of Python's most powerful and commonly used data structures — perfect for storing data in key-value pairs (like a real dictionary: word → meaning).
Written in simple English with syntax, many practical examples, outputs, and tips — ready to copy-paste directly into your webpage.
10. Dictionaries
A dictionary (or dict) is an unordered, mutable, and indexed collection of key-value pairs. Keys must be unique and immutable (strings, numbers, tuples), values can be anything.
10.1 Creating & Accessing Dictionaries
Ways to create a dictionary:
Empty dictionary
Python
my_dict = {} empty = dict() # same thing
With key-value pairs
Python
person = { "name": "Anshuman", "age": 25, "city": "Muzaffarpur", "is_student": True, "hobbies": ["coding", "cricket", "reading"] } student = dict(name="Rahul", marks=85, grade="A")
Accessing values Use square brackets [] with key (fast & common)
Python
print(person["name"]) # Anshuman print(person["age"]) # 25 print(person["hobbies"]) # ['coding', 'cricket', 'reading']
Safer way: .get() method (returns None if key not found, no error)
Python
print(person.get("phone")) # None print(person.get("phone", "Not available")) # Not available
Tip: Never use [] if key might not exist → it raises KeyError.
10.2 Adding, Updating, Removing Items
Dictionaries are mutable — easy to change.
Add or Update (same syntax)
Python
person["phone"] = "9876543210" # adds new key person["age"] = 26 # updates existing person["skills"] = ["Python", "HTML"] # adds list print(person["phone"]) # 9876543210
Remove item
Python
del person["is_student"] # removes key-value pair removed_age = person.pop("age") # removes & returns value print(removed_age) # 26 person.pop("city", None) # safe remove (no error if missing)
Clear entire dictionary
Python
person.clear() # becomes {}
Tip: Use pop() when you want the removed value, del when you don't.
10.3 Dictionary Methods (keys, values, items, get, update, pop, etc.)
Important built-in methods:
MethodDescriptionExampleResult / Returnskeys()Returns all keysperson.keys()dict_keys(['name', 'age', ...])values()Returns all valuesperson.values()dict_values(['Anshuman', 25, ...])items()Returns key-value pairs as tuplesperson.items()dict_items([('name', 'Anshuman'), ...])get(key, default)Get value safely (default if missing)person.get("age", 0)25 or 0update()Merge another dict or add multiple pairsperson.update({"city": "Patna", "job": "Dev"})Updates personpop(key)Remove & return valueperson.pop("name")'Anshuman'popitem()Remove & return last inserted pair (Python 3.7+)person.popitem()('job', 'Dev')clear()Remove all itemsperson.clear(){}copy()Shallow copy of dictionarynew = person.copy()New independent dict
Practical Example – Update & Merge
Python
info = {"name": "Priya", "age": 22} extra = {"city": "Delhi", "skills": ["Java", "SQL"]} info.update(extra) print(info) # {'name': 'Priya', 'age': 22, 'city': 'Delhi', 'skills': ['Java', 'SQL']}
10.4 Looping through Dictionaries
Three main ways:
Loop over keys (default)
Python
for key in person: print(key, ":", person[key])
Loop over keys() explicitly
Python
for key in person.keys(): print(key)
Loop over values
Python
for value in person.values(): print(value)
Loop over key-value pairs (best & most common)
Python
for key, value in person.items(): print(f"{key.capitalize()}: {value}")
Output example:
text
Name: Anshuman Age: 25 City: Muzaffarpur Hobbies: ['coding', 'cricket', 'reading']
Tip: Always prefer .items() when you need both key and value.
10.5 Nested Dictionaries
Dictionaries inside dictionaries — very useful for complex data (like JSON, student records, configs).
Example – Student Database
Python
students = { "student1": { "name": "Anshuman", "age": 25, "marks": {"math": 95, "science": 88, "english": 92}, "address": {"city": "Muzaffarpur", "state": "Bihar"} }, "student2": { "name": "Rahul", "age": 24, "marks": {"math": 78, "science": 85}, "address": {"city": "Patna"} } } # Access nested data print(students["student1"]["name"]) # Anshuman print(students["student1"]["marks"]["math"]) # 95 print(students["student2"]["address"].get("state", "N/A")) # N/A # Update nested students["student1"]["marks"]["science"] = 90 # Add new student students["student3"] = {"name": "Priya", "age": 23}
Loop through nested dictionary
Python
for student_id, details in students.items(): print(f"\nStudent ID: {student_id}") for key, value in details.items(): if isinstance(value, dict): print(f" {key.capitalize()}:") for sub_key, sub_value in value.items(): print(f" {sub_key}: {sub_value}") else: print(f" {key.capitalize()}: {value}")
Mini Project – Simple Contact Book
Python
contacts = {} while True: print("\n1. Add Contact 2. View Contact 3. Delete Contact 4. Exit") choice = input("Choose: ") if choice == "1": name = input("Name: ").strip().title() phone = input("Phone: ").strip() contacts[name] = phone print(f"{name} added!") elif choice == "2": name = input("Enter name to search: ").strip().title() if name in contacts: print(f"{name}: {contacts[name]}") else: print("Not found!") elif choice == "3": name = input("Enter name to delete: ").strip().title() contacts.pop(name, None) print("Deleted if existed.") elif choice == "4": print("Goodbye!") break
This completes the full Dictionaries section — now you can handle key-value data like a pro!
11. Sets
A set is an unordered, mutable collection of unique items (no duplicates allowed). Sets are very fast for checking if an item exists (in operator) and for performing mathematical operations like union, intersection, etc.
11.1 What is a Set? Unique Values
Key Features of Sets:
Unordered → No indexing (cannot use [0], [1], etc.)
No duplicates → Adding the same item multiple times has no effect
Mutable → You can add/remove items (but items themselves must be immutable: numbers, strings, tuples — not lists or dictionaries)
Very fast membership testing (in is O(1) average time)
Creating a Set:
Using curly braces {}
Python
fruits = {"apple", "banana", "mango", "apple"} # duplicate "apple" ignored print(fruits) # {'apple', 'banana', 'mango'} (order may vary)
Using set() function
Python
empty_set = set() # Important! {} is empty dict, not empty set numbers = set([1, 2, 2, 3, 4]) # {1, 2, 3, 4} from_string = set("hello") # {'h', 'e', 'l', 'o'} (unique characters)
Remove duplicates from a list (very common use)
Python
my_list = [10, 20, 10, 30, 20, 40] unique = set(my_list) print(unique) # {10, 20, 30, 40}
Check membership
Python
print("apple" in fruits) # True print("grape" in fruits) # False
Tip: Use sets when order doesn't matter and duplicates are unwanted (e.g., unique users, tags, IDs).
11.2 Set Operations (union, intersection, difference, symmetric difference)
Sets support mathematical operations — very useful in data analysis, filtering, etc.
OperationSymbolMethodDescriptionExample (A = {1,2,3}, B = {3,4,5})Union``A.union(B)All elements from both setsIntersection&A.intersection(B)Elements common to both{3}Difference-A.difference(B)Elements in A but not in B{1,2}Symmetric Difference^A.symmetric_difference(B)Elements in A or B but not both{1,2,4,5}
Examples with code:
Python
A = {1, 2, 3, 4} B = {3, 4, 5, 6} # Union print(A | B) # {1, 2, 3, 4, 5, 6} print(A.union(B)) # same # Intersection print(A & B) # {3, 4} print(A.intersection(B)) # same # Difference print(A - B) # {1, 2} print(B - A) # {5, 6} # Symmetric Difference print(A ^ B) # {1, 2, 5, 6} print(A.symmetric_difference(B)) # same
Real-life Example – Find common friends
Python
my_friends = {"Rahul", "Priya", "Ankit", "Sneha"} her_friends = {"Sneha", "Vikram", "Priya", "Rohan"} common = my_friends & her_friends print("Common friends:", common) # {'Priya', 'Sneha'} only_mine = my_friends - her_friends print("Only my friends:", only_mine) # {'Rahul', 'Ankit'}
Tip: You can chain operations: A | B & C - D
11.3 Set Methods (add, remove, discard, update, etc.)
Sets have useful methods for modification.
MethodDescriptionExampleEffect / Returnsadd(item)Add a single items.add(10)Adds if not presentupdate(iterable)Add multiple items from list/tuple/sets.update([5,6,7])Adds all unique itemsremove(item)Remove item (raises KeyError if missing)s.remove(3)Removes itemdiscard(item)Remove item (no error if missing)s.discard(99)Safe removepop()Remove & return arbitrary items.pop()Returns removed itemclear()Remove all itemss.clear()Becomes empty setcopy()Shallow copynew = s.copy()Independent copyissubset()Check if all elements are in another setA.issubset(B)True/Falseissuperset()Check if contains another setB.issuperset(A)True/Falseisdisjoint()No common elementsA.isdisjoint(B)True/False
Practical Examples:
Python
s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.update([3, 5, 6, 4]) # {1, 2, 3, 4, 5, 6} (duplicates ignored) s.remove(2) # {1, 3, 4, 5, 6} s.discard(99) # No error print(s.pop()) # Removes random item, e.g., 1 print(s) # e.g. {3, 4, 5, 6} # Set relations A = {1, 2, 3} B = {1, 2, 3, 4} print(A.issubset(B)) # True print(B.issuperset(A)) # True print(A.isdisjoint({5,6})) # True
Mini Project – Unique Visitors & Common Interests
Python
visitors_today = ["user1", "user2", "user1", "user3", "user4"] unique_visitors = set(visitors_today) print("Unique visitors today:", len(unique_visitors), unique_visitors) # Interests group_A = {"cricket", "coding", "music", "football"} group_B = {"coding", "reading", "music", "chess"} print("Common interests:", group_A & group_B) # {'coding', 'music'} print("All interests:", group_A | group_B) print("Only group A:", group_A - group_B)
This completes the full Sets section — short, powerful, and super useful for uniqueness and operations!
12. Functions – Reusing Code
A function is a block of code that performs a specific task. You define it once and call it many times — avoids repetition (DRY principle: Don't Repeat Yourself).
12.1 Defining & Calling Functions
Syntax to define a function:
Python
def function_name(parameters): # optional parameters # code to execute # optional return statement
Calling (using) the function:
Python
function_name(arguments)
Example – Simple function
Python
def greet(): print("Hello, Anshuman!") print("Welcome to Python 2026!") # Call the function greet() greet() # You can call it multiple times
Output:
text
Hello, Anshuman! Welcome to Python 2026! Hello, Anshuman! Welcome to Python 2026!
Example with parameter
Python
def greet(name): print(f"Hello, {name}! How are you?") greet("Anshuman") greet("Rahul")
Output:
text
Hello, Anshuman! How are you? Hello, Rahul! How are you?
Tip: Function name should be lowercase with underscores (snake_case) — e.g., calculate_area
12.2 Parameters vs Arguments
Parameter: Variable listed inside the parentheses in the function definition (placeholder)
Argument: Actual value passed when you call the function
Python
def add(a, b): # a, b are parameters print(a + b) add(5, 3) # 5, 3 are arguments add(10, 20) # positional arguments
Output:
text
8 30
12.3 Default Arguments
You can give parameters default values — they become optional.
Syntax:
Python
def function_name(param=default_value): ...
Example:
Python
def greet(name="Guest"): print(f"Hello, {name}! Welcome!") greet("Anshuman") # Hello, Anshuman! Welcome! greet() # Hello, Guest! Welcome!
Important Rule: Default parameters must come after non-default ones
Python
# Correct def info(name, age=25, city="Muzaffarpur"): print(name, age, city) # Wrong → SyntaxError # def info(age=25, name, city): ...
12.4 Keyword Arguments
Pass arguments using parameter names — order doesn't matter.
Example:
Python
def person_info(name, age, city): print(f"{name} is {age} years old from {city}") person_info(age=25, name="Anshuman", city="Muzaffarpur") # Order doesn't matter when using keywords
Mix positional + keyword (positional first)
Python
person_info("Rahul", city="Patna", age=24)
Tip: Keyword arguments make code more readable when there are many parameters.
12.5 args and *kwargs
Used when you don't know how many arguments will be passed.
*args → collects extra positional arguments into a tuple
**kwargs → collects extra keyword arguments into a dictionary
*Example – args
Python
def sum_numbers(*args): total = 0 for num in args: total += num return total print(sum_numbers(1, 2, 3)) # 6 print(sum_numbers(10, 20, 30, 40)) # 100 print(sum_numbers()) # 0
**Example – kwargs
Python
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Anshuman", age=25, city="Muzaffarpur", hobby="coding")
Output:
text
name: Anshuman age: 25 city: Muzaffarpur hobby: coding
Combined Example
Python
def advanced_func(a, b, args, *kwargs): print("a:", a) print("b:", b) print("args:", args) print("kwargs:", kwargs) advanced_func(10, 20, 30, 40, name="Test", city="Bihar")
Output:
text
a: 10 b: 20 args: (30, 40) kwargs: {'name': 'Test', 'city': 'Bihar'}
Tip: Common in real libraries (e.g., print(), matplotlib.plot())
12.6 Return Statement
return sends a value back to the caller. Function stops after return.
Examples:
Python
def square(num): return num * num result = square(5) print(result) # 25 print(square(10)) # 100
Multiple returns (one at a time)
Python
def check_even_odd(num): if num % 2 == 0: return "Even" else: return "Odd" print(check_even_odd(10)) # Even
Return multiple values (packs into tuple)
Python
def get_person(): return "Anshuman", 25, "Muzaffarpur" name, age, city = get_person() # unpacking print(name, age, city)
Tip: If no return, function returns None by default.
12.7 Scope – Local vs Global Variables
Local scope → Variables defined inside function (only accessible inside) Global scope → Variables defined outside (accessible everywhere, but careful)
Example:
Python
x = 100 # global def my_func(): y = 200 # local print("Inside function: x =", x) # can read global print("y =", y) my_func() print("Outside: x =", x) # print(y) # Error! y is local
Modify global inside function
Python
count = 0 def increment(): global count count += 1 print("Count:", count) increment() # Count: 1 increment() # Count: 2 print(count) # 2
Tip: Avoid modifying globals too much — pass as parameters instead for cleaner code.
12.8 Lambda Functions (Anonymous Functions)
Short, nameless functions — used for one-liners.
Syntax:
Python
lambda arguments: expression
Examples:
Python
# Normal function def square(x): return x x # Lambda equivalent square_lambda = lambda x: x x print(square_lambda(5)) # 25
Common uses – with map(), filter(), sort()
Python
numbers = [1, 2, 3, 4, 5] # Double each doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # [2, 4, 6, 8, 10] # Filter even evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # Sort by length words = ["apple", "banana", "kiwi"] sorted_words = sorted(words, key=lambda w: len(w)) print(sorted_words) # ['kiwi', 'apple', 'banana']
Mini Project – Calculator using Functions
Python
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x y def divide(x, y): if y == 0: return "Cannot divide by zero!" return x / y operations = { "+": add, "-": subtract, "": multiply, "/": divide } print("Simple Calculator") num1 = float(input("First number: ")) op = input("Operator (+ - * /): ") num2 = float(input("Second number: ")) if op in operations: result = operations[op](num1, num2) print(f"{num1} {op} {num2} = {result}") else: print("Invalid operator!")
This completes the full Functions section — now you can write reusable, powerful code!
13. Modules & How to Use Them
A module is a file containing Python code (usually functions, classes, or variables) that you can import and use in other Python files.
13.1 What is a Module?
A module is just a .py file with Python code.
Python comes with many built-in modules (no installation needed).
You can also install external modules using pip (later topic).
You can create your own modules easily.
Why use modules?
Organize large programs (split code into files)
Reuse code in different projects
Use powerful libraries written by others (math, random, requests, pandas, etc.)
Keep code clean and maintainable
13.2 import, from … import, as keyword
There are different ways to bring code from a module into your program.
Basic import
Python
import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.141592653589793
import with alias (as) – very common
Python
import random as rnd print(rnd.randint(1, 100)) # random number between 1 and 100
from … import … (import specific things)
Python
from math import sqrt, pi print(sqrt(25)) # 5.0 print(pi) # 3.141592653589793
from … import * (import everything – avoid this in big projects)
Python
from random import * print(randint(1, 10)) # works directly
Best Practices (2026 standard):
Use import module or import module as short_name (most readable)
Use from module import specific_function when you need only 1–2 things
Avoid from module import * — can cause name conflicts
13.3 Popular Built-in Modules (math, random, datetime)
Python has many useful built-in modules — no installation needed!
1. math – Mathematical functions
Python
import math print(math.ceil(4.2)) # 5 print(math.floor(4.9)) # 4 print(math.pow(2, 3)) # 8.0 print(math.factorial(5)) # 120 print(math.sin(math.radians(30))) # 0.5 (sin 30°)
2. random – Generate random numbers/values
Python
import random print(random.random()) # random float 0.0 to 1.0 print(random.randint(1, 100)) # random integer 1–100 print(random.choice(["apple", "banana", "mango"])) # random fruit print(random.shuffle([1,2,3,4,5])) # shuffles list in place
3. datetime – Work with dates and times
Python
from datetime import datetime, date, timedelta # Current date & time now = datetime.now() print(now) # e.g. 2026-03-05 13:45:22.123456 # Format date print(now.strftime("%d %B %Y")) # 05 March 2026 print(now.strftime("%H:%M %p")) # 01:45 PM # Create specific date birthday = date(2000, 12, 15) print(birthday) # 2000-12-15 # Add/subtract days future = now + timedelta(days=30) print(future.date()) # 30 days from today
Quick Tip: These three modules are used in almost every real project!
13.4 Create Your Own Module
Very easy — just make a .py file and import it.
Step 1: Create a file named mymodule.py (in the same folder)
Python
# mymodule.py def greet(name): return f"Hello, {name}! Welcome to Python." def square(num): return num * num PI = 3.14159 print("This runs when module is imported") # runs only once
Step 2: Use it in another file (e.g., main.py)
Python
# main.py import mymodule print(mymodule.greet("Anshuman")) # Hello, Anshuman! Welcome to Python. print(mymodule.square(7)) # 49 print(mymodule.PI) # 3.14159
Alternative ways to import your module
Python
from mymodule import greet, square print(greet("Rahul")) # Hello, Rahul! Welcome to Python. print(square(10)) # 100 # or with alias import mymodule as mm print(mm.greet("Priya"))
Important Notes:
Module name = filename without .py
Code at the top level of module runs only once (when first imported)
To prevent code from running when imported, use this common pattern:
Python
# mymodule.py def greet(name): return f"Hello, {name}!" if name == "__main__": # This block runs only when you run the file directly # Not when imported print("This is running directly") print(greet("Test"))
Mini Project – Your Own Utility Module Create utils.py:
Python
# utils.py def celsius_to_fahrenheit(c): return (c 9/5) + 32 def is_prime(n): if n <= 1: return False for i in range(2, int(n*0.5) + 1): if n % i == 0: return False return True
Then use it:
Python
# main.py import utils print(utils.celsius_to_fahrenheit(30)) # 86.0 print(utils.is_prime(17)) # True print(utils.is_prime(15)) # False
This completes the full Modules section — now you can organize and reuse code like a professional!
Mini Projects & Practice Ideas. These small projects combine everything you've learned so far (variables, input/output, conditionals, loops, lists, dictionaries, functions, modules, etc.) — perfect for practice and building confidence!
All projects include full code with comments, explanations, sample output, and ideas to improve them.
14. Mini Projects & Practice Ideas
Build these projects step-by-step. They are designed to be simple at first but expandable.
14.1 Calculator Program
A simple console-based calculator that performs basic operations.
Features:
Add, subtract, multiply, divide
Handle division by zero
Loop until user exits
Full Code:
Python
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x y def divide(x, y): if y == 0: return "Error! Division by zero." return x / y operations = { '+': add, '-': subtract, '': multiply, '/': divide } print("=== Simple Calculator (2026 Edition) ===") print("Operations: + - /") print("Type 'exit' to quit\n") while True: num1_input = input("Enter first number: ").strip() if num1_input.lower() == 'exit': print("Goodbye!") break try: num1 = float(num1_input) except ValueError: print("Invalid number! Try again.") continue op = input("Enter operator (+ - /): ").strip() if op not in operations: print("Invalid operator!") continue try: num2 = float(input("Enter second number: ")) except ValueError: print("Invalid number!") continue result = operations[op](num1, num2) print(f"{num1} {op} {num2} = {result}\n")
Sample Output:
text
=== Simple Calculator (2026 Edition) === Operations: + - / Type 'exit' to quit Enter first number: 25 Enter operator (+ - /): Enter second number: 4 25.0 4.0 = 100.0 ... Enter first number: exit Goodbye!
Improvements to try:
Add more operations (power **, modulo %, square root)
Keep history of calculations
Use eval() cautiously for advanced mode
14.2 Guess the Number Game
Computer picks a random number — user guesses it.
Features:
Hints (too high / too low)
Count attempts
Uses random module
Full Code:
Python
import random print("=== Guess the Number Game ===") print("I'm thinking of a number between 1 and 100.") print("Can you guess it?\n") secret_number = random.randint(1, 100) attempts = 0 while True: try: guess = int(input("Your guess: ")) attempts += 1 if guess == secret_number: print(f"Congratulations! You guessed it in {attempts} attempts! 🎉") break elif guess < secret_number: print("Too low! Try higher.") else: print("Too high! Try lower.") except ValueError: print("Please enter a valid number!")
Sample Output:
text
=== Guess the Number Game === I'm thinking of a number between 1 and 100. Can you guess it? Your guess: 50 Too high! Try lower. Your guess: 25 Too low! Try higher. ... Your guess: 42 Congratulations! You guessed it in 7 attempts! 🎉
Improvements:
Add difficulty levels (1-10, 1-100, 1-1000)
Limit maximum attempts
Play again option
14.3 To-Do List (using lists/dictionaries)
A command-line to-do list manager.
Features:
Add, view, remove tasks
Uses list of dictionaries for better structure
Full Code:
Python
todo_list = [] print("=== To-Do List Manager ===") while True: print("\n1. Add Task") print("2. View Tasks") print("3. Remove Task") print("4. Exit") choice = input("Choose (1-4): ").strip() if choice == '1': task = input("Enter task: ").strip() priority = input("Priority (High/Medium/Low): ").strip().capitalize() todo_list.append({"task": task, "priority": priority, "done": False}) print("Task added!") elif choice == '2': if not todo_list: print("No tasks yet!") else: print("\nYour To-Do List:") for i, item in enumerate(todo_list, 1): status = "✔" if item["done"] else " " print(f"{i}. [{status}] {item['task']} ({item['priority']})") elif choice == '3': if not todo_list: print("No tasks to remove!") else: try: num = int(input("Task number to remove: ")) if 1 <= num <= len(todo_list): removed = todo_list.pop(num - 1) print(f"Removed: {removed['task']}") else: print("Invalid number!") except ValueError: print("Enter a valid number!") elif choice == '4': print("Goodbye! Stay productive!") break else: print("Invalid choice!")
Improvements:
Mark task as done
Save/load from file
Sort by priority
14.4 Password Generator
Generate strong random passwords.
Features:
Custom length
Include letters, numbers, symbols
Full Code:
Python
import random import string print("=== Password Generator ===") length = int(input("Password length (8-32 recommended): ")) use_upper = input("Include uppercase? (y/n): ").lower() == 'y' use_numbers = input("Include numbers? (y/n): ").lower() == 'y' use_symbols = input("Include symbols? (y/n): ").lower() == 'y' characters = string.ascii_lowercase if use_upper: characters += string.ascii_uppercase if use_numbers: characters += string.digits if use_symbols: characters += string.punctuation if not characters: print("No character types selected! Using lowercase only.") characters = string.ascii_lowercase password = ''.join(random.choice(characters) for _ in range(length)) print("\nGenerated Password:", password)
Sample Output:
text
=== Password Generator === Password length (8-32 recommended): 12 Include uppercase? (y/n): y Include numbers? (y/n): y Include symbols? (y/n): y Generated Password: kP9#mL2$xQv8
Improvements:
Generate multiple passwords
Copy to clipboard (use pyperclip module)
Check password strength
14.5 Rock Paper Scissors Game
Classic game against computer.
Full Code:
Python
import random print("=== Rock Paper Scissors ===") print("Choices: rock, paper, scissors") print("Type 'exit' to quit\n") choices = ["rock", "paper", "scissors"] while True: user_choice = input("Your choice: ").lower().strip() if user_choice == 'exit': print("Thanks for playing!") break if user_choice not in choices: print("Invalid choice! Try again.") continue computer_choice = random.choice(choices) print(f"Computer chose: {computer_choice}") if user_choice == computer_choice: print("It's a tie!") elif (user_choice == "rock" and computer_choice == "scissors") or \ (user_choice == "paper" and computer_choice == "rock") or \ (user_choice == "scissors" and computer_choice == "paper"): print("You win! 🎉") else: print("Computer wins!")
Sample Output:
text
Your choice: rock Computer chose: scissors You win! 🎉
Improvements:
Keep score (wins, losses, ties)
Add "lizard spock" variant
Best of 3/5 rounds
Final Tip for All Projects:
Run them in VS Code or any editor
Add error handling (try-except) everywhere
Make them prettier with colors (use colorama module later)
Share your versions on GitHub for portfolio!
These projects will help solidify your Python basics.
15. Best Practices & Next Steps
You’ve learned the fundamentals — now focus on writing clean, professional Python code and planning your next journey.
15.1 Naming Conventions (PEP 8)
PEP 8 is Python’s official style guide — follow it to make your code readable and consistent with most Python developers.
Key Naming Rules:
TypeConventionExampleCorrect?Variable / Functionsnake_caseuser_name, calculate_totalYesConstantUPPER_CASE_WITH_UNDERSCORESMAX_USERS, PI_VALUEYesClassCamelCaseUserProfile, BankAccountYesModule / File namesnake_case.pyuser_utils.py, data_processor.pyYesSingle leading underscoreInternal use (private)_internal_helperCommonDouble leading underscoreName mangling (advanced)__private_methodAdvanced
Quick PEP 8 Tips:
Lines ≤ 79 characters (or 120 max in modern projects)
4 spaces indentation (never tabs)
Spaces around operators: x = y + 2 (not x=y+2)
No spaces inside parentheses: func(arg1, arg2) (not func( arg1, arg2 ))
One blank line between functions/classes, two between top-level functions
Example – Good vs Bad
Python
# Bad UserAge=25 def CalculateArea(r):return 3.14*r*r # Good (PEP 8) user_age = 25 def calculate_area(radius): return 3.14159 radius radius
Tool to help: Install black formatter or use VS Code’s built-in formatter with Python extension.
15.2 Writing Readable Code
“Code is read much more often than it is written.” — Follow these rules:
Use meaningful namestotal_price > tp, calculate_area > f
Keep functions small One function = one responsibility (ideally < 20–30 lines)
Write comments only when needed Explain why, not what
Python
# Good comment # Adjust for Indian GST 18% price_with_tax = price * 1.18 # Bad (obvious) # add 1 to count count += 1
Use blank lines wisely Separate logical blocks
Follow DRY (Don’t Repeat Yourself) If you copy-paste code → make a function!
Handle errors gracefully Use try-except instead of letting program crash
Readable Example:
Python
def get_final_price(base_price, discount_percent=0, tax_rate=0.18): """ Calculate final price after discount and tax. Default tax is 18% (GST in India). """ discounted = base_price (1 - discount_percent / 100) final = discounted (1 + tax_rate) return round(final, 2)
15.3 Common Beginner Mistakes to Avoid
MistakeWhy it's badHow to fixUsing global too muchMakes code hard to understand/debugPass variables as parametersMutable default argumentsUnexpected behaviorUse None and initialize insidefrom module import *Name conflicts, hard to traceImport specific or use aliasNot handling exceptionsProgram crashes on bad inputUse try-except blocksComparing with is instead of ==Wrong for values (except None/True)Use == for value, is for identityModifying list while loopingSkips items or errorsLoop over copy or use list comprehensionForgetting to convert input()"25" + 1 → errorUse int(input()), float(input())Long lines / no formattingHard to readFollow PEP 8, use black formatter
Mutable Default Argument Trap Example (Common Bug):
Python
def add_item(item, my_list=[]): # Dangerous! my_list.append(item) return my_list print(add_item(1)) # [1] print(add_item(2)) # [1, 2] ← unexpected!
Correct Way:
Python
def add_item(item, my_list=None): if my_list is None: my_list = [] my_list.append(item) return my_list
15.4 What to Learn After Basics (file handling, OOP, libraries…)
You now know the core of Python — here’s the natural next path:
File Handling Read/write text files, CSV, JSON open(), with statement, json module
Object-Oriented Programming (OOP) Classes, objects, inheritance, encapsulation init, self, @property, super()
Popular Libraries & Ecosystems
Data: pandas, numpy, matplotlib
Web: requests, flask/fastapi, beautifulsoup
Automation: selenium, pyautogui
AI/ML: scikit-learn, tensorflow/pytorch (basics)
Error Handling & Debuggingtry-except-else-finally, logging, pdb debugger
Virtual Environments & pipvenv, requirements.txt, pip install
Git & GitHub Version control — essential for real projects
Projects Build: CLI app, web scraper, simple website (Flask), data dashboard, automation script
Suggested Learning Path (2026):
Weeks 1–2 → File I/O + Exception Handling
Weeks 3–5 → OOP (classes & inheritance)
Weeks 6+ → Pick one domain: Data Analysis (pandas) or Web (Flask/FastAPI)
15.5 Recommended Resources & Practice Platforms
Free Learning Resources (2026 Updated):
Official Python Tutorial: https://docs.python.org/3/tutorial/
Automate the Boring Stuff with Python (free online book): https://automatetheboringstuff.com/
Corey Schafer YouTube Channel (excellent explanations)
freeCodeCamp Python Course (YouTube – 4+ hours)
Python Crash Course book (Eric Matthes)
Practice Platforms:
PlatformBest ForDifficultyFree?LeetCodeAlgorithms & interviewsEasy → HardMostly freeHackerRankPython track + domainsBeginner → ProFreeCodewarsFun, gamified katas8kyu → 1kyuFreeExercismPython track with mentoringBeginnerFreeProject EulerMath + programming problemsMedium → HardFreeReplit / Google ColabQuick testing & sharing projectsAll levelsFree
Final Advice from Anshuman’s Tutorial: Code every day — even 30 minutes. Build real projects → put them on GitHub. Read other people’s code → ask questions on Stack Overflow or Reddit (r/learnpython). You’ve completed Python Basics — you’re ready to build amazing things in 2026! 🚀
Congratulations! 🎉 This ends the full Python Basics – Made Easy, Fun & Practical tutorial.
Free Reading Alert! All my books are FREE on Kindle Unlimited or eBooks just ₹145!
Check now: https://www.amazon.in/stores/Anshuman-Mishra/author/B0DQVNPL7P
Start reading! 🚀
फ्री रीडिंग का मौका! मेरी सारी किताबें Kindle Unlimited में FREE या ईबुक सिर्फ ₹145 में!
अभी देखें: https://www.amazon.in/stores/Anshuman-Mishra/author/B0DQVNPL7P पढ़ना शुरू करें! 🚀🚀
FAQs
What is this site?
This site offers Python tutorials and study notes to help learners.
Who is it for?
It's designed for beginners and intermediate Python users seeking clear guidance.
How are tutorials structured?
Tutorials break down concepts into simple steps with examples, making complex topics easier to grasp.
Are notes downloadable?
Yes, study notes can be downloaded for offline review anytime.
Is prior experience needed?
No prior experience is required; the content starts from basics.
Can I ask questions if stuck?
Absolutely! You can reach out via the contact page for help with any topic.
These Python notes made complex concepts feel simple and clear.
Amy K.
★★★★★
ibm.anshuman@gmail.com
© 2026 CodeForge AI | Privacy Policy |Terms of Service | Contact | Disclaimer | 1000 university college list












