Untitled flipbook
>>> print('Hello, World!') Hello, World! >>> for i in range(3): ... print(i) 0 1 2 BEGINNER FRIENDLY | STEP BY STEP | HANDS-ON Python Programming from Zero A Complete Beginner's Guide to Learning Python Step by Step AI CREATION 15 chapters | 150+ code examples | practice exercises | interview questions
Python Programming from Zero 2AI CREATION About This Book Welcome! This book was written for people who have never programmed before. You do not need a technical background, a special computer, or any paid software. Everything in this book works on a normal Windows, macOS or Linux computer, and everything you need is free. Each chapter explains one idea in plain language, shows short working examples, points out the mistakes beginners commonly make, and ends with practice exercises. Type the examples yourself instead of copying and pasting. Typing builds the habit, and the errors you run into are where most of the learning happens. How to use this book: read a chapter, type every example, change the example to see what happens, then try the exercises before looking at the sample solutions in Chapter 15. Aim for 30 to 45 minutes a day rather than one long weekend session. Python version: the examples use Python 3 (3.10 or newer works for everything here). Copyright: All rights reserved. This eBook is for personal use. Please do not copy, resell or share the file. If you enjoyed it, a recommendation to a friend who wants to learn Python is the best compliment.
Python Programming from Zero 3AI CREATION Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41. Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82. Installing Python and Setting Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133. Python Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194. Data Types and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265. Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336. Lists, Tuples and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417. Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478. Loops in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6110. Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6811. File Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7512. Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8213. Practical Python Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9114. Common Errors and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 10015. Exercises and Interview Questions
Python Programming from Zero 4AI CREATION CHAPTER 1 Introduction to Python What is programming? A computer is very fast but not very smart. It does exactly what it is told, nothing more and nothing less. Programming is the skill of writing clear, step-by-step instructions that a computer can follow. Those instructions are called a program or code. You already know the idea from daily life. A recipe is a list of steps: boil water, add rice, wait 15 minutes, drain. A program is a recipe for a computer. The difference is that a computer has no common sense, so every step must be written precisely. What is Python? Python is a programming language created by Guido van Rossum and first released in 1991. It was designed to be easy to read and easy to write. Compare how the same idea looks in plain English and in Python: age = 18 if age >= 18: print("You can vote") OUTPUT You can vote Even if you have never coded, you can probably guess what this does. That readability is the main reason Python is the first language recommended to beginners, and also the reason professionals keep using it. Why learn Python? • Easy to learn. The syntax (the grammar of the language) is short and clean. • Very popular. Python is consistently ranked among the most used languages in the world, so there are plenty of tutorials, answers and jobs. • Free and open source. You can download and use it at no cost. • Works everywhere. Windows, macOS and Linux all run Python. • Huge library collection. Ready-made code exists for almost everything, from websites to data analysis.
Python Programming from Zero 5AI CREATION What can you build with Python? Area What Python is used for Popular tools Web development Websites and web apps Django, Flask, FastAPI Data analysis Cleaning, exploring and charting data pandas, matplotlib Machine learning and AI Models that learn from data scikit-learn, TensorFlow, PyTorch Automation Renaming files, sending emails, filling spreadsheets Built-in modules, openpyxl Games Simple 2D games pygame Scientific computing Maths, simulations, research NumPy, SciPy Cybersecurity and networking Scanning tools and scripts socket, scapy You do not need to learn all of these. This book teaches the core language, which is the foundation for every one of them. How does Python run your code? Python is an interpreted language. When you run a program, a piece of software called the Python interpreter reads your code line by line and carries out the instructions. You do not need a separate step to convert your code into a machine program first. Here is the full journey of a Python program: 1. You write instructions in a text file that ends with .py. 2. You ask the interpreter to run the file. 3. The interpreter reads the code from top to bottom and executes each line. 4. If it finds a mistake, it stops and shows an error message that tells you what went wrong and where. Your first look at a program Do not worry about installing anything yet. That is the next chapter. For now, just read these examples and notice how simple they look. print("Hello, World!") OUTPUT Hello, World! print() is a built-in function. It displays whatever you place inside the brackets. The text inside quotation marks is called a string. print("My name is Asha") print("I am learning Python")
Python Programming from Zero 6AI CREATION print(2 + 3) OUTPUT My name is Asha I am learning Python 5 Notice that print(2 + 3) shows 5 instead of the text "2 + 3". Python calculated the sum first. Text needs quotation marks. Numbers and calculations do not. Comments A comment is a note for humans that Python ignores. It starts with a # symbol. # This line is a comment and is ignored print("Comments help explain code") # This comment is at the end of a line OUTPUT Comments help explain code TIP Good comments explain why you did something, not what the code already says. Write comments for the future you who has forgotten everything. Python 2 versus Python 3 You may see old tutorials that mention Python 2. It was retired in 2020 and is no longer supported. Everything in this book is Python 3. If a tutorial uses print "hello" without brackets, it is old Python 2 code. Skip it. Common beginner worries • "I am bad at maths." Programming uses far less maths than people think. Everyday arithmetic is enough for most tasks. • "I am too old or too late." People of every age and background learn Python. Consistency matters more than talent. • "I will break my computer." Beginner programs cannot harm your computer. The worst that happens is an error message. • "I need to memorise everything." Nobody does. Professionals look things up daily. Understanding ideas matters more than memorising syntax. NOTE The fastest way to learn is to write code every day, even for 20 minutes, and to build small things you find interesting.
Python Programming from Zero 7AI CREATION Chapter summary • Programming means giving a computer precise step-by-step instructions. • Python is a readable, free and popular language used in many fields. • Python is interpreted: it runs your code line by line. • print() shows output, and # starts a comment. • This book uses Python 3. Practice Exercises 1. In your own words, explain what a program is. Use a real-life example other than a recipe. 2. List three fields where Python is used and name one tool for each. 3. What is the difference between print("5 + 5") and print(5 + 5)? Predict the output of each, then check in Chapter 2 once Python is installed. 4. Write down a comment line explaining what the line print("Welcome") does. 5. Find one job advertisement that mentions Python. What other skills does it ask for?
Python Programming from Zero 8AI CREATION CHAPTER 2 Installing Python and Setting Up What you need You need three things: Python itself, a place to type your code, and a way to run it. All three are free. This chapter walks through each one, step by step. Step 1: Check whether Python is already installed Some computers already have Python. Open a terminal and type the command below. • Windows: press the Windows key, type cmd, and press Enter to open the Command Prompt. • macOS: open Spotlight (Command + Space), type Terminal, and press Enter. • Linux: press Ctrl + Alt + T. python --version On macOS and Linux the command is often python3 --version. If you see something like Python 3.12.4, you already have Python 3. If you see an error or a version starting with 2, install a new version as shown next. Step 2: Download Python 1. Open your browser and go to python.org. 2. Click Downloads. The website detects your system and offers the latest version. 3. Download the installer and open it. Step 3: Install on Windows 1. Run the downloaded .exe file. 2. Tick the box that says "Add python.exe to PATH". This is the most important step. It lets you run Python from any folder. 3. Click Install Now and wait for it to finish. 4. Close the window when it says "Setup was successful". COMMON MISTAKE Forgetting to tick "Add python.exe to PATH" is the number one beginner problem. If you get "python is not recognized as an internal or external command", re-run the installer, choose Modify or Repair, and make sure that box is ticked.
Python Programming from Zero 9AI CREATION Step 3 (alternative): Install on macOS 1. Open the downloaded .pkg file and follow the prompts. 2. When finished, open Terminal and type python3 --version to confirm. 3. On macOS you will usually type python3 instead of python. Step 3 (alternative): Install on Linux Most Linux systems already include Python 3. If not, use your package manager. On Ubuntu or Debian: sudo apt update sudo apt install python3 python3-pip Step 4: Verify the installation Open a new terminal window and type: python --version OUTPUT Python 3.12.4 Your version number may be different, which is fine as long as it starts with 3. If it works, congratulations. Python is installed. Step 5: Try the interactive shell Python has an interactive shell (also called the REPL, short for Read-Evaluate-Print Loop). It lets you type one line of code and see the result at once. It is perfect for experiments. Type python (or python3) in the terminal and press Enter. You will see a prompt that looks like >>>. >>> print("Hello, World!") Hello, World! >>> 5 + 7 12 >>> "Python" * 3 'PythonPythonPython' >>> exit() In the shell you can type just 5 + 7 and Python shows the answer without needing print(). Type exit() and press Enter to leave the shell. TIP The interactive shell is the quickest way to test a small idea. When you wonder "what happens if I do this?", just try it there.
Python Programming from Zero 10AI CREATION Step 6: Choose a code editor A shell is great for one-liners, but real programs are saved in files. You need a code editor, a program for writing code. Here are three good free options: Editor Best for Notes IDLE Absolute beginners Comes with Python. Simple and nothing extra to install. Visual Studio Code (VS Code) Beginners who want to grow Free, popular, and has a Python extension with helpful hints. Thonny Learning and debugging Made for beginners and shows step-by-step how code runs. If you want the smoothest start, pick Thonny or VS Code. In VS Code, install the extension named "Python" from Microsoft after you install the editor. Avoid using Notepad or Word. Word processors add hidden formatting that breaks code. Step 7: Write and run your first program 1. Create a new folder on your computer called python_book. 2. Open your editor and create a new file. 3. Type the following lines: print("Hello, World!") print("This is my first Python program.") 4. Save the file inside python_book with the name hello.py. The .py ending tells your computer it is a Python file. 5. Run the file. In your editor, click the Run button (a triangle). Or in the terminal, go to the folder and type: cd python_book python hello.py OUTPUT Hello, World! This is my first Python program. You have just written and run your first program. Running from the terminal: the basics Here are the few terminal commands you need. Command What it does cd folder_name Move into a folder
Python Programming from Zero 11AI CREATION Command What it does cd .. Go up one folder dir (Windows) or ls (macOS/Linux) List the files in the current folder python file.py Run a Python file What is pip? pip is Python's package installer. It downloads extra code, called packages, written by other people. You will use it in Chapter 12. Check that it works: pip --version To install a package, for example one called requests, you would type pip install requests. On macOS and Linux you may need to type pip3 instead of pip. Virtual environments (a quick introduction) As you build more projects, you will want each project to keep its own packages, separate from the others. A virtual environment does this. You do not need it today, but here is how it looks so it will not be strange later: python -m venv myenv myenv\Scripts\activate (Windows) source myenv/bin/activate (macOS and Linux) When the environment is active, you will see (myenv) at the start of your terminal line. Type deactivate to leave it. Troubleshooting • "python is not recognized" (Windows): Python was not added to PATH. Re-run the installer and tick that box. • "command not found: python" (macOS or Linux): try python3 instead. • "No such file or directory": you are in the wrong folder. Use cd to go to the folder that contains your file. • A file named hello.py.txt: your system is hiding file extensions. Turn on "show file extensions" in your file manager and rename the file. • Nothing appears when you run the file: make sure you saved it first and that you actually used print().
Python Programming from Zero 12AI CREATION Chapter summary • Python and a code editor are both free to download. • On Windows, remember to tick "Add python.exe to PATH". • python --version confirms the installation. • The interactive shell (>>>) is great for quick experiments. • Programs are saved in .py files and run with python filename.py. • pip installs extra packages, and virtual environments keep projects separate. Practice Exercises 1. Install Python and write down your version number. 2. Open the interactive shell and calculate 15 * 4, 100 / 8 and 2 ** 5. What does each give? 3. Create about_me.py that prints your name, your city and one reason you want to learn Python. 4. In the shell, type print("5 + 5") and then print(5 + 5). Compare the results with your prediction from Chapter 1. 5. Deliberately make a mistake: type pritn("Hello") and read the error message. What does Python say?
Python Programming from Zero 13AI CREATION CHAPTER 3 Python Syntax and Variables What is syntax? Syntax is the set of rules for writing valid Python, like grammar in a spoken language. If you break a rule, Python shows a SyntaxError and refuses to run the program. The good news is that Python's rules are few and consistent. Statements and lines Each instruction is called a statement. Normally, one statement goes on one line. print("First statement") print("Second statement") print("Third statement") OUTPUT First statement Second statement Third statement Python runs statements in order, from top to bottom. Indentation matters Many languages use curly brackets to group code. Python uses indentation, which means spaces at the start of a line. Code that belongs together is indented by the same amount. The standard is four spaces. temperature = 35 if temperature > 30: print("It is hot") print("Drink water") print("This line always runs") OUTPUT It is hot Drink water This line always runs The two indented lines belong to the if. The last line is not indented, so it runs no matter what.
Python Programming from Zero 14AI CREATION COMMON MISTAKE Inconsistent indentation causes an IndentationError. Do not mix tabs and spaces. Set your editor to insert four spaces when you press Tab. What is a variable? A variable is a name that stores a value. Think of it as a labelled box. You put something in the box and use the label whenever you need it. name = "Asha" age = 25 print(name) print(age) OUTPUT Asha 25 The = sign here does not mean "equals" like in maths. It means assign: take the value on the right and store it in the name on the left. Using variables You can use variables in calculations and in print(). price = 250 quantity = 4 total = price * quantity print("Total cost:", total) OUTPUT Total cost: 1000 A variable can be changed at any time. This is why it is called a variable. score = 10 print(score) score = 20 print(score) score = score + 5 print(score) OUTPUT 10 20 25
Python Programming from Zero 15AI CREATION The line score = score + 5 reads: take the current score, add 5, and store the result back in score. Naming rules Python has strict rules for variable names: • Names can contain letters, digits and underscores. • Names cannot start with a digit. • Names cannot contain spaces or symbols like -, @ or $. • Names are case sensitive: age, Age and AGE are three different variables. • Names cannot be Python keywords such as if, for, while, class or True. Name Valid? Reason student_name Yes Letters and underscore age2 Yes Digit is allowed after the first character 2nd_place No Starts with a digit my-name No Hyphen is not allowed class No Reserved keyword Naming style The Python community uses snake_case for variable names: lowercase words joined by underscores. Choose names that explain themselves. # Hard to understand x = 200 y = 0.18 z = x * y # Much clearer bill_amount = 200 tax_rate = 0.18 tax = bill_amount * tax_rate print(tax) OUTPUT 36.0 TIP A good name saves you from writing a comment. Prefer total_marks over tm.
Python Programming from Zero 16AI CREATION Assigning multiple variables Python lets you assign several variables in one line. a, b, c = 1, 2, 3 print(a, b, c) x = y = 0 print(x, y) OUTPUT 1 2 3 0 0 You can swap two values without a helper variable, which is unusual and handy: first = "tea" second = "coffee" first, second = second, first print(first, second) OUTPUT coffee tea Constants Python has no true constants, but by convention, a name written in capital letters means "do not change this". PI = 3.14159 MAX_ATTEMPTS = 3 print(PI, MAX_ATTEMPTS) OUTPUT 3.14159 3 Getting input from the user The input() function pauses the program and waits for the user to type something. Whatever the user types is returned as text. name = input("What is your name? ") print("Hello,", name) If the user types Ravi, the screen shows: What is your name? Ravi Hello, Ravi
Python Programming from Zero 17AI CREATION More about print() print() can show several values separated by spaces, and you can control the separator and the ending. print("Python", "is", "fun") print("2026", "11", "09", sep="-") print("Loading", end="...") print("done") OUTPUT Python is fun 2026-11-09 Loading...done Formatted strings (f-strings) The easiest way to mix text and variables is an f-string. Put an f before the opening quote and place variables inside curly brackets. name = "Asha" age = 25 print(f"My name is {name} and I am {age} years old.") print(f"Next year I will be {age + 1}.") OUTPUT My name is Asha and I am 25 years old. Next year I will be 26. Multiple lines and long statements Use triple quotes for text that spans several lines: poem = """Roses are red, Violets are blue, Python is easy, And so are you.""" print(poem) OUTPUT Roses are red, Violets are blue, Python is easy, And so are you.
Python Programming from Zero 18AI CREATION Common errors in this chapter COMMON MISTAKE NameError: using a variable before it exists, or misspelling it. print(scor) when you defined score gives NameError: name 'scor' is not defined. COMMON MISTAKE SyntaxError: forgetting a closing quote or bracket, as in print("Hello. Python points to the line where it got confused, but the real mistake may be on the line above. Chapter summary • Syntax is the set of rules for valid Python code. • Indentation (four spaces) groups code together. • A variable stores a value, and = assigns it. • Variable names use letters, digits and underscores, cannot start with a digit, and are case sensitive. • Use snake_case and descriptive names. • input() reads text from the user, and f-strings mix variables into text. Practice Exercises 1. Create variables for your name, age and city. Print them in one sentence using an f-string. 2. Which of these names are invalid and why: total_price, 1st_prize, user name, _count, for? 3. Create length = 8 and width = 5. Calculate and print the area of the rectangle. 4. Swap the values of two variables without using a third variable. 5. Ask the user for their favourite colour with input() and print a friendly reply. 6. Fix the error: print("Hello World).
Python Programming from Zero 19AI CREATION CHAPTER 4 Data Types and Operators What is a data type? Every value in Python has a type that tells Python what kind of data it is and what you can do with it. You can add two numbers, but adding a number to a word makes little sense. Types keep these things apart. The built-in function type() tells you the type of any value. print(type(42)) print(type(3.14)) print(type("hello")) print(type(True)) OUTPUT <class 'int'> <class 'float'> <class 'str'> <class 'bool'> The main basic types Type Name Example Meaning int Integer 7, -3, 1000 Whole numbers float Floating-point 3.14, -0.5, 2.0 Numbers with decimals str String "hello", 'A' Text bool Boolean True, False Yes or no values NoneType None None The absence of a value Integers Integers are whole numbers, positive or negative. Python can handle very large integers without any special effort. students = 30 temperature = -5 population = 1400000000 print(students, temperature, population) print(2 ** 100)
Python Programming from Zero 20AI CREATION OUTPUT 30 -5 1400000000 1267650600228229401496703205376 For readability, you can write large numbers with underscores: 1_400_000_000. Floats Floats are numbers with a decimal point. height = 1.75 price = 99.99 print(height + 0.05) print(price * 2) OUTPUT 1.8 199.98 Computers store decimals in binary, so tiny rounding differences can appear: print(0.1 + 0.2) print(round(0.1 + 0.2, 2)) OUTPUT 0.30000000000000004 0.3 This is normal in every programming language. Use round() when you display results. Strings A string is text inside single or double quotes. Both work the same. city = "Pune" greeting = 'Good morning' print(city, greeting) print("It's easy") print('She said "hello"') OUTPUT Pune Good morning It's easy She said "hello"
Python Programming from Zero 21AI CREATION Booleans A boolean is either True or False. The capital first letter is required. Booleans are the result of comparisons and drive decisions in your programs. print(10 > 5) print(10 == 5) is_raining = False print(is_raining) OUTPUT True False False None None means "no value yet". It is used when something is empty or not set. result = None print(result) print(type(result)) OUTPUT None <class 'NoneType'> Type conversion You can convert a value from one type to another using int(), float(), str() and bool(). print(int("25") + 5) print(float("3.5") * 2) print(str(100) + " rupees") print(int(7.9)) OUTPUT 30 7.0 100 rupees 7 Notice that int(7.9) gives 7. It cuts off the decimal part and does not round. This matters most with input(), which always returns text: age = input("Enter your age: ") next_age = int(age) + 1 print("Next year you will be", next_age)
Python Programming from Zero 22AI CREATION COMMON MISTAKE Trying "5" + 3 gives a TypeError because you cannot add text and a number. Convert first: int("5") + 3. If the text is not a number, as in int("hello"), Python raises a ValueError. Arithmetic operators An operator is a symbol that performs an operation. These are the arithmetic operators: Operator Meaning Example Result + Addition 7 + 2 9 - Subtraction 7 - 2 5 * Multiplication 7 * 2 14 / Division (always a float) 7 / 2 3.5 // Floor division 7 // 2 3 % Remainder (modulus) 7 % 2 1 ** Power 7 ** 2 49 a = 17 b = 5 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print(a ** 2) OUTPUT 22 12 85 3.4 3 2 289 The remainder operator % is very useful. A number is even if n % 2 is 0. print(10 % 2) print(11 % 2) OUTPUT 0 1
Python Programming from Zero 23AI CREATION Order of operations Python follows the same order as maths: brackets first, then powers, then multiplication and division, then addition and subtraction. print(2 + 3 * 4) print((2 + 3) * 4) print(2 ** 3 ** 2) OUTPUT 14 20 512 When in doubt, add brackets. They make the order obvious to readers. Assignment operators These shortcuts update a variable in place. score = 10 score += 5 print(score) score -= 3 print(score) score *= 2 print(score) score //= 4 print(score) OUTPUT 15 12 24 6 Comparison operators Comparison operators compare two values and give True or False. Operator Meaning Example Result == Equal to 5 == 5 True != Not equal to 5 != 3 True > Greater than 5 > 8 False < Less than 5 < 8 True >= Greater than or equal 5 >= 5 True <= Less than or equal 4 <= 3 False
Python Programming from Zero 24AI CREATION COMMON MISTAKE Do not confuse = with ==. A single = assigns a value. Double == compares two values. Logical operators Logical operators combine conditions: and, or and not. age = 22 has_id = True print(age >= 18 and has_id) print(age < 18 or has_id) print(not has_id) OUTPUT True True False • and is True only when both sides are True. • or is True when at least one side is True. • not flips True to False and the other way round. Membership and identity operators The in operator checks whether something is inside another value: print("a" in "banana") print("z" in "banana") print(3 not in [1, 2, 3]) OUTPUT True False False Useful built-in functions for numbers print(abs(-12)) print(round(3.14159, 2)) print(max(4, 9, 2)) print(min(4, 9, 2)) print(pow(2, 10)) print(divmod(17, 5)) OUTPUT 12 3.14
Python Programming from Zero 25AI CREATION 9 2 1024 (3, 2) Chapter summary • The main types are int, float, str, bool and None. Use type() to check. • Convert with int(), float() and str(). input() always returns text. • Arithmetic: + - * / // % **. • Comparisons give True or False. • Logical operators and, or and not combine conditions. • = assigns, == compares. Practice Exercises 1. Predict, then check: 7 // 2, 7 % 2, 7 / 2, 2 ** 4. 2. Ask the user for two numbers and print their sum, difference, product and quotient. 3. Convert a temperature of 36.6 Celsius to Fahrenheit using F = C * 9 / 5 + 32. 4. Given total_seconds = 3725, calculate hours, minutes and seconds using // and %. 5. What does bool(0), bool(1) and bool("") give? Test them. 6. Write one expression that is True only when a number n is between 10 and 20 (inclusive).
Python Programming from Zero 26AI CREATION CHAPTER 5 Working with Strings What is a string? A string is a sequence of characters: letters, digits, spaces and symbols. You will work with strings constantly, because almost all human data (names, messages, addresses) is text. word = "Python" sentence = "Learning Python is fun!" empty = "" print(word) print(sentence) print(len(word)) print(len(empty)) OUTPUT Python Learning Python is fun! 6 0 len() returns the number of characters in a string. Indexing: getting one character Every character has a position called an index. Counting starts at 0, not 1. P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 word = "Python" print(word[0]) print(word[3]) print(word[-1]) print(word[-2]) OUTPUT P h n o Negative indexes count from the end. -1 is the last character.
Python Programming from Zero 27AI CREATION COMMON MISTAKE Asking for an index that does not exist, like word[10], raises an IndexError: string index out of range. Slicing: getting part of a string A slice takes a piece of a string. The format is [start:stop]. It includes start but stops just before stop. word = "Programming" print(word[0:3]) print(word[3:7]) print(word[:4]) print(word[4:]) print(word[-3:]) print(word[::2]) print(word[::-1]) OUTPUT Pro gram Prog ramming ing Pormig gnimmargorP • [:4] means from the start to index 4. • [4:] means from index 4 to the end. • [::2] takes every second character. • [::-1] reverses the string. Strings cannot be changed Strings are immutable: once created, you cannot change a character in place. To "change" a string, build a new one. word = "Python" # word[0] = "J" <- this would cause a TypeError new_word = "J" + word[1:] print(new_word) OUTPUT Jython
Python Programming from Zero 28AI CREATION Joining and repeating first = "Good" second = "Morning" print(first + " " + second) print("ha" * 3) print("-" * 20) OUTPUT Good Morning hahaha -------------------- Changing case text = "python is Fun" print(text.upper()) print(text.lower()) print(text.title()) print(text.capitalize()) print(text.swapcase()) OUTPUT PYTHON IS FUN python is fun Python Is Fun Python is fun PYTHON IS fUN Cleaning strings User input often has extra spaces. strip() removes spaces from both ends. raw = " hello world " print("[" + raw.strip() + "]") print("[" + raw.lstrip() + "]") print("[" + raw.rstrip() + "]") OUTPUT [hello world] [hello world ] [ hello world]
Python Programming from Zero 29AI CREATION Searching in strings text = "the quick brown fox jumps over the lazy dog" print(text.find("quick")) print(text.find("cat")) print(text.count("the")) print(text.startswith("the")) print(text.endswith("dog")) print("fox" in text) OUTPUT 4 -1 2 True True True find() returns the index of the first match, or -1 if the text is not found. Replacing text message = "I like tea. Tea is great." print(message.replace("tea", "coffee")) print(message.replace("Tea", "Coffee")) OUTPUT I like coffee. Tea is great. I like tea. Coffee is great. Replacement is case sensitive. The original message is not changed, because strings are immutable. replace() returns a new string. Splitting and joining split() breaks a string into a list of pieces. join() does the opposite. sentence = "apples,bananas,cherries" fruits = sentence.split(",") print(fruits) words = "Python is easy to learn".split() print(words) print(len(words)) print("-".join(["2026", "11", "09"])) print(" ".join(words)) OUTPUT ['apples', 'bananas', 'cherries'] ['Python', 'is', 'easy', 'to', 'learn'] 5
Python Programming from Zero 30AI CREATION 2026-11-09 Python is easy to learn Checking what a string contains print("12345".isdigit()) print("hello".isalpha()) print("hello123".isalnum()) print(" ".isspace()) print("HELLO".isupper()) print("hello".islower()) OUTPUT True True True True True True Escape characters Some characters need a special code that starts with a backslash. Code Meaning \n New line \t Tab \\ A backslash \" A double quote inside double quotes print("Line one\nLine two") print("Name:\tAsha") print("She said \"Hi\"") print("C:\\Users\\Asha") OUTPUT Line one Line two Name: Asha She said "Hi" C:\Users\Asha
Python Programming from Zero 31AI CREATION Formatting strings You met f-strings in Chapter 3. They can also control how numbers look. price = 1234.5678 name = "Notebook" print(f"{name}: {price:.2f}") print(f"{name}: {price:,.1f}") print(f"{42:05d}") print(f"{0.256:.1%}") print(f"{name:>12}|") print(f"{name:<12}|") print(f"{name:^12}|") OUTPUT Notebook: 1234.57 Notebook: 1,234.6 00042 25.6% Notebook| Notebook | Notebook | • .2f shows two decimal places. • , adds thousands separators. • 05d pads with zeros to width 5. • % shows a percentage. • >, < and ^ align right, left and centre. A practical example Here is a small program that cleans up a name typed by a user. raw_name = " rAVI kUMAR " clean = " ".join(raw_name.split()).title() print(clean) print(f"Initials: {clean[0]}.{clean.split()[1][0]}.") OUTPUT Ravi Kumar Initials: R.K. Chapter summary • Strings are sequences of characters. Indexing starts at 0. • Slicing [start:stop:step] extracts parts. [::-1] reverses. • Strings are immutable, so methods return new strings. • Useful methods: upper, lower, strip, find, count, replace, split, join. • Use escape characters like \n and \t.
Python Programming from Zero 32AI CREATION • f-strings can format numbers neatly. Practice Exercises 1. Ask the user for their name and print it in uppercase, then the number of letters. 2. Check whether a word typed by the user is a palindrome (reads the same backwards), such as "madam". 3. Given "python programming", print it in title case and print only the first word. 4. Count how many vowels are in a sentence entered by the user. 5. Take "2026-11-09" and print the day, month and year separately using split("-"). 6. Replace every space in a sentence with an underscore. 7. Print the number 3.14159 rounded to 3 decimal places using an f-string.
Python Programming from Zero 33AI CREATION CHAPTER 6 Lists, Tuples and Dictionaries Why collections? So far each variable held one value. Real programs handle many values: the marks of 40 students, a shopping list, the details of a customer. Python provides collections to store many values under one name. This chapter covers the three most important ones: lists, tuples and dictionaries. It also introduces sets. Lists A list is an ordered, changeable collection. Write it with square brackets and separate items with commas. fruits = ["apple", "banana", "cherry"] marks = [78, 85, 92, 67] mixed = ["Asha", 25, True, 3.5] empty = [] print(fruits) print(len(fruits)) print(type(fruits)) OUTPUT ['apple', 'banana', 'cherry'] 3 <class 'list'> Accessing list items Lists use the same indexing and slicing as strings: the first index is 0 and negative indexes count from the end. fruits = ["apple", "banana", "cherry", "mango", "grape"] print(fruits[0]) print(fruits[-1]) print(fruits[1:3]) print(fruits[:2]) print(fruits[::2]) OUTPUT apple grape ['banana', 'cherry'] ['apple', 'banana']
Python Programming from Zero 34AI CREATION ['apple', 'cherry', 'grape'] Changing a list Unlike strings, lists are mutable: you can change them after creating them. fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" print(fruits) fruits.append("mango") print(fruits) fruits.insert(0, "kiwi") print(fruits) fruits.remove("cherry") print(fruits) last = fruits.pop() print(last) print(fruits) del fruits[0] print(fruits) OUTPUT ['apple', 'blueberry', 'cherry'] ['apple', 'blueberry', 'cherry', 'mango'] ['kiwi', 'apple', 'blueberry', 'cherry', 'mango'] ['kiwi', 'apple', 'blueberry', 'mango'] mango ['kiwi', 'apple', 'blueberry'] ['apple', 'blueberry'] Method What it does append(x) Adds x to the end insert(i, x) Adds x at position i remove(x) Removes the first x pop() Removes and returns the last item (or pop(i) for position i) clear() Removes everything More list operations numbers = [5, 2, 9, 1, 7] print(len(numbers)) print(sum(numbers)) print(max(numbers)) print(min(numbers))
Python Programming from Zero 35AI CREATION print(sorted(numbers)) print(sorted(numbers, reverse=True)) print(numbers) numbers.sort() print(numbers) numbers.reverse() print(numbers) print(numbers.index(9)) print(numbers.count(2)) OUTPUT 5 24 9 1 [1, 2, 5, 7, 9] [9, 7, 5, 2, 1] [5, 2, 9, 1, 7] [1, 2, 5, 7, 9] [9, 7, 5, 2, 1] 0 1 sorted() returns a new list and leaves the original alone. .sort() changes the list itself. Combining lists and checking membership a = [1, 2, 3] b = [4, 5] print(a + b) print(a * 2) print(3 in a) print(10 in a) OUTPUT [1, 2, 3, 4, 5] [1, 2, 3, 1, 2, 3] True False A common trap: copying lists original = [1, 2, 3] alias = original alias.append(4) print(original) safe_copy = original.copy() safe_copy.append(5) print(original) print(safe_copy)
Python Programming from Zero 36AI CREATION OUTPUT [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5] COMMON MISTAKE alias = original does not make a copy. Both names point to the same list. Use .copy() or list(original) when you need an independent copy. Nested lists A list can hold other lists. This is how you represent a table or grid. grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] print(grid[0]) print(grid[1][2]) print(grid[2][0]) OUTPUT [1, 2, 3] 6 7 List comprehensions (a first look) A list comprehension builds a new list in one line. You will love it once you get used to it. squares = [n * n for n in range(1, 6)] print(squares) evens = [n for n in range(10) if n % 2 == 0] print(evens) names = ["asha", "ravi", "meena"] print([name.title() for name in names]) OUTPUT [1, 4, 9, 16, 25] [0, 2, 4, 6, 8] ['Asha', 'Ravi', 'Meena']
Python Programming from Zero 37AI CREATION Tuples A tuple is like a list, but it is immutable: once created it cannot be changed. Write it with round brackets. point = (10, 20) colors = ("red", "green", "blue") print(point[0]) print(colors[-1]) print(len(colors)) print(colors.index("green")) OUTPUT 10 blue 3 1 Trying point[0] = 99 raises a TypeError. Use a tuple when the data should not change, such as coordinates, days of the week or RGB colour values. A tuple with one item needs a trailing comma: (5,). Tuple unpacking person = ("Asha", 25, "Pune") name, age, city = person print(name) print(age) print(city) OUTPUT Asha 25 Pune Dictionaries A dictionary stores data as key-value pairs, like a real dictionary where each word (key) has a meaning (value). Use curly brackets with key: value pairs. student = { "name": "Asha", "age": 21, "course": "Data Science", } print(student) print(student["name"]) print(student.get("age")) print(student.get("phone")) print(student.get("phone", "not given"))
Python Programming from Zero 38AI CREATION OUTPUT {'name': 'Asha', 'age': 21, 'course': 'Data Science'} Asha 21 None not given Use .get() when the key might not exist. student["phone"] would raise a KeyError. Changing a dictionary student = {"name": "Asha", "age": 21} student["age"] = 22 student["city"] = "Pune" print(student) del student["city"] print(student) removed = student.pop("age") print(removed) print(student) OUTPUT {'name': 'Asha', 'age': 22, 'city': 'Pune'} {'name': 'Asha', 'age': 22} 22 {'name': 'Asha'} Assigning to a key that exists updates it. Assigning to a new key adds it. Looping over dictionaries prices = {"tea": 20, "coffee": 35, "juice": 50} print(list(prices.keys())) print(list(prices.values())) print(list(prices.items())) for item, price in prices.items(): print(f"{item} costs {price}") OUTPUT ['tea', 'coffee', 'juice'] [20, 35, 50] [('tea', 20), ('coffee', 35), ('juice', 50)] tea costs 20 coffee costs 35 juice costs 50
Python Programming from Zero 39AI CREATION Nested data Real data is often a list of dictionaries, which is the same shape as a table of rows. students = [ {"name": "Asha", "marks": 88}, {"name": "Ravi", "marks": 72}, {"name": "Meena", "marks": 95}, ] for s in students: print(s["name"], s["marks"]) best = max(students, key=lambda s: s["marks"]) print("Top scorer:", best["name"]) OUTPUT Asha 88 Ravi 72 Meena 95 Top scorer: Meena Sets A set is an unordered collection of unique items. It removes duplicates automatically. numbers = {1, 2, 3, 3, 2, 1} print(numbers) tags = set(["python", "code", "python", "learn"]) print(sorted(tags)) a = {1, 2, 3, 4} b = {3, 4, 5} print(a & b) print(a | b) print(a - b) OUTPUT {1, 2, 3} ['code', 'learn', 'python'] {3, 4} {1, 2, 3, 4, 5} {1, 2} An empty set must be written set(), because {} creates an empty dictionary. Which collection should I use? Type Ordered Changeable Duplicates Use it for List Yes Yes Allowed A sequence of items that may change
Python Programming from Zero 40AI CREATION Type Ordered Changeable Duplicates Use it for Tuple Yes No Allowed Fixed data like coordinates Dictionary Yes (by insertion) Yes Keys must be unique Looking things up by name Set No Yes Not allowed Unique items and set maths Chapter summary • Lists [ ] are ordered and changeable. Use append, insert, remove, pop and sort. • Tuples ( ) cannot be changed. • Dictionaries {key: value} look values up by key. Use .get() for safe access. • Sets { } hold unique items. • list2 = list1 does not copy. Use .copy(). Practice Exercises 1. Create a list of five of your favourite foods. Add one, remove one, and print it sorted. 2. Given [4, 8, 15, 16, 23, 42], print the sum, the average, the largest and the smallest. 3. Remove the duplicates from [1, 2, 2, 3, 3, 3, 4] using a set. 4. Create a dictionary for a book with the keys title, author and year. Print each pair. 5. Make a list of squares of the numbers 1 to 10 using a list comprehension. 6. Given a list of student dictionaries, print the names of students with marks above 80. 7. Swap the keys and values of {"a": 1, "b": 2}.
Python Programming from Zero 41AI CREATION CHAPTER 7 Conditional Statements Making decisions A program that always does the same thing is not very useful. Real programs make decisions: "If the password is correct, log in. Otherwise, show an error." In Python, decisions are written with if, elif and else. The if statement age = 20 if age >= 18: print("You are an adult") OUTPUT You are an adult The structure has three parts: • The keyword if • A condition that is True or False • A colon : followed by an indented block of code that runs only when the condition is True COMMON MISTAKE Do not forget the colon at the end of the if line, and do not forget to indent the block. Missing either causes a SyntaxError or IndentationError. if and else else runs when the condition is False. age = 15 if age >= 18: print("You can vote") else: print("You cannot vote yet") OUTPUT You cannot vote yet
Python Programming from Zero 42AI CREATION elif: many choices Use elif (short for "else if") to check more than two possibilities. Python checks conditions from top to bottom and runs the first one that is True. marks = 76 if marks >= 90: grade = "A+" elif marks >= 75: grade = "A" elif marks >= 60: grade = "B" elif marks >= 40: grade = "C" else: grade = "Fail" print("Grade:", grade) OUTPUT Grade: A Even though 76 >= 60 is also True, Python stops at the first match. The order of your conditions matters. Using comparison and logical operators age = 25 has_ticket = True if age >= 18 and has_ticket: print("Entry allowed") day = "Sunday" if day == "Saturday" or day == "Sunday": print("It is the weekend") username = "" if not username: print("Username is empty") OUTPUT Entry allowed It is the weekend Username is empty Truthy and falsy values Python treats some values as False in a condition: 0, 0.0, "" (empty string), [], {}, (), set() and None. Almost everything else counts as True. items = [] if items: print("Cart has items")
Python Programming from Zero 43AI CREATION else: print("Cart is empty") name = "Asha" if name: print("Hello", name) OUTPUT Cart is empty Hello Asha Nested if statements You can place an if inside another if. age = 22 has_license = True if age >= 18: if has_license: print("You may drive") else: print("Get a license first") else: print("You are too young to drive") OUTPUT You may drive Deep nesting gets hard to read. The same logic can be written more clearly with and: age = 22 has_license = True if age >= 18 and has_license: print("You may drive") OUTPUT You may drive Comparing text String comparison is case sensitive, so "Yes" is not equal to "yes". Normalise input first: answer = " YES " if answer.strip().lower() == "yes": print("Confirmed") OUTPUT Confirmed
Python Programming from Zero 44AI CREATION Chained comparisons Python lets you write a range check the way you do in maths: score = 55 if 40 <= score < 60: print("Pass class") OUTPUT Pass class The ternary (one-line) if For a simple choice between two values, you can write the decision in one line: age = 17 status = "adult" if age >= 18 else "minor" print(status) OUTPUT minor The match statement Python 3.10 added match, a tidy way to compare one value against many options. day = 3 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case _: print("Another day") OUTPUT Wednesday The underscore _ is the default case, like else. If you use an older Python, use if and elif instead.
Python Programming from Zero 45AI CREATION The pass statement Sometimes you need a block that does nothing yet, such as when you are still planning your code. Python does not allow an empty block, so use pass as a placeholder. age = 30 if age > 18: pass print("Program continues") OUTPUT Program continues Example: a simple login check saved_user = "asha" saved_pass = "python123" username = "asha" password = "python123" if username == saved_user and password == saved_pass: print("Login successful") elif username != saved_user: print("Unknown user") else: print("Wrong password") OUTPUT Login successful Example: leap year A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400. year = 2024 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print(year, "is a leap year") else: print(year, "is not a leap year") OUTPUT 2024 is a leap year
Python Programming from Zero 46AI CREATION Common mistakes COMMON MISTAKE Writing if x = 5: instead of if x == 5:. A single = assigns, so Python reports a SyntaxError. COMMON MISTAKE Writing if x == 1 or 2: and expecting it to check both numbers. Python reads 2 on its own as always True. Write if x == 1 or x == 2: or use if x in (1, 2):. Chapter summary • if, elif and else let programs choose what to do. • Conditions use comparison operators and and, or, not. • Indentation shows which lines belong to which block. • Empty values (0, "", [], None) are falsy. • match (Python 3.10+) is a tidy alternative to many elif lines. Practice Exercises 1. Ask for a number and print whether it is positive, negative or zero. 2. Ask for a number and print whether it is even or odd. 3. Ask for three numbers and print the largest without using max(). 4. Write a grading program: 90+ gives A, 80+ gives B, 70+ gives C, otherwise Fail. 5. Ask for a year and print whether it is a leap year. 6. Build a ticket pricing program: under 5 is free, 5 to 17 costs 50, 18 to 59 costs 100, and 60 or over costs 60. 7. Check whether a password is at least 8 characters and contains at least one digit.
Python Programming from Zero 47AI CREATION CHAPTER 8 Loops in Python Why loops? Imagine printing the numbers 1 to 100. You could write 100 print() lines, or you could write a loop of three lines. A loop repeats a block of code. Python has two kinds: for loops and while loops. The for loop A for loop goes through the items of a sequence one by one. fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit) OUTPUT I like apple I like banana I like cherry In each round, the variable fruit takes the next value from the list. The indented lines are the loop body. You can loop over strings too: for letter in "Python": print(letter) OUTPUT P y t h o n The range() function range() creates a sequence of numbers. for i in range(5): print(i) OUTPUT
Python Programming from Zero 48AI CREATION 0 1 2 3 4 • range(5) gives 0, 1, 2, 3, 4 (stops before 5). • range(2, 6) gives 2, 3, 4, 5. • range(0, 10, 2) gives 0, 2, 4, 6, 8 (step of 2). • range(5, 0, -1) counts down: 5, 4, 3, 2, 1. for i in range(1, 6): print(i, end=" ") print() for i in range(10, 0, -3): print(i, end=" ") print() OUTPUT 1 2 3 4 5 10 7 4 1 Using loops to calculate total = 0 for n in range(1, 11): total += n print("Sum of 1 to 10:", total) OUTPUT Sum of 1 to 10: 55 This pattern is the accumulator: start with an empty total and add to it in each round. Multiplication table number = 7 for i in range(1, 6): print(f"{number} x {i} = {number * i}") OUTPUT 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Python Programming from Zero 49AI CREATION The while loop A while loop repeats as long as a condition stays True. Use it when you do not know in advance how many times you need to repeat. count = 1 while count <= 5: print("Count is", count) count += 1 print("Done") OUTPUT Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done COMMON MISTAKE If the condition never becomes False, the loop runs forever. That is an infinite loop. In the example above, without count += 1 the loop would never end. Press Ctrl + C in the terminal to stop a runaway program. Asking until the answer is valid while loops are ideal for repeating a question until the user gives a good answer. password = "" while password != "python123": password = input("Enter the password: ") print("Access granted") break: leave the loop early for number in range(1, 100): if number % 7 == 0 and number % 5 == 0: print("First multiple of 35:", number) break OUTPUT First multiple of 35: 35
Python Programming from Zero 50AI CREATION continue: skip to the next round for number in range(1, 8): if number % 2 == 0: continue print(number) OUTPUT 1 3 5 7 The else clause on loops A loop can have an else block that runs only if the loop finished without hitting break. number = 29 for i in range(2, number): if number % i == 0: print(number, "is not prime") break else: print(number, "is prime") OUTPUT 29 is prime Nested loops A loop inside a loop runs the inner loop fully for each round of the outer loop. for row in range(1, 5): for col in range(1, row + 1): print("*", end="") print() OUTPUT * ** *** **** A multiplication grid: for i in range(1, 4): for j in range(1, 4): print(i * j, end="\t") print()
Python Programming from Zero 51AI CREATION OUTPUT 1 2 3 2 4 6 3 6 9 enumerate and zip enumerate() gives you the position and the value together. zip() walks through two lists at once. colors = ["red", "green", "blue"] for index, color in enumerate(colors, start=1): print(index, color) names = ["Asha", "Ravi", "Meena"] marks = [88, 72, 95] for name, mark in zip(names, marks): print(name, "scored", mark) OUTPUT 1 red 2 green 3 blue Asha scored 88 Ravi scored 72 Meena scored 95 Looping with a counter and a condition Finding the largest value in a list by hand: numbers = [34, 12, 89, 5, 61] largest = numbers[0] for n in numbers: if n > largest: largest = n print("Largest:", largest) OUTPUT Largest: 89 Example: counting characters text = "mississippi" counts = {} for ch in text: counts[ch] = counts.get(ch, 0) + 1 print(counts) OUTPUT
Python Programming from Zero 52AI CREATION {'m': 1, 'i': 4, 's': 4, 'p': 2} Example: FizzBuzz This classic exercise is also a popular interview question. Print the numbers 1 to 15. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz". for n in range(1, 16): if n % 15 == 0: print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n) OUTPUT 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz for or while? • Use for when you know what you are looping over (a list, a range, a string). • Use while when you repeat until something happens. Common mistakes COMMON MISTAKE Changing a list while looping over it. Loop over a copy (for x in items[:]) or build a new list instead. COMMON MISTAKE Forgetting that range(5) stops at 4, not 5. This "off by one" error is one of the most common in programming.
Python Programming from Zero 53AI CREATION Chapter summary • for loops go through the items of a sequence, and range() makes number sequences. • while loops repeat while a condition is True. Make sure the condition can become False. • break exits a loop, and continue skips to the next round. • Nested loops put one loop inside another. • enumerate() gives index and value, and zip() pairs two lists. Practice Exercises 1. Print the numbers 1 to 20 that are divisible by 3. 2. Calculate the factorial of 6 using a loop (6 x 5 x 4 x 3 x 2 x 1). 3. Print the first 10 numbers of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, and so on. 4. Print a pyramid of stars with 5 rows. 5. Write a number-guessing game that keeps asking until the player guesses the secret number. 6. Count how many words in a sentence start with a capital letter. 7. Print all prime numbers between 1 and 50. 8. Reverse a string using a loop, without using slicing.
Python Programming from Zero 54AI CREATION CHAPTER 9 Functions What is a function? A function is a named block of code that does one job. You write it once and use it as many times as you like. You have already used functions such as print(), len() and input(). Now you will create your own. Functions help you avoid repeating code, break big problems into small pieces, and make programs easier to read and fix. Defining and calling a function Use the keyword def to define a function, then call it by writing its name followed by brackets. def say_hello(): print("Hello!") print("Welcome to Python.") say_hello() say_hello() OUTPUT Hello! Welcome to Python. Hello! Welcome to Python. Defining a function does not run it. The code inside runs only when you call it. Parameters and arguments Parameters are the names in the function definition. Arguments are the actual values you pass when calling. They let a function work with different data. def greet(name): print(f"Hello, {name}!") greet("Asha") greet("Ravi") OUTPUT Hello, Asha! Hello, Ravi!
Python Programming from Zero 55AI CREATION A function can take several parameters: def add(a, b): print(a + b) add(3, 4) add(10, 25) OUTPUT 7 35 Returning a value print() shows a value on the screen, but the function cannot use it afterwards. A return statement sends a value back to the caller, so you can store it or use it in further calculations. def square(n): return n * n result = square(6) print(result) print(square(3) + square(4)) OUTPUT 36 25 When Python reaches return, the function ends immediately. def check_age(age): if age < 0: return "Invalid age" if age >= 18: return "Adult" return "Minor" print(check_age(25)) print(check_age(10)) print(check_age(-3)) OUTPUT Adult Minor Invalid age COMMON MISTAKE A function without a return statement returns None. If you see None in your output, you probably printed the result of a function that only prints, or forgot return.
Python Programming from Zero 56AI CREATION Default parameter values You can give a parameter a default value. It is used when the caller does not provide one. def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Asha")) print(greet("Asha", "Good morning")) OUTPUT Hello, Asha! Good morning, Asha! Parameters with defaults must come after those without. Keyword arguments You can pass arguments by name, so the order does not matter and the call is easier to read. def describe_pet(animal, name, age): return f"{name} is a {age}-year-old {animal}." print(describe_pet("dog", "Bruno", 3)) print(describe_pet(name="Misty", age=2, animal="cat")) OUTPUT Bruno is a 3-year-old dog. Misty is a 2-year-old cat. Returning multiple values A function can return several values, which Python packs into a tuple. def min_max(numbers): return min(numbers), max(numbers) low, high = min_max([4, 9, 1, 7]) print(low, high) OUTPUT 1 9 Variable number of arguments: *args and **kwargs Use *args to accept any number of positional arguments, and **kwargs to accept any number of keyword arguments. def total(*numbers):
Python Programming from Zero 57AI CREATION return sum(numbers) print(total(1, 2)) print(total(5, 10, 15, 20)) def show_profile(**details): for key, value in details.items(): print(f"{key}: {value}") show_profile(name="Asha", city="Pune", job="Analyst") OUTPUT 3 50 name: Asha city: Pune job: Analyst Scope: where variables live A variable created inside a function is local. It exists only while the function runs. A variable created outside functions is global. def calculate(): result = 100 print("Inside:", result) calculate() # print(result) <- NameError: result is not defined here OUTPUT Inside: 100 rate = 0.1 def interest(amount): return amount * rate print(interest(500)) OUTPUT 50.0 A function can read a global variable. To change one you would need the global keyword, but it is better to pass values in as arguments and return results. This keeps functions predictable.
Python Programming from Zero 58AI CREATION Docstrings A docstring is a string in triple quotes right after the def line. It describes what the function does. def area_of_circle(radius): """Return the area of a circle with the given radius.""" return 3.14159 * radius ** 2 print(area_of_circle(5)) print(area_of_circle.__doc__) OUTPUT 78.53975 Return the area of a circle with the given radius. Functions calling functions Small functions can be combined to solve bigger problems. def is_even(n): return n % 2 == 0 def count_evens(numbers): count = 0 for n in numbers: if is_even(n): count += 1 return count print(count_evens([1, 2, 3, 4, 6, 7])) OUTPUT 3 Recursion A recursive function calls itself. It needs a base case that stops the recursion, otherwise it runs forever. def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) print(factorial(5)) OUTPUT 120
Python Programming from Zero 59AI CREATION Lambda functions A lambda is a tiny unnamed function written in one line. It is handy for short jobs, especially with sorted(), map() and filter(). double = lambda x: x * 2 print(double(7)) words = ["banana", "kiwi", "apple", "fig"] print(sorted(words, key=lambda w: len(w))) numbers = [1, 2, 3, 4, 5, 6] print(list(filter(lambda n: n % 2 == 0, numbers))) print(list(map(lambda n: n * n, numbers))) OUTPUT 14 ['fig', 'kiwi', 'apple', 'banana'] [2, 4, 6] [1, 4, 9, 16, 25, 36] Example: a small calculator def calculate(a, b, operation): if operation == "add": return a + b elif operation == "subtract": return a - b elif operation == "multiply": return a * b elif operation == "divide": if b == 0: return "Cannot divide by zero" return a / b return "Unknown operation" print(calculate(10, 5, "add")) print(calculate(10, 5, "divide")) print(calculate(10, 0, "divide")) print(calculate(10, 5, "power")) OUTPUT 15 2.0 Cannot divide by zero Unknown operation
Python Programming from Zero 60AI CREATION Good function habits • Give each function one clear job. • Choose names that start with a verb: calculate_tax, is_valid, get_name. • Prefer returning values over printing inside the function. • Keep functions short enough to read at a glance. • Write a docstring for anything that is not obvious. Common mistakes COMMON MISTAKE Forgetting the brackets when calling. greet refers to the function. greet("Asha") calls it. COMMON MISTAKE Using a mutable default value such as def add_item(item, items=[]). The same list is shared across all calls. Use items=None and create the list inside the function. Chapter summary • Define functions with def, and call them by name with brackets. • Parameters receive arguments, and return sends a value back. • Defaults, keyword arguments, *args and **kwargs make functions flexible. • Variables inside a function are local. • Docstrings document a function, and lambdas are tiny one-line functions. • Recursion means a function calls itself and needs a base case. Practice Exercises 1. Write is_even(n) that returns True when n is even. 2. Write celsius_to_fahrenheit(c) and test it with 0, 37 and 100. 3. Write count_vowels(text) that returns how many vowels the text contains. 4. Write average(*numbers) that accepts any number of values. 5. Write is_palindrome(word) that returns True or False. 6. Write a recursive function sum_to(n) that adds 1 + 2 + ... + n. 7. Write fizzbuzz(n) that returns the correct word or number for a single value n. 8. Rewrite the grade program from Chapter 7 as a function get_grade(marks).
Python Programming from Zero 61AI CREATION CHAPTER 10 Object-Oriented Programming The big idea So far you have written programs as a series of steps and functions. Object-oriented programming (OOP) is another way to organise code: you model things from the real world as objects that hold data and can do actions. Think of a car. It has properties (colour, speed, brand) and abilities (start, brake, accelerate). OOP lets you describe such a thing once and then create as many cars as you like. Classes and objects A class is a blueprint. An object (also called an instance) is something built from that blueprint. class Dog: pass dog1 = Dog() dog2 = Dog() print(type(dog1)) print(dog1 is dog2) OUTPUT <class '__main__.Dog'> False Class names use CapWords style, such as Dog or BankAccount. The __init__ method and attributes The special method __init__ runs automatically when you create an object. It sets up the object's attributes (its data). The first parameter, self, refers to the object being created. class Dog: def __init__(self, name, age): self.name = name self.age = age dog1 = Dog("Bruno", 3) dog2 = Dog("Misty", 5) print(dog1.name) print(dog2.age) OUTPUT Bruno
Python Programming from Zero 62AI CREATION 5 Each object has its own copy of the attributes. dog1.name and dog2.name are separate. Methods A method is a function inside a class. Every method takes self as its first parameter. class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): return f"{self.name} says Woof!" def birthday(self): self.age += 1 return f"{self.name} is now {self.age}" dog = Dog("Bruno", 3) print(dog.bark()) print(dog.birthday()) print(dog.age) OUTPUT Bruno says Woof! Bruno is now 4 4 TIP Think of self as meaning "this particular object". When you call dog.bark(), Python passes dog as self automatically. Example: a bank account class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): if amount <= 0: return "Deposit must be positive" self.balance += amount return f"Deposited {amount}. Balance: {self.balance}" def withdraw(self, amount): if amount > self.balance: return "Insufficient funds" self.balance -= amount return f"Withdrew {amount}. Balance: {self.balance}" account = BankAccount("Asha", 1000)
Python Programming from Zero 63AI CREATION print(account.deposit(500)) print(account.withdraw(300)) print(account.withdraw(5000)) OUTPUT Deposited 500. Balance: 1500 Withdrew 300. Balance: 1200 Insufficient funds Notice how the rules (no negative deposits, no overdrafts) live inside the class. Anyone using the account gets those rules for free. The __str__ method By default, printing an object shows an unhelpful message. Define __str__ to control how an object appears as text. class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"'{self.title}' by {self.author}" book = Book("Wings of Fire", "A. P. J. Abdul Kalam") print(book) OUTPUT 'Wings of Fire' by A. P. J. Abdul Kalam Class attributes An attribute defined directly in the class is shared by all objects. class Student: school = "Greenfield High" count = 0 def __init__(self, name): self.name = name Student.count += 1 a = Student("Asha") b = Student("Ravi") print(a.school, b.school) print(Student.count) OUTPUT Greenfield High Greenfield High 2
Python Programming from Zero 64AI CREATION Inheritance Inheritance lets a new class reuse everything from an existing class and add or change things. The existing class is the parent (or base class). The new one is the child. class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound" class Dog(Animal): def speak(self): return f"{self.name} says Woof!" class Cat(Animal): def speak(self): return f"{self.name} says Meow!" animals = [Dog("Bruno"), Cat("Misty"), Animal("Creature")] for animal in animals: print(animal.speak()) OUTPUT Bruno says Woof! Misty says Meow! Creature makes a sound Dog and Cat did not write their own __init__. They inherited it from Animal. They override speak to give their own behaviour. Using super() When a child class needs its own __init__ but still wants the parent's setup, call super().__init__(). class Employee: def __init__(self, name, salary): self.name = name self.salary = salary class Manager(Employee): def __init__(self, name, salary, team_size): super().__init__(name, salary) self.team_size = team_size def info(self): return f"{self.name} manages {self.team_size} people" m = Manager("Meena", 90000, 8) print(m.info()) print(m.salary)
Python Programming from Zero 65AI CREATION OUTPUT Meena manages 8 people 90000 Polymorphism Polymorphism means "many forms". Different classes can have a method with the same name, and you can call it without worrying about which class the object belongs to. The animal example above did this: the loop called speak() on every animal and each one answered in its own way. Encapsulation: protecting data Encapsulation means keeping an object's data safe and exposing it only in controlled ways. Python uses naming conventions: one leading underscore (_balance) means "internal, please do not touch". Two leading underscores (__balance) make the name harder to reach from outside. class Wallet: def __init__(self): self._money = 0 def add(self, amount): if amount > 0: self._money += amount def get_money(self): return self._money w = Wallet() w.add(100) w.add(-50) print(w.get_money()) OUTPUT 100 Properties A property lets you use a method like an attribute while still running checks. class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value <= 0: raise ValueError("Radius must be positive") self._radius = value
Python Programming from Zero 66AI CREATION @property def area(self): return round(3.14159 * self._radius ** 2, 2) c = Circle(3) print(c.radius) print(c.area) c.radius = 5 print(c.area) OUTPUT 3 28.27 78.54 Class methods and static methods class MathTools: @staticmethod def add(a, b): return a + b @classmethod def describe(cls): return f"This is the {cls.__name__} class" print(MathTools.add(2, 3)) print(MathTools.describe()) OUTPUT 5 This is the MathTools class When should you use classes? Use classes when you have things that combine data and behaviour, such as users, products, accounts or game characters, and especially when you need several of them. For a short script that does one job, plain functions are often simpler. Do not use OOP just because it exists. Common mistakes COMMON MISTAKE Forgetting self in a method definition. Writing def bark(): instead of def bark(self): gives a TypeError when you call it. COMMON MISTAKE Forgetting self. when setting attributes. Writing name = name inside __init__ changes only a local variable. Write self.name = name.
Python Programming from Zero 67AI CREATION Chapter summary • A class is a blueprint, and an object is an instance of it. • __init__ sets up attributes, and methods are functions inside a class. • self refers to the current object. • Inheritance lets a child class reuse and override a parent class. • Encapsulation protects data, and properties add checks around attributes. • __str__ controls how an object prints. Practice Exercises 1. Create a Rectangle class with width and height, and methods area() and perimeter(). 2. Create a Student class that stores a name and a list of marks, with a method that returns the average. 3. Add a __str__ method to your Student class. 4. Create a Vehicle class and two child classes Car and Bike that each override a describe() method. 5. Extend BankAccount with a transfer(other_account, amount) method. 6. Build a Counter class with increment(), decrement() and reset() methods.
Python Programming from Zero 68AI CREATION CHAPTER 11 File Handling Why work with files? Variables vanish when your program ends. Files let you save data permanently: notes, scores, settings, reports. In this chapter you will learn to read and write text files, work with CSV and JSON files, and handle errors safely. All the examples below create their own files, so you can try them without any setup. Writing to a file Use the built-in open() function. The second argument is the mode. Mode Meaning "r" Read (default). The file must exist. "w" Write. Creates the file, or erases it if it already exists. "a" Append. Adds to the end of the file without erasing. "r+" Read and write file = open("notes.txt", "w") file.write("Learning Python\n") file.write("File handling is useful\n") file.close() print("File saved") OUTPUT File saved Always call close() when you finish, so the data is safely saved. The with statement (best practice) The with statement closes the file for you automatically, even if an error occurs. This is the recommended way to work with files. with open("notes.txt", "w") as f: f.write("Line one\n") f.write("Line two\n") f.write("Line three\n") with open("notes.txt", "r") as f: content = f.read()
Python Programming from Zero 69AI CREATION print(content) OUTPUT Line one Line two Line three The output ends with an empty line because the text itself ends with \n and print() adds another. Reading files in different ways with open("notes.txt", "w") as f: f.write("apple\nbanana\ncherry\n") # Read everything as one string with open("notes.txt") as f: print(repr(f.read())) # Read one line with open("notes.txt") as f: print(repr(f.readline())) # Read all lines into a list with open("notes.txt") as f: print(f.readlines()) # Loop through the file line by line (best for big files) with open("notes.txt") as f: for line in f: print(line.strip()) OUTPUT 'apple\nbanana\ncherry\n' 'apple\n' ['apple\n', 'banana\n', 'cherry\n'] apple banana cherry strip() removes the newline character at the end of each line. Appending to a file with open("log.txt", "w") as f: f.write("Start\n") with open("log.txt", "a") as f: f.write("Step 1 done\n") f.write("Step 2 done\n") with open("log.txt") as f: print(f.read())
Python Programming from Zero 70AI CREATION OUTPUT Start Step 1 done Step 2 done Checking whether a file exists import os print(os.path.exists("missing.txt")) with open("present.txt", "w") as f: f.write("hello") print(os.path.exists("present.txt")) print(os.path.getsize("present.txt"), "bytes") OUTPUT False True 5 bytes Handling errors with try and except If you try to open a file that does not exist, Python raises a FileNotFoundError. You can catch that error instead of letting the program crash. try: with open("does_not_exist.txt") as f: print(f.read()) except FileNotFoundError: print("Sorry, that file was not found.") OUTPUT Sorry, that file was not found. The structure is: • try: code that might fail • except: what to do if it fails • else: runs if nothing failed (optional) • finally: always runs, error or not (optional) def read_number(text): try: value = int(text) except ValueError: print(f"'{text}' is not a valid number") return None
Python Programming from Zero 71AI CREATION else: print("Conversion worked") return value finally: print("Finished checking") print(read_number("42")) print(read_number("abc")) OUTPUT Conversion worked Finished checking 42 'abc' is not a valid number Finished checking None Example: a simple to-do list saved to a file def save_tasks(tasks, filename): with open(filename, "w") as f: for task in tasks: f.write(task + "\n") def load_tasks(filename): try: with open(filename) as f: return [line.strip() for line in f] except FileNotFoundError: return [] tasks = ["Buy milk", "Study Python", "Call mom"] save_tasks(tasks, "todo.txt") loaded = load_tasks("todo.txt") print(loaded) print(load_tasks("nothing_here.txt")) OUTPUT ['Buy milk', 'Study Python', 'Call mom'] [] Working with CSV files CSV (comma-separated values) files store tables as plain text, and spreadsheets can open them. Python has a built-in csv module. import csv rows = [ ["name", "marks"], ["Asha", 88], ["Ravi", 72], ["Meena", 95],
Python Programming from Zero 72AI CREATION ] with open("students.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(rows) with open("students.csv") as f: reader = csv.reader(f) for row in reader: print(row) OUTPUT ['name', 'marks'] ['Asha', '88'] ['Ravi', '72'] ['Meena', '95'] csv.DictReader is even friendlier, because each row becomes a dictionary using the header names. import csv with open("students.csv", "w", newline="") as f: f.write("name,marks\nAsha,88\nRavi,72\nMeena,95\n") total = 0 with open("students.csv") as f: for row in csv.DictReader(f): print(row["name"], row["marks"]) total += int(row["marks"]) print("Average:", total / 3) OUTPUT Asha 88 Ravi 72 Meena 95 Average: 85.0 Working with JSON files JSON is a popular format for storing structured data, and it looks very much like Python dictionaries and lists. Websites and apps use it to exchange data. import json data = { "name": "Asha", "skills": ["Python", "SQL"], "active": True, } with open("profile.json", "w") as f: json.dump(data, f, indent=2) with open("profile.json") as f:
Python Programming from Zero 73AI CREATION loaded = json.load(f) print(loaded["name"]) print(loaded["skills"][0]) print(type(loaded)) OUTPUT Asha Python <class 'dict'> You can also convert between JSON text and Python objects without a file, using json.dumps() and json.loads(). File paths A path tells Python where a file lives. A name like notes.txt means "in the current folder". The pathlib module handles paths neatly on every operating system. from pathlib import Path folder = Path("reports") folder.mkdir(exist_ok=True) file_path = folder / "summary.txt" file_path.write_text("Quarterly summary") print(file_path.read_text()) print(file_path.exists()) print(file_path.name) print(file_path.suffix) OUTPUT Quarterly summary True summary.txt .txt Encoding When you work with text that includes accented or non-English characters, open the file with encoding="utf-8" so letters display correctly everywhere. with open("menu.txt", "w", encoding="utf-8") as f: f.write("café Python") with open("menu.txt", encoding="utf-8") as f: print(len(f.read())) OUTPUT 11
Python Programming from Zero 74AI CREATION Common mistakes COMMON MISTAKE Opening a file in "w" mode erases what was there. Use "a" if you want to add to an existing file. COMMON MISTAKE Forgetting that read() returns text. A number read from a file is a string until you convert it with int() or float(). COMMON MISTAKE Running your script from a different folder than the file's folder, which causes FileNotFoundError. Check your current folder, or use the full path. Chapter summary • Use open() with modes "r", "w" and "a", and prefer with open(...). • Read with read(), readline(), readlines() or by looping over the file. • try and except handle errors such as FileNotFoundError. • The csv and json modules read and write common data formats. • pathlib makes working with paths easy. Practice Exercises 1. Write a program that saves three lines of text to a file and then reads them back. 2. Count the number of lines and words in a text file. 3. Ask the user for a note and append it to diary.txt with the date. 4. Read a CSV of student marks and print the highest scorer. 5. Save a dictionary to a JSON file and load it back. 6. Write a safe number-input function that keeps asking until the user types a valid integer.
Python Programming from Zero 75AI CREATION CHAPTER 12 Python Libraries Modules and libraries You do not have to write everything yourself. A module is a Python file containing ready-made code. A library (or package) is a collection of modules. Python comes with a big standard library that is already installed, and thousands more are available through pip. Importing Use import to bring a module into your program. import math print(math.sqrt(49)) print(math.pi) from math import factorial print(factorial(5)) import math as m print(m.ceil(4.2)) OUTPUT 7.0 3.141592653589793 120 5 • import math loads the module. You write math.sqrt(...). • from math import factorial loads one item, so you write just factorial(...). • import math as m gives the module a short nickname. TIP Do not name your own file after a module, such as math.py or random.py. Python will import your file instead of the real module, which causes confusing errors. math: mathematics import math print(math.floor(7.8)) print(math.ceil(7.2)) print(math.sqrt(144)) print(math.pow(2, 8)) print(math.gcd(12, 18))
Python Programming from Zero 76AI CREATION print(round(math.log10(1000))) print(round(math.sin(math.radians(90)))) OUTPUT 7 8 12.0 256.0 6 3 1 random: chance and games import random random.seed(10) print(random.randint(1, 6)) print(random.choice(["rock", "paper", "scissors"])) cards = [1, 2, 3, 4, 5] random.shuffle(cards) print(cards) print(random.sample(range(1, 50), 3)) print(round(random.random(), 3)) OUTPUT 5 rock [2, 1, 3, 5, 4] [14, 30, 32] 0.824 random.seed(10) makes the results repeatable. Without it, the numbers are different every run, which is what you want in a game. Your exact output may differ from the lines above when you change the seed or your Python version. datetime: dates and times from datetime import date, datetime, timedelta d = date(2026, 11, 9) print(d) print(d.year, d.month, d.day) print(d.strftime("%d %B %Y")) print(d.strftime("%A")) later = d + timedelta(days=30) print(later) born = date(2000, 1, 8) print((d - born).days) moment = datetime(2026, 11, 9, 14, 30)
Python Programming from Zero 77AI CREATION print(moment.strftime("%I:%M %p")) OUTPUT 2026-11-09 2026 11 9 09 November 2026 Monday 2026-12-09 9802 02:30 PM To get today's date, use date.today(), and for the current date and time use datetime.now(). Code Meaning Example %Y Year (4 digits) 2026 %m Month number 11 %d Day 09 %B Month name November %A Weekday name Monday %H:%M Hour and minute (24 hour) 14:30 collections: smarter containers from collections import Counter, defaultdict votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"] count = Counter(votes) print(count) print(count.most_common(1)) groups = defaultdict(list) for word in ["apple", "avocado", "banana", "blueberry", "cherry"]: groups[word[0]].append(word) print(dict(groups)) OUTPUT Counter({'tea': 3, 'coffee': 2, 'juice': 1}) [('tea', 3)] {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']} Counter counts things for you, which replaces the manual counting loop from Chapter 8.
Python Programming from Zero 78AI CREATION statistics: quick data summaries import statistics marks = [72, 85, 90, 66, 85, 78] print(statistics.mean(marks)) print(statistics.median(marks)) print(statistics.mode(marks)) print(round(statistics.stdev(marks), 2)) OUTPUT 79.33333333333333 81.5 85 9.07 os and shutil: working with files and folders import os print(os.getcwd() != "") os.makedirs("demo_folder", exist_ok=True) for name in ["a.txt", "b.txt", "c.py"]: with open(os.path.join("demo_folder", name), "w") as f: f.write("x") print(sorted(os.listdir("demo_folder"))) os.rename("demo_folder/a.txt", "demo_folder/renamed.txt") print(sorted(os.listdir("demo_folder"))) os.remove("demo_folder/renamed.txt") print(sorted(os.listdir("demo_folder"))) OUTPUT True ['a.txt', 'b.txt', 'c.py'] ['b.txt', 'c.py', 'renamed.txt'] ['b.txt', 'c.py'] sys and time import time import sys start = time.time() total = sum(range(1_000_000)) elapsed = time.time() - start print(total) print(elapsed < 5) print(sys.version_info.major) OUTPUT
Python Programming from Zero 79AI CREATION 499999500000 True 3 Creating your own module Any .py file is a module. Suppose you save these lines in a file called helpers.py: def square(n): return n * n def greet(name): return f"Hello, {name}!" In another file in the same folder, you can write: import helpers print(helpers.square(6)) print(helpers.greet("Asha")) Installing third-party packages with pip Packages written by other people are installed from the terminal. Here are the ones most beginners meet first. Package Install command What it does requests pip install requests Talks to websites and web services pandas pip install pandas Tables of data (like Excel in code) numpy pip install numpy Fast number crunching with arrays matplotlib pip install matplotlib Charts and graphs openpyxl pip install openpyxl Read and write Excel files flask pip install flask Build small websites beautifulsoup4 pip install beautifulsoup4 Read and extract data from web pages The examples below need those packages installed, so they are shown for reference. requests: talking to the web import requests response = requests.get("https://api.github.com") print(response.status_code) data = response.json() print(type(data))
Python Programming from Zero 80AI CREATION A status code of 200 means success. pandas: working with tables import pandas as pd df = pd.DataFrame({ "name": ["Asha", "Ravi", "Meena"], "marks": [88, 72, 95], }) print(df) print(df["marks"].mean()) print(df[df["marks"] > 80]) Typical output: name marks 0 Asha 88 1 Ravi 72 2 Meena 95 85.0 name marks 0 Asha 88 2 Meena 95 pandas can also read a CSV with pd.read_csv("file.csv"), which makes it a favourite for data analysis. matplotlib: drawing charts import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] sales = [120, 150, 90, 180] plt.bar(months, sales) plt.title("Monthly Sales") plt.xlabel("Month") plt.ylabel("Sales") plt.show() This opens a window with a bar chart. How to find and choose libraries • Read the official documentation. Almost every good library has a "Getting Started" page. • Check that the library is maintained, with recent updates and many users. • Search with phrases like "python library for reading PDF files". • Use help(module) or dir(module) in the shell to see what a module offers. import math print("sqrt" in dir(math))
Python Programming from Zero 81AI CREATION help(math.sqrt) OUTPUT True Help on built-in function sqrt in module math: sqrt(x, /) Return the square root of x. Common mistakes COMMON MISTAKE ModuleNotFoundError: the package is not installed. Run pip install packagename, and make sure you install it for the same Python you run. COMMON MISTAKE Naming your file the same as a library (for example random.py or requests.py), which hides the real library. Chapter summary • A module is a Python file, and a library is a collection of modules. • Import with import, from ... import and import ... as. • The standard library includes math, random, datetime, collections, statistics, os, json and csv. • Third-party packages are installed with pip. The popular ones are requests, pandas, numpy and matplotlib. • Any .py file can be imported as your own module. Practice Exercises 1. Use math to compute the area of a circle with radius 7. 2. Use random to roll two dice and print the total. 3. Use datetime to calculate how many days remain until your next birthday. 4. Use Counter to find the most common word in a sentence. 5. Use statistics to find the mean and median of a list of 8 numbers. 6. Create your own module with two functions and import it into another file. 7. Install requests and fetch the status code of any website.
Python Programming from Zero 82AI CREATION CHAPTER 13 Practical Python Projects Why build projects? Reading about Python is useful, but building things is where it clicks. In this chapter you will create five small, complete programs. Each one combines ideas from earlier chapters: variables, loops, conditions, functions, collections, files and libraries. For each project, read the idea, type the code yourself, run it, and then change it. Add a feature, rename things, break it on purpose and fix it. That is how you turn knowledge into skill. Save each program in a .py file inside your python_book folder, and run it with python filename.py. Project 1: Number Guessing Game Skills used: random, while loop, conditions, input validation, functions. The computer picks a secret number between 1 and 50. The player keeps guessing, and the computer says whether each guess is too high or too low. import random def play(): secret = random.randint(1, 50) attempts = 0 print("I am thinking of a number between 1 and 50.") while True: guess_text = input("Your guess: ") if not guess_text.isdigit(): print("Please type a whole number.") continue guess = int(guess_text) attempts += 1 if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print(f"Correct! You got it in {attempts} attempts.") break play() SAMPLE RUN I am thinking of a number between 1 and 50. Your guess: 25 Too high! Your guess: abc
Python Programming from Zero 83AI CREATION Please type a whole number. Your guess: 10 Too low! Your guess: 13 Too low! Your guess: 16 Correct! You got it in 4 attempts. How it works: • random.randint(1, 50) picks the secret number. • while True loops forever, and break ends it when the guess is correct. • isdigit() protects the program from non-numbers, and continue asks again. Try these upgrades: limit the player to 7 guesses; ask whether to play again; let the player choose the range. Project 2: To-Do List Manager Skills used: functions, lists, file handling, a menu loop. A command-line to-do list that remembers your tasks even after you close the program, by saving them in a file. import os FILENAME = "todo.txt" def load_tasks(): if not os.path.exists(FILENAME): return [] with open(FILENAME) as f: return [line.strip() for line in f if line.strip()] def save_tasks(tasks): with open(FILENAME, "w") as f: for task in tasks: f.write(task + "\n") def show_tasks(tasks): if not tasks: print("Your list is empty.") return for number, task in enumerate(tasks, start=1): print(f"{number}. {task}") def main(): tasks = load_tasks() while True: print("\n1. Show tasks 2. Add task 3. Remove task 4. Quit") choice = input("Choose an option: ").strip() if choice == "1": show_tasks(tasks) elif choice == "2": task = input("New task: ").strip() if task: tasks.append(task) save_tasks(tasks)
Python Programming from Zero 84AI CREATION print("Task added.") elif choice == "3": show_tasks(tasks) number = input("Number to remove: ").strip() if number.isdigit() and 1 <= int(number) <= len(tasks): removed = tasks.pop(int(number) - 1) save_tasks(tasks) print(f"Removed: {removed}") else: print("Invalid number.") elif choice == "4": print("Goodbye!") break else: print("Please choose 1, 2, 3 or 4.") main() Here is one session. The tasks are saved to todo.txt, so the next time you run the program the list is still there. SAMPLE RUN 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 1 Your list is empty. 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 2 New task: Buy milk Task added. 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 2 New task: Study Python Task added. 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 1 1. Buy milk 2. Study Python 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 3 1. Buy milk 2. Study Python Number to remove: 1 Removed: Buy milk 1. Show tasks 2. Add task 3. Remove task 4. Quit Choose an option: 4 Goodbye! How it works: • load_tasks() reads the file if it exists, and returns an empty list otherwise. • save_tasks() writes every task on its own line. • The menu loop shows the options until the user chooses 4.
Python Programming from Zero 85AI CREATION Try these upgrades: mark tasks as done; add due dates; sort by priority. Project 3: Expense Tracker Skills used: dictionaries, lists of dictionaries, defaultdict, f-string formatting, error handling. Enter your spending by category and get a report that shows the total for each category and its share of the whole. from collections import defaultdict expenses = [] def add_expense(category, amount, note=""): expenses.append({"category": category, "amount": amount, "note": note}) def total_spent(): return sum(e["amount"] for e in expenses) def summary_by_category(): totals = defaultdict(float) for e in expenses: totals[e["category"]] += e["amount"] return dict(totals) def print_report(): print("--- Expense Report ---") totals = summary_by_category() ordered = sorted(totals.items(), key=lambda x: x[1], reverse=True) for category, amount in ordered: share = amount / total_spent() * 100 print(f"{category:<12} {amount:>8.2f} ({share:.0f}%)") print("-" * 24) print(f"{'Total':<12} {total_spent():>8.2f}") def main(): print("Expense Tracker. Type 'done' as the category to finish.") while True: category = input("Category: ").strip().lower() if category == "done": break try: amount = float(input("Amount: ")) except ValueError: print("That is not a number. Try again.") continue add_expense(category, amount) if expenses: print_report() else: print("No expenses entered.") main() SAMPLE RUN Expense Tracker. Type 'done' as the category to finish. Category: food Amount: 250
Python Programming from Zero 86AI CREATION Category: transport Amount: 80.5 Category: food Amount: 120 Category: rent Amount: abc That is not a number. Try again. Category: rent Amount: 1500 Category: done --- Expense Report --- rent 1500.00 (77%) food 370.00 (19%) transport 80.50 (4%) ------------------------ Total 1950.50 How it works: • Each expense is a dictionary stored in the expenses list. • summary_by_category() adds up the amounts for each category. • try and except catch typing mistakes in the amount, so the program does not crash. • {category:<12} and {amount:>8.2f} align the report neatly in columns. Try these upgrades: save the expenses to a CSV file; add a monthly budget and warn when it is passed; show the report as a bar chart with matplotlib. Project 4: Quiz App Skills used: lists of dictionaries, loops, functions, scoring and percentages. A multiple-choice quiz that gives instant feedback and a final score. The questions are stored as data, so you can add more without changing the logic. questions = [ {"q": "Which symbol starts a comment in Python?", "options": ["//", "#", "--", "/*"], "answer": 2}, {"q": "What does len([4, 5, 6]) return?", "options": ["2", "3", "4", "6"], "answer": 2}, {"q": "Which keyword defines a function?", "options": ["func", "define", "def", "function"], "answer": 3}, {"q": "What is the result of 7 // 2?", "options": ["3.5", "3", "4", "1"], "answer": 2}, ] def ask(question): print("\n" + question["q"]) for number, option in enumerate(question["options"], start=1): print(f" {number}. {option}") reply = input("Your answer (1-4): ").strip() return reply.isdigit() and int(reply) == question["answer"] def main(): score = 0 for question in questions: if ask(question): print("Correct!") score += 1
Python Programming from Zero 87AI CREATION else: right = question["options"][question["answer"] - 1] print(f"Wrong. The answer is: {right}") percent = score / len(questions) * 100 print(f"\nYou scored {score} out of {len(questions)} ({percent:.0f}%).") main() SAMPLE RUN Which symbol starts a comment in Python? 1. // 2. # 3. -- 4. /* Your answer (1-4): 2 Correct! What does len([4, 5, 6]) return? 1. 2 2. 3 3. 4 4. 6 Your answer (1-4): 2 Correct! Which keyword defines a function? 1. func 2. define 3. def 4. function Your answer (1-4): 1 Wrong. The answer is: def What is the result of 7 // 2? 1. 3.5 2. 3 3. 4 4. 1 Your answer (1-4): 2 Correct! You scored 3 out of 4 (75%). How it works: • Each question is a dictionary with the text, the options and the number of the right answer. • ask() shows one question and returns True or False. • The main loop counts the score and prints a percentage. Try these upgrades: shuffle the questions with random.shuffle; load questions from a JSON file; add a timer.
Python Programming from Zero 88AI CREATION Project 5: File Organizer Skills used: os, shutil, dictionaries, loops, string methods. A script that tidies a messy folder by moving each file into a subfolder based on its file type, such as Images, Documents and Videos. import os import shutil CATEGORIES = { "Images": [".jpg", ".jpeg", ".png", ".gif"], "Documents": [".pdf", ".docx", ".txt", ".xlsx"], "Videos": [".mp4", ".mkv", ".mov"], } def category_for(filename): extension = os.path.splitext(filename)[1].lower() for category, extensions in CATEGORIES.items(): if extension in extensions: return category return "Other" def organize(folder): moved = 0 for name in os.listdir(folder): path = os.path.join(folder, name) if not os.path.isfile(path): continue target_folder = os.path.join(folder, category_for(name)) os.makedirs(target_folder, exist_ok=True) shutil.move(path, os.path.join(target_folder, name)) print(f"Moved {name} -> {category_for(name)}") moved += 1 print(f"Done. {moved} files organized.") organize("downloads_test") COMMON MISTAKE This program really moves files. Always test it on a practice folder first, never on your important documents. Create a folder named downloads_test, put a few dummy files in it, and run the program there. Suppose downloads_test contains photo.jpg, report.pdf, notes.txt, clip.mp4, archive.zip and logo.PNG. The output looks like this (the order of the files may differ on your computer): SAMPLE RUN Moved report.pdf -> Documents Moved archive.zip -> Other Moved photo.jpg -> Images Moved clip.mp4 -> Videos Moved notes.txt -> Documents Moved logo.PNG -> Images Done. 6 files organized.
Python Programming from Zero 89AI CREATION Afterwards the folder contains four subfolders: Documents, Images, Other and Videos. How it works: • os.path.splitext() splits a file name into its name and extension. • .lower() makes sure .PNG and .png are treated the same. • shutil.move() moves the file into its category folder. • Anything that does not match a category goes into Other. Try these upgrades: add more categories; ask the user for the folder name; add an "undo" feature that moves the files back. How to design your own project When you have an idea, follow these steps: 1. Describe it in one sentence. "A program that tracks my daily water intake." 2. List the inputs and outputs. What does the user type? What should appear? 3. Break it into small functions. One job per function. 4. Build the smallest working version first. Get something running, even if it is ugly. 5. Test it often. Run it after every small change. 6. Improve it step by step. Add one feature at a time. More project ideas Project What you will practise Password generator random, strings, loops Unit converter functions, conditions, dictionaries Contact book dictionaries, JSON files Rock, paper, scissors random, conditions, loops Simple calculator with a menu functions, error handling Word counter for a text file files, strings, Counter Hangman game strings, lists, loops Student marks analyzer CSV, statistics, functions Birthday reminder datetime, files Weather lookup requests, JSON Chapter summary • Projects combine many small skills into something real. • Plan the inputs, outputs and functions before you write code. • Start small, test often, then add features.
Python Programming from Zero 90AI CREATION • Always test programs that change or delete files on practice data first. Practice Exercises 1. Add a "give up" option to the guessing game that reveals the number. 2. Add a "mark as done" option to the to-do list. 3. Make the expense tracker save its data to a CSV file and load it on the next run. 4. Add five more questions to the quiz and shuffle the order each time. 5. Extend the file organizer so that it asks which folder to organize. 6. Build one project from the ideas table and write a short description of how it works.
Python Programming from Zero 91AI CREATION CHAPTER 14 Common Errors and Debugging Errors are normal Every programmer, from a first-week beginner to a senior engineer, sees errors every day. An error is not a sign that you are bad at coding. It is Python telling you exactly what it did not understand. Learning to read errors calmly is one of the most valuable skills you can build. A bug is a mistake in a program, and debugging is the process of finding and fixing it. The three kinds of errors Kind When it appears Example Syntax error Before the program runs. Python cannot understand the code. Missing colon or bracket Runtime error (exception) While the program runs. Python understood the code but something went wrong. Dividing by zero Logic error The program runs without any error message but gives the wrong answer. Using + when you meant * Logic errors are the hardest, because Python has nothing to complain about. You find them by checking the results. How to read a traceback When a runtime error happens, Python prints a traceback. Read it from the bottom up. Traceback (most recent call last): File "shop.py", line 8, in <module> total = calculate_total(prices) File "shop.py", line 4, in calculate_total return sum(prices) / len(prices_list) NameError: name 'prices_list' is not defined 1. The last line tells you the error type and a short message: NameError: name 'prices_list' is not defined. 2. The line above it shows the exact line of code that failed, and its line number (line 4). 3. The lines above show how the program got there: calculate_total was called from line 8. Start with the last line and ask: what does this message mean, and which name or value is the problem?
Python Programming from Zero 92AI CREATION Syntax errors Python refuses to run code that breaks the grammar rules. Common causes: • A missing colon after if, for, while, def or class • A missing closing bracket, quote or parenthesis • Using = instead of == in a condition • Misspelling a keyword code = 'if 5 > 3 print("yes")' try: compile(code, "example", "exec") except SyntaxError as e: print(type(e).__name__) print(e.msg) OUTPUT SyntaxError invalid syntax The exact wording of error messages changes a little between Python versions, and newer versions often give more helpful hints. When the error line looks fine, check the line before it for a missing bracket or quote. IndentationError code = "def f():\nreturn 1" try: compile(code, "example", "exec") except IndentationError as e: print(type(e).__name__) print(e.msg) OUTPUT IndentationError expected an indented block after function definition on line 1 NameError You used a name that does not exist. Usually it is a typo, or the variable was never created. try: print(scoree) except NameError as e: print(type(e).__name__, "-", e) OUTPUT NameError - name 'scoree' is not defined
Python Programming from Zero 93AI CREATION Fix: check the spelling and capital letters, and make sure the variable was assigned before you use it. TypeError You used a value of the wrong type for an operation. try: print("Age: " + 25) except TypeError as e: print(type(e).__name__, "-", e) try: print(len(100)) except TypeError as e: print(type(e).__name__, "-", e) OUTPUT TypeError - can only concatenate str (not "int") to str TypeError - object of type 'int' has no len() Fix: convert the value (str(25), int("5")) or use an f-string. ValueError The type is right, but the value is not acceptable. try: number = int("twelve") except ValueError as e: print(type(e).__name__, "-", e) OUTPUT ValueError - invalid literal for int() with base 10: 'twelve' Fix: validate the input before converting, or wrap the conversion in try and except. IndexError You asked for a position that does not exist. colors = ["red", "green", "blue"] try: print(colors[3]) except IndexError as e: print(type(e).__name__, "-", e) OUTPUT IndexError - list index out of range
Python Programming from Zero 94AI CREATION Fix: remember that the last valid index is len(list) - 1. KeyError You asked a dictionary for a key it does not have. student = {"name": "Asha", "age": 21} try: print(student["city"]) except KeyError as e: print(type(e).__name__, "-", e) print(student.get("city", "unknown")) OUTPUT KeyError - 'city' unknown Fix: use .get() or check with if key in dictionary. ZeroDivisionError try: print(10 / 0) except ZeroDivisionError as e: print(type(e).__name__, "-", e) OUTPUT ZeroDivisionError - division by zero AttributeError You used a method or attribute that the object does not have. try: "hello".append("!") except AttributeError as e: print(type(e).__name__, "-", e) OUTPUT AttributeError - 'str' object has no attribute 'append' Fix: check the type of the object with type(x) and look up its real methods with dir(x).
Python Programming from Zero 95AI CREATION FileNotFoundError and ModuleNotFoundError try: open("no_such_file.txt") except FileNotFoundError as e: print(type(e).__name__) try: import not_a_real_module except ModuleNotFoundError as e: print(type(e).__name__, "-", e) OUTPUT FileNotFoundError ModuleNotFoundError - No module named 'not_a_real_module' Fix: check the file name, extension and folder. For modules, run pip install for the package. A quick error reference Error Usual cause First thing to check SyntaxError Broken grammar Colons, brackets, quotes IndentationError Wrong spacing Four spaces, no mixed tabs NameError Unknown name Spelling, missing assignment TypeError Wrong type Convert with int(), str() ValueError Bad value The input being converted IndexError Position too big len() and the last index KeyError Missing key Use .get() ZeroDivisionError Divided by zero The divisor AttributeError Wrong method type() and dir() FileNotFoundError Wrong path Name, folder, extension Catching exceptions with try and except You can handle errors gracefully instead of crashing. def safe_divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Please provide numbers" print(safe_divide(10, 2)) print(safe_divide(10, 0))
Python Programming from Zero 96AI CREATION print(safe_divide(10, "x")) OUTPUT 5.0 Cannot divide by zero Please provide numbers COMMON MISTAKE Avoid a bare except: that catches everything. It hides real bugs. Catch the specific errors you expect. Raising your own errors Use raise to signal that something is wrong in your own functions. def set_age(age): if age < 0 or age > 120: raise ValueError("Age must be between 0 and 120") return age try: set_age(-5) except ValueError as e: print("Error:", e) OUTPUT Error: Age must be between 0 and 120 Assertions An assert statement checks something you believe is true. If it is false, Python raises an AssertionError. It is a handy way to test small pieces of your code. def average(numbers): return sum(numbers) / len(numbers) assert average([2, 4, 6]) == 4 assert average([10]) == 10 print("All checks passed") OUTPUT All checks passed
Python Programming from Zero 97AI CREATION Debugging with print() The simplest and most popular debugging tool is print(). Show the values of variables at key points to see what is really happening. def total_price(prices, tax_rate): subtotal = 0 for p in prices: subtotal += p print("DEBUG: running subtotal =", subtotal) total = subtotal * (1 + tax_rate) print("DEBUG: total =", total) return total total_price([100, 200], 0.1) OUTPUT DEBUG: running subtotal = 100 DEBUG: running subtotal = 300 DEBUG: total = 330.0 Remove the debug prints when you have fixed the problem. Finding a logic error This function should return the average of a list, but it gives the wrong answer. No error appears, so you have to investigate. def average(numbers): total = 0 for n in numbers: total += n return total / len(numbers) + 1 print(average([10, 20, 30])) OUTPUT 21.0 The correct answer is 20.0. Checking the result against a hand calculation reveals the extra + 1 at the end of the return line. A logic error like this is found by comparing results with what you expect. Using the built-in debugger Python includes a debugger called pdb. Put breakpoint() where you want the program to pause. You can then look at variables and step through the code line by line. def buggy(numbers): total = 0 for n in numbers: breakpoint() total += n
Python Programming from Zero 98AI CREATION return total When it pauses you will see a (Pdb) prompt. The most useful commands are: Command What it does n Run the next line s Step into a function call c Continue until the next breakpoint p variable Print a variable's value l Show the code around the current line q Quit the debugger Editors like VS Code and Thonny also have a visual debugger. You click next to a line number to set a breakpoint and then step through the program with buttons. Thonny is especially good for seeing how variables change. A step-by-step debugging method 1. Read the error message from the bottom up. Do not skip it. 2. Find the line it points to, and check the line just before it too. 3. Reproduce the problem with the smallest example you can. 4. Check your assumptions. Print variables and types. Is the value what you expected? 5. Change one thing at a time, then run again. 6. Search the error message online. Someone has almost certainly seen it before. Include the error type and the key words. 7. Explain the problem aloud. Describing the code line by line to a friend, or even a rubber duck, often reveals the bug. This is called rubber duck debugging. 8. Take a break. Fresh eyes spot mistakes that tired eyes miss. Habits that prevent bugs • Write and test small pieces of code, not 200 lines at once. • Use meaningful names, so mistakes are easier to see. • Keep functions short with one job each. • Do not copy code you do not understand. • Use version control (Git) so you can always go back to a working version. • Test with unusual input: empty lists, zero, negative numbers, very large values.
Python Programming from Zero 99AI CREATION Chapter summary • Errors give you information. Read the traceback from the bottom up. • Know the common errors: SyntaxError, NameError, TypeError, ValueError, IndexError, KeyError and ZeroDivisionError. • Handle expected problems with try and except, and raise errors with raise. • Debug with print(), assert, breakpoint() and your editor's debugger. • Work methodically: reproduce, check assumptions, change one thing at a time. Practice Exercises 1. For each error type in this chapter, write a short line of code that causes it, then fix it. 2. Find the bug: for i in range(1, 5): print(i * i. What is the error and the fix? 3. A program should print the numbers 1 to 10 but prints only 1 to 9. Find and fix the off-by-one error in for i in range(1, 10). 4. Write a function safe_int(text) that returns the integer, or None if the text is not a number. 5. Add a try and except to a program that divides two numbers typed by the user. 6. Take any program from Chapter 13, add a deliberate bug, and use print() to track it down.
Python Programming from Zero 100AI CREATION CHAPTER 15 Exercises and Interview Questions How to use this chapter This chapter has four parts: 1. Sample solutions to selected exercises from earlier chapters. 2. Mixed challenges to test everything together. 3. Interview questions with short, clear answers. 4. Coding interview problems with worked solutions. Always try a problem yourself first. Struggling for 15 to 20 minutes before reading a solution is what makes the lesson stick. There are usually several correct solutions, so yours does not need to match these exactly. Part 1: Sample solutions to chapter exercises Chapter 3: area of a rectangle length = 8 width = 5 area = length * width print(f"Area = {area}") OUTPUT Area = 40 Chapter 4: splitting seconds into hours, minutes and seconds total_seconds = 3725 hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 print(hours, minutes, seconds) OUTPUT 1 2 5
Python Programming from Zero 101AI CREATION Chapter 5: palindrome check and counting vowels def is_palindrome(word): word = word.lower() return word == word[::-1] def count_vowels(text): return sum(1 for ch in text.lower() if ch in "aeiou") print(is_palindrome("Madam")) print(is_palindrome("Python")) print(count_vowels("Learning Python is fun")) OUTPUT True False 6 Chapter 6: duplicates and swapping dictionary keys numbers = [1, 2, 2, 3, 3, 3, 4] print(sorted(set(numbers))) original = {"a": 1, "b": 2} swapped = {value: key for key, value in original.items()} print(swapped) OUTPUT [1, 2, 3, 4] {1: 'a', 2: 'b'} Chapter 7: ticket pricing def ticket_price(age): if age < 5: return 0 elif age <= 17: return 50 elif age <= 59: return 100 else: return 60 for age in [3, 10, 30, 65]: print(age, ticket_price(age)) OUTPUT 3 0 10 50 30 100 65 60
Python Programming from Zero 102AI CREATION Chapter 8: factorial, Fibonacci, pyramid and primes # Factorial of 6 result = 1 for n in range(1, 7): result *= n print(result) # First 10 Fibonacci numbers a, b = 0, 1 fib = [] for _ in range(10): fib.append(a) a, b = b, a + b print(fib) # Pyramid with 5 rows for row in range(1, 6): print(" " * (5 - row) + "*" * (2 * row - 1)) # Primes up to 50 primes = [] for n in range(2, 51): if all(n % i != 0 for i in range(2, int(n ** 0.5) + 1)): primes.append(n) print(primes) OUTPUT 720 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] * *** ***** ******* ********* [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] Chapter 9: recursion def sum_to(n): if n == 0: return 0 return n + sum_to(n - 1) print(sum_to(10)) OUTPUT 55
Python Programming from Zero 103AI CREATION Chapter 10: Rectangle and Student classes class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) class Student: def __init__(self, name, marks): self.name = name self.marks = marks def average(self): return sum(self.marks) / len(self.marks) def __str__(self): return f"{self.name}: average {self.average():.1f}" r = Rectangle(4, 6) print(r.area(), r.perimeter()) print(Student("Asha", [88, 92, 79])) OUTPUT 24 20 Asha: average 86.3 Chapter 11: counting lines and words in a file with open("sample.txt", "w") as f: f.write("Python is fun\nFiles are useful\nPractice every day\n") lines = 0 words = 0 with open("sample.txt") as f: for line in f: lines += 1 words += len(line.split()) print("Lines:", lines) print("Words:", words) OUTPUT Lines: 3 Words: 9
Python Programming from Zero 104AI CREATION Chapter 14: a safe integer converter def safe_int(text): try: return int(text) except ValueError: return None print(safe_int("42")) print(safe_int("forty")) print(safe_int(" 7 ")) OUTPUT 42 None 7 Part 2: Mixed challenges Try these without looking at solutions. Each uses several skills from the book. Beginner level 1. Print a multiplication table (1 to 10) for a number the user chooses. 2. Convert kilometres to miles (1 km = 0.621371 miles). 3. Check whether a number is positive, negative or zero. 4. Print the sum of the digits of a number (for 472, the answer is 13). 5. Count how many times a chosen letter appears in a sentence. 6. Make a program that tells the user whether a year is a leap year. 7. Create a list of 10 numbers and print only the even ones. 8. Print the reverse of a number (for 1234, print 4321). Intermediate level 9. Find the second largest number in a list without sorting it. 10. Write a function that checks whether two words are anagrams (for example, "listen" and "silent"). 11. Count the frequency of every word in a paragraph and print the top three. 12. Write a program that removes duplicates from a list but keeps the original order. 13. Create a dictionary that maps each letter of the alphabet to its position (a is 1, b is 2). 14. Write a simple login system that allows only three password attempts. 15. Read a CSV of products and prices and print the most expensive product. 16. Write a function that generates a random password of a chosen length.
Python Programming from Zero 105AI CREATION Advanced level 17. Build a contact book class that saves and loads contacts from a JSON file. 18. Write a function that checks whether brackets in a string are balanced, such as "{[()]}". 19. Build a text-based Hangman game. 20. Write a decorator that prints how long a function takes to run. 21. Create a Library class with Book objects, borrowing and returning. 22. Write a program that reads a text file and reports the number of lines, words, characters and the five most common words. Part 3: Interview questions and answers These are the questions that come up most often in interviews for Python beginners and junior roles. Practise answering them aloud in your own words. 1. What is Python, and why is it popular? Python is a high-level, interpreted, general-purpose programming language known for its readable syntax. It is popular because it is easy to learn, has a huge standard library and community, and is used in web development, data science, machine learning, automation and more. 2. Is Python interpreted or compiled? Both, in a way. Python source code is first compiled to bytecode, which is then run by the Python virtual machine. From the programmer's point of view it behaves as an interpreted language, because you do not run a separate compile step. 3. What is the difference between a list and a tuple? A list is mutable (can be changed) and written with [ ]. A tuple is immutable (cannot be changed) and written with ( ). Tuples are slightly faster, can be used as dictionary keys when all their items are hashable, and are good for fixed data. 4. What is the difference between a list, a set and a dictionary? A list is an ordered collection that allows duplicates. A set is an unordered collection of unique items. A dictionary stores key-value pairs with unique keys. Lookups in sets and dictionaries are very fast. 5. What does mutable and immutable mean? A mutable object can be changed after it is created (lists, dictionaries, sets). An immutable object cannot be changed (integers, floats, strings, tuples). Changing an immutable value really creates a new object. 6. What is the difference between == and is? == checks whether two values are equal. is checks whether two names refer to the same object in memory. a = [1, 2, 3] b = [1, 2, 3]
Python Programming from Zero 106AI CREATION c = a print(a == b) print(a is b) print(a is c) OUTPUT True False True 7. What is PEP 8? PEP 8 is the official style guide for Python code. It recommends four spaces for indentation, snake_case for variables and functions, CapWords for classes, lines under about 79 characters, and spaces around operators. Consistent style makes code easier to read. 8. What are *args and **kwargs? *args collects any number of extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. They let a function accept a flexible number of arguments. 9. What is a lambda function? A lambda is a small anonymous function written in one expression, such as lambda x: x * 2. It is often used for short jobs like sorting keys. 10. What is a list comprehension? A list comprehension is a short way to build a list from another sequence, such as [n * n for n in range(5) if n % 2 == 0]. It is usually shorter and faster than the equivalent loop. 11. What is the difference between append() and extend()? append() adds one item (even if that item is a list). extend() adds every item of an iterable one by one. a = [1, 2] a.append([3, 4]) print(a) b = [1, 2] b.extend([3, 4]) print(b) OUTPUT [1, 2, [3, 4]] [1, 2, 3, 4]
Python Programming from Zero 107AI CREATION 12. What is the difference between a shallow copy and a deep copy? A shallow copy copies the outer container but shares the inner objects. A deep copy copies everything, including nested objects. import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) original[0].append(99) print(shallow) print(deep) OUTPUT [[1, 2, 99], [3, 4]] [[1, 2], [3, 4]] 13. What is a function, and how is it different from a method? A function is a reusable block of code defined with def. A method is a function that belongs to a class and is called on an object, such as "hello".upper(). 14. What are self and __init__? __init__ is the constructor method that runs when an object is created and sets up its attributes. self is the first parameter of an instance method and refers to the object itself. 15. Explain the four pillars of OOP. • Encapsulation: bundling data with the methods that use it and protecting it from careless changes. • Abstraction: hiding complex details and exposing a simple interface. • Inheritance: a child class reuses the code of a parent class. • Polymorphism: different classes can respond to the same method name in their own way. 16. How does exception handling work in Python? Code that might fail goes inside try. Specific errors are caught in except blocks. else runs if no error occurred, and finally always runs, which makes it good for clean-up such as closing files. You can raise your own errors with raise. 17. What is the difference between a module and a package? A module is a single Python file. A package is a folder of modules, usually containing an __init__.py file.
Python Programming from Zero 108AI CREATION 18. What does if __name__ == "__main__": do? It makes some code run only when the file is executed directly, not when it is imported as a module. It is the standard way to separate reusable code from the part that starts the program. def greet(): return "Hello" if __name__ == "__main__": print(greet()) OUTPUT Hello 19. What are decorators? A decorator is a function that wraps another function to add behaviour without changing its code. They are applied with the @ symbol. def shout(func): def wrapper(*args, **kwargs): return func(*args, **kwargs).upper() return wrapper @shout def greet(name): return f"hello, {name}" print(greet("asha")) OUTPUT HELLO, ASHA 20. What are generators? A generator is a function that uses yield to produce values one at a time instead of building a full list. This saves memory for large sequences. def count_up(limit): n = 1 while n <= limit: yield n n += 1 print(list(count_up(5))) OUTPUT [1, 2, 3, 4, 5]
Python Programming from Zero 109AI CREATION 21. How does Python manage memory? Python manages memory automatically. It uses reference counting, which frees an object when nothing refers to it any more, and a garbage collector that cleans up groups of objects that refer to each other. 22. What is the GIL? The Global Interpreter Lock lets only one thread run Python bytecode at a time in the standard CPython implementation. It means that threads do not speed up CPU-heavy work, so programmers use multiprocessing for that, while threads still work well for waiting on files or networks. 23. What are Python's built-in data types? Numbers (int, float, complex), text (str), booleans (bool), sequences (list, tuple, range), mappings (dict), sets (set, frozenset), binary types (bytes, bytearray) and NoneType. 24. What is a virtual environment, and why use one? A virtual environment is an isolated folder with its own Python packages. It stops different projects from clashing over package versions. You create one with python -m venv name. 25. How do you handle files safely? Use the with open(...) statement, which closes the file automatically, choose the correct mode ("r", "w", "a"), and handle errors such as FileNotFoundError with try and except. Part 4: Coding interview problems with solutions Reverse a string def reverse_string(text): return text[::-1] print(reverse_string("python")) OUTPUT nohtyp Check for an anagram def is_anagram(a, b): return sorted(a.lower()) == sorted(b.lower()) print(is_anagram("listen", "silent")) print(is_anagram("hello", "world")) OUTPUT True False
Python Programming from Zero 110AI CREATION Find duplicates in a list def find_duplicates(items): seen = set() duplicates = set() for item in items: if item in seen: duplicates.add(item) seen.add(item) return sorted(duplicates) print(find_duplicates([1, 2, 3, 2, 4, 3, 5])) OUTPUT [2, 3] Two sum Return the positions of two numbers that add up to a target. def two_sum(numbers, target): seen = {} for index, number in enumerate(numbers): needed = target - number if needed in seen: return [seen[needed], index] seen[number] = index return None print(two_sum([2, 7, 11, 15], 9)) print(two_sum([3, 2, 4], 6)) OUTPUT [0, 1] [1, 2] Remove duplicates but keep the order def unique_in_order(items): seen = set() result = [] for item in items: if item not in seen: seen.add(item) result.append(item) return result print(unique_in_order([4, 1, 4, 2, 1, 3])) OUTPUT [4, 1, 2, 3]
Python Programming from Zero 111AI CREATION Second largest number def second_largest(numbers): unique = sorted(set(numbers)) if len(unique) < 2: return None return unique[-2] print(second_largest([10, 40, 30, 40, 20])) OUTPUT 30 Most common word from collections import Counter text = "the cat and the dog and the bird" words = text.split() print(Counter(words).most_common(2)) OUTPUT [('the', 3), ('and', 2)] Flatten a nested list def flatten(items): result = [] for item in items: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result print(flatten([1, [2, 3], [4, [5, 6]], 7])) OUTPUT [1, 2, 3, 4, 5, 6, 7] Balanced brackets def is_balanced(text): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in text: if ch in "([{": stack.append(ch) elif ch in ")]}":
Python Programming from Zero 112AI CREATION if not stack or stack.pop() != pairs[ch]: return False return not stack print(is_balanced("{[()]}")) print(is_balanced("{[(])}")) print(is_balanced("(((")) OUTPUT True False False Merge two sorted lists def merge_sorted(a, b): result = [] i = j = 0 while i < len(a) and j < len(b): if a[i] <= b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1 result.extend(a[i:]) result.extend(b[j:]) return result print(merge_sorted([1, 4, 7], [2, 3, 9, 10])) OUTPUT [1, 2, 3, 4, 7, 9, 10] Recursive Fibonacci with memory from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) print(fib(10)) print(fib(50)) OUTPUT 55 12586269025
Python Programming from Zero 113AI CREATION Tips for the interview itself • Think aloud. Interviewers care about how you reason, not only the final answer. • Ask clarifying questions before you start: what are the inputs, and what should happen with an empty list? • Start with a simple solution, then improve it. • Test with examples, including edge cases such as empty input, one item and duplicates. • Be honest when you do not know something. Say how you would find out. • Practise on your own computer first, then on a whiteboard or plain text editor. Where to go from here You now have a solid foundation. Here is a simple 30-day plan to keep your momentum: Days Focus 1 to 7 Re-do the chapter exercises from memory. Build Projects 1 and 4 again with your own twists. 8 to 14 Solve one small coding problem a day (Part 2 and Part 4). 15 to 21 Build one bigger project from the ideas list in Chapter 13. 22 to 30 Choose a direction and start learning it Pick a direction that fits your goal: • Data analysis and data science: learn pandas, NumPy and matplotlib, then scikit-learn. • Web development: learn Flask or Django, plus HTML and basic SQL. • Automation: learn to work with Excel files, PDFs, email and web pages. • Software careers: practise data structures and algorithms, learn Git, and put your projects on GitHub. A final word Learning to program is a skill, and skills grow with practice. You will get stuck. You will see errors you do not understand. That is part of the process, and everyone who writes code has been exactly where you are now. Keep your projects small, write code every day, and be patient with yourself. You started this book at zero. Now you can read Python, write programs, fix errors and build real tools. The next step is yours. Pick a problem you care about, and start building. Happy coding!
