BEGINNER FRIENDLY | STEP BY STEP | HANDS-ON Python Programming from Zero A Complete Beginner's Guide

AI CREATION Python Programming from Zero 2 About This Book Welcome! Thisbook 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.

AI CREATION Python Programming from Zero 3 Table of Contents 1. IntroductiontoPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2. Installing Python and Setting Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3. Python Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4. Data Types and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 5. Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6. Lists, Tuples and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 7. Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 8. Loops in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 9. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 10. Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 11. File Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 12. Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 13. Practical Python Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 14. Common Errors and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 15. Exercises and Interview Questions . . . . . . . . . . . . . . . . . . . . . . . . . . 100

AI CREATION Python Programming from Zero 4 CHAPTER 1 Introduction to Python What is programming? What is Python? Python is a programminglanguage created by Guido van Rossum and first released in 1991. It was Why learn Python? Easy to learn. Thesyntax (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. 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. designed to be easy to read and easy to write. Compare how the same idea looks in plain English and in Python: Acomputerisvery 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. You can vote age = 18 if age >= 18: print("You can vote") OUTPUT • • • • •

AI CREATION Python Programming from Zero 5 Your first look at a program What can you build with Python? How does Python run your code? Area Web development Data analysis Machine learning and AI Automation Games Scientific computing Cybersecurity and networking What Python is used for Websites and web apps Cleaning, exploring and charting data Models that learn from data Renaming files, sending emails, filling spreadsheets Simple 2D games Maths, simulations, research Scanning tools and scripts pygame NumPy, SciPy socket, scapy Popular tools Django, Flask, FastAPI pandas, matplotlib scikit-learn, TensorFlow, PyTorch Built-in modules, openpyxl Donotworry aboutinstallinganything yet.That is the next chapter. For now, just read these examples and notice how simple they look. print() is a built-in function. It displays whatever you place inside the brackets. The text inside quotation marks is called a string. You do not need to learn all of these. This book teaches the core language, which is the foundation for every one of them. Python is an interpreted language. When yourun 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. 2. 3. 4. You write instructions in a text file that ends with .py. You ask the interpreter to run the file. The interpreter reads the code from top to bottom and executes each line. If it finds a mistake, it stops and shows an error message that tells you what went wrong and where. Hello, World! print("Hello, World!") print("My name is Asha") print("I am learning Python") OUTPUT

AI CREATION Python Programming from Zero 6 print(2 + 3) My name is Asha I am learning Python 5 Comments help explain code # This line is a comment and is ignored print("Comments help explain code") # This comment is at the end of a line TIP Good comments explain why you did something, not what the code already says. Write comments for the future you who has forgotten everything. NOTE The fastest way to learn is to write code every day, even for 20 minutes, and to build small things you find interesting. OUTPUT OUTPUT A comment is a note for humans that Python ignores. It starts with a # symbol. 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. "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. 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 Python 2 versus Python 3 Common beginner worries • • • •

AI CREATION Python Programming from Zero 7 Chapter summary Practice Exercises • • • • • 1. 2. 3. 4. 5. Programmingmeans 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. In yourownwords,explain what a program is. Use a real-life example other than a recipe. List three fields where Python is used and name one tool for each. 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. Write down a comment line explaining what the line print("Welcome") does. Find one job advertisement that mentions Python. What other skills does it ask for?

AI CREATION Python Programming from Zero 8 CHAPTER 2 Installing Python and Setting Up What you need Step 2: Download Python Step 3: Install on Windows Step 1: Check whether Python is already installed Open yourbrowser and gotopython.org. Click Downloads. The website detects your system and offers the latest version. Download the installer and open it. Somecomputersalready havePython. Open aterminal 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. Run the downloaded.exefile. Tick the box that says "Add python.exe to PATH". This is the most important step. It lets you run Python from any folder. Click Install Now and wait for it to finish. Close the window when it says "Setup was successful". 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. You needthreethings: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. 1. 2. 3. 1. 2. 3. 4. 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 --version COMMON MISTAKE

AI CREATION Python Programming from Zero 9 Step 4: Verify the installation Step 5: Try the interactive shell Step 3 (alternative): Install on Linux Step 3 (alternative): Install on macOS 1. 2. 3. 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. Open a new terminal window and type: Open thedownloaded .pkgfileandfollowtheprompts. When finished, open Terminal and type On macOS you will usually type instead of to confirm. In the shell you can type just 5 + 7 and Python shows the answer without needing exit() and press Enter to leave the shell. Your version number may be different, which is fine as long as it starts with 3. If it works, congratulations. Python is installed. MostLinuxsystemsalreadyincludePython3.Ifnot,use your package manager. On Ubuntu or Debian: Python hasan 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 >>>. . Type python3 --version python3 python. print() Python 3.12.4 python --version >>> print("Hello, World!") Hello, World! >>> 5 + 7 12 >>> "Python" * 3 'PythonPythonPython' >>> exit() sudo apt update sudo apt install python3 python3-pip TIP OUTPUT

AI CREATION Python Programming from Zero 10 Step 6: Choose a code editor Running from the terminal: the basics Step 7: Write and run your first program Here are the few terminal commands you need. You have just written and run your first program. Create anewfolder on your computercalled Open your editor and create a new file. Type the following lines: Ashell is greatfor one-liners, but realprograms are saved in files. You need a code editor, a program for writing code. Here are three good free options: 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. Save the file inside python_book with the name hello.py. The .py ending tells your computer it is a Python file. Run the file. In your editor, click the Run button (a triangle). Or in the terminal, go to the folder and type: Editor IDLE Thonny Command cd folder_name Visual Studio Code (VS Code) Best for Absolute beginners Learning and debugging Beginners who want to grow What it does Move into a folder Notes Comes with Python. Simple and nothing extra to install. Free, popular, and has a Python extension with helpful hints. Made for beginners and shows step-by-step how code runs. 1. 2. 3. 4. 5. python_book. cd python_book python hello.py Hello, World! This is my first Python program. print("Hello, World!") print("This is my first Python program.") OUTPUT

AI CREATION Python Programming from Zero 11 Command cd .. dir (Windows) or ls (macOS/Linux) python file.py What it does Go up one folder List the files in the current folder 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: Troubleshooting • Virtual environments (a quick introduction) To install a package, for example one called On macOS and Linux you may need to type When the environment is active, you will see deactivate to leave it. , you would type instead of pip. at the start of your terminal line. Type "python is notrecognized" (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(). As you buildmore projects,you will want each project tokeepits 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: pip --version python -m venv myenv myenv\Scripts\activate source myenv/bin/activate (Windows) (macOS and Linux) (myenv) requests pip3 pip install requests. • • • •

AI CREATION Python Programming from Zero 12 Chapter summary Practice Exercises • • • • • • 1. 2. 3. 4. 5. Pythonanda codeeditor 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. Install Pythonandwritedown your version number. Open the interactive shell and calculate 15 * 4, 100 / 8 and 2 ** 5. What does each give? Create about_me.py that prints your name, your city and one reason you want to learn Python. In the shell, type print("5 + 5") and then print(5 + 5). Compare the results with your prediction from Chapter 1. Deliberately make a mistake: type pritn("Hello") and read the error message. What does Python say?

AI CREATION Python Programming from Zero 13 CHAPTER 3 Python Syntax and Variables What is syntax? Syntax is the set of rulesfor writing valid Python, like grammar in a spoken language. If you break a 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. Statements and lines The two indented lines belong to the Python runs statements in order, from top to bottom. Eachinstructioniscalledastatement. Normally, one statement goes on one line. . The last line is not indented, so it runs no matter what. rule, Python shows a SyntaxError and refuses to run the program. The good news is that Python's rules are few and consistent. First statement Second statement Third statement It is hot Drink water This line always runs print("First statement") print("Second statement") print("Third statement") temperature = 35 if temperature > 30: print("It is hot") print("Drink water") print("This line always runs") OUTPUT OUTPUT if

AI CREATION Python Programming from Zero 14 OUTPUT OUTPUT OUTPUT COMMON MISTAKE Inconsistent indentation causes an IndentationError. Do not mix tabs and spaces. Set your editor to insert four spaces when you press Tab. Using variables What is a variable? Youcanusevariablesin calculations and in A variable can be changed at any time. This is why it is called a variable. 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. Avariable is anamethatstores a value. Think of it as a labelled box. You put something in the box and use the label whenever you need it. 10 20 25 Asha 25 name = "Asha" age = 25 print(name) print(age) Total cost: 1000 score = 10 print(score) score = 20 print(score) score = score + 5 print(score) price = 250 quantity = 4 total = price * quantity print("Total cost:", total) print().

AI CREATION Python Programming from Zero 15 The line . 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 The Python community uses snake_case for variable names: lowercase words joined by underscores. Choose names that explain themselves. reads: take the current score, add 5, and store the result back inscore = score + 5 score True. Naming style Naming rules A good name saves you from writing a comment. Prefer over 2nd_place my-name class Name student_name age2 No No No Valid? Yes Yes Reason Letters and underscore Digit is allowed after the first character Starts with a digit Hyphen is not allowed Reserved keyword 36.0 #Hardtounderstand x = 200 y = 0.18 z = x * y #Muchclearer bill_amount= 200 tax_rate =0.18 tax = bill_amount * tax_rate print(tax) TIP OUTPUT total_marks tm.

AI CREATION Python Programming from Zero 16 Constants Getting input from the user Assigning multiple variables If the user types , the screen shows: Pythonletsyouassignseveralvariablesinone line. You can swap two values without a helper variable, which is unusual and handy: Python hasnotrue constants, but by convention, a name written in capital letters means "do not change this". The input() function pausestheprogram and waits for the user to type something. Whatever the user types is returned as text. 1 2 3 0 0 3.14159 3 coffee tea a, b,c=1, 2, 3 print(a, b, c) PI = 3.14159 MAX_ATTEMPTS = 3 print(PI, MAX_ATTEMPTS) What is your name? Ravi Hello, Ravi first = "tea" second = "coffee" first, second = second, first print(first, second) name = input("What is your name? ") print("Hello,", name) x = y = 0 print(x, y) OUTPUT OUTPUT OUTPUT Ravi

AI CREATION Python Programming from Zero 17 More about print() Formatted strings (f-strings) Multiple lines and long statements print() ending. f Use triple quotes for text that spans several lines: The easiestway tomix text andvariablesis an f-string. Put an place variables inside curly brackets. before the opening quote and canshowseveral values separated by spaces, and you can control the separator and the Python is fun 2026-11-09 Loading...done Roses are red, Violets are blue, Python is easy, And so are you. poem = """Roses are red, Violets are blue, Python is easy, And so are you.""" print(poem) print("Python", "is", "fun") print("2026", "11", "09", sep="-") print("Loading", end="...") print("done") My name is Asha and I am 25 years old. Next year I will be 26. 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 OUTPUT OUTPUT

AI CREATION Python Programming from Zero 18 Chapter summary Practice Exercises Common errors in this chapter COMMON MISTAKE NameError: using a variable before it exists, or misspelling it. COMMON MISTAKE SyntaxError: forgetting a closing quote or bracket, as in • • • • • • 1. 2. 3. 4. 5. 6. score gives where it got confused, but the real mistake may be on the line above. when you defined . Python points to the lineprint("Hello print(scor) NameError: name 'scor' is not defined. Syntaxistheset ofrules 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. Create variables foryour name, age and city. Print them in one sentence using an f-string. Which of these names are invalid and why: for? Create length = 8 and width = 5. Calculate and print the area of the rectangle. Swap the values of two variables without using a third variable. Ask the user for their favourite colour with input() and print a friendly reply. Fix the error: print("Hello World). , , ,total_price 1st_prize user name _count,

AI CREATION Python Programming from Zero 19 CHAPTER 4 Data Types and Operators What is a data type? Integers Integers arewhole numbers, positive or negative. Python can handle very large integers without any The main basic types special effort. Every value in Pythonhas 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. <class 'int'> <class 'float'> <class 'str'> <class 'bool'> print(type(42)) print(type(3.14)) print(type("hello")) print(type(True)) students = 30 temperature = -5 population = 1400000000 print(students, temperature, population) print(2 ** 100) OUTPUT Type int float str bool NoneType Name Integer Floating-point String Boolean None Example 7, -3, 1000 3.14, -0.5, 2.0 "hello", 'A' True, False None Meaning Whole numbers Numbers with decimals Text Yes or no values The absence of a value

AI CREATION Python Programming from Zero 20 OUTPUT OUTPUT OUTPUT OUTPUT 1.8 199.98 Pune Good morning It's easy She said "hello" 0.30000000000000004 0.3 height = 1.75 price = 99.99 print(height + 0.05) print(price * 2) city = "Pune" greeting = 'Good morning' print(city, greeting) print("It's easy") print('She said "hello"') print(0.1 + 0.2) print(round(0.1 + 0.2, 2)) 30 -5 1400000000 1267650600228229401496703205376 Floats are numbers with a decimal point. This is normal in every programming language. Use For readability, you can write large numbers with underscores: A string is text inside single or double quotes. Both work the same. Computers store decimals in binary, so tiny rounding differences can appear: when you display results.round() 1_400_000_000. Floats Strings

AI CREATION Python Programming from Zero 21 None Booleans Type conversion Notice that gives This matters most with Youcanconvertavaluefrom one type to another using means "no value yet". It is used when something is empty or not set. . It cuts off the decimal part and does not round. , which always returns text: and Abooleanis either True or False. The capital first letter is required. Booleans are the result of comparisons and drive decisions in your programs. None int(7.9) 7 input() int(), float(), str() bool(). True False False 30 7.0 100 rupees 7 print(10 > 5) print(10 == 5) is_raining = False print(is_raining) None <class 'NoneType'> result = None print(result) print(type(result)) print(int("25") + 5) print(float("3.5") * 2) print(str(100) + " rupees") print(int(7.9)) age = input("Enter your age: ") next_age = int(age) + 1 print("Next year you will be", next_age) OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 22 OUTPUT OUTPUT COMMON MISTAKE Trying gives a TypeError because you cannot add text and a number. Convert first: . If the text is not a number, as in int("hello"), Python raises a ValueError. "5" + 3 int("5") + 3 Arithmetic operators The remainder operator is very useful. A number is even if is Anoperatorisasymbolthatperforms an operation. These are the arithmetic operators: Operator + - * / // % ** Meaning Addition Subtraction Multiplication Division (always a float) Floor division Remainder (modulus) Power Example 7 + 2 7 - 2 7 * 2 7 / 2 7 // 2 7 % 2 7 ** 2 Result 9 5 14 3.5 3 1 49 0 1 22 12 85 3.4 3 2 289 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) print(10 % 2) print(11 % 2) % n % 2 0.

AI CREATION Python Programming from Zero 23 Order of operations Assignment operators Comparison operators Theseshortcutsupdateavariable in place. Comparisonoperatorscomparetwo values and give or When in doubt, add brackets. They make the order obvious to readers. Pythonfollows the sameorder as maths: brackets first, then powers, then multiplication and division, then addition and subtraction. 15 12 24 6 14 20 512 score = 10 score += 5 print(score) score -= 3 print(score) score *= 2 print(score) score //= 4 print(score) print(2 + 3 * 4) print((2 + 3) * 4) print(2 ** 3 ** 2) OUTPUT OUTPUT True False. Operator == != > < >= <= Meaning Equal to Not equal to Greater than Less than Greater than or equal Less than or equal Example 5 == 5 5 != 3 5 > 8 5 < 8 5 >= 5 4 <= 3 Result True True False True True False

AI CREATION Python Programming from Zero 24 OUTPUT OUTPUT OUTPUT COMMON MISTAKE • • • Do not confuse = with . A single assigns a value. Double compares two values.== = == Logical operators Membership and identity operators Useful built-in functions for numbers The Logicaloperatorscombineconditions: and is True only when both sides are True. is True when at least one side is True. flips True to False and the other way round. operatorcheckswhethersomethingisinside another value:in and or not and, or not. 12 3.14 True True False True False False 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)) print("a" in "banana") print("z" in "banana") print(3 not in [1, 2, 3]) age = 22 has_id = True print(age >= 18 and has_id) print(age < 18 or has_id) print(not has_id)

AI CREATION Python Programming from Zero 25 9 2 1024 (3, 2) Chapter summary Practice Exercises • • • • • • 1. 2. 3. 4. 5. 6. Themain typesare 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. Predict, then check: 7// 2, 7 % 2, 7 / 2, 2 ** 4. Ask the user for two numbers and print their sum, difference, product and quotient. Convert a temperature of 36.6 Celsius to Fahrenheit using F = C * 9 / 5 + 32. Given total_seconds = 3725, calculate hours, minutes and seconds using // and %. What does bool(0), bool(1) and bool("") give? Test them. Write one expression that is True only when a number n is between 10 and 20 (inclusive).

AI CREATION Python Programming from Zero 26 CHAPTER 5 Working with Strings What is a string? Indexing: getting one character Negative indexes count from the end. returns the number of characters in a string. is the last character. Everycharacterhasapositioncalledanindex. Counting starts at 0, not 1. Astringis asequenceofcharacters: letters, digits, spaces and symbols. You will work with strings constantly, because almost all human data (names, messages, addresses) is text. P h n o word = "Python" print(word[0]) print(word[3]) print(word[-1]) print(word[-2]) P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 Python Learning Python is fun! 6 0 word = "Python" sentence = "Learning Python is fun!" empty = "" print(word) print(sentence) print(len(word)) print(len(empty)) OUTPUT OUTPUT len() -1

AI CREATION Python Programming from Zero 27 OUTPUT OUTPUT COMMON MISTAKE Asking for an index that does not exist, like • • • • range. , raises an IndexError: string index out ofword[10] Strings cannot be changed Slicing: getting part of a string means from the start to index 4. means from index 4 to the end. takes every second character. reverses the string. Aslice takesapieceofastring.Theformatis before stop. . It includes but stops just Strings are immutable:oncecreated,you cannot change a character in place. To "change" a string, build a new one. [:4] [4:] [::2] [::-1] [start:stop] start Jython Pro gram Prog ramming ing Pormig gnimmargorP 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]) word = "Python" # word[0] = "J" <- this would cause a TypeError new_word = "J" + word[1:] print(new_word)

AI CREATION Python Programming from Zero 28 Changing case Cleaning strings Joining and repeating PYTHON IS FUN python is fun Python Is Fun Python is fun PYTHON IS fUN [hello world] [hello world ] hello world][ Good Morning hahaha -------------------- text = "python is Fun" print(text.upper()) print(text.lower()) print(text.title()) print(text.capitalize()) print(text.swapcase()) first = "Good" second = "Morning" print(first + " " + second) print("ha" * 3) print("-" * 20) raw = " hello world " print("[" + raw.strip() + "]") print("[" + raw.lstrip() + "]") print("[" + raw.rstrip() + "]") OUTPUT OUTPUT OUTPUT Userinputoftenhasextra spaces. removes spaces from both ends.strip()

AI CREATION Python Programming from Zero 29 Replacing text Splitting and joining Searching in strings 4 -1 2 True True True I like coffee. Tea is great. I like tea. Coffee is great. sentence = "apples,bananas,cherries" fruits = sentence.split(",") print(fruits) print("-".join(["2026", "11", "09"])) print(" ".join(words)) message = "I like tea. Tea is great." print(message.replace("tea", "coffee")) print(message.replace("Tea", "Coffee")) ['apples', 'bananas', 'cherries'] ['Python', 'is', 'easy', 'to', 'learn'] 5 words = "Python is easy to learn".split() print(words) print(len(words)) 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 OUTPUT OUTPUT find() split() -1 join() message breaksastringintoa list of pieces. Replacement is case sensitive. The original immutable. replace() returns a new string. returns the index of the first match, or if the text is not found. does the opposite. is not changed, because strings are

AI CREATION Python Programming from Zero 30 True True True True True True Line one Line two Name: Asha She said "Hi" C:\Users\Asha 2026-11-09 Python is easy to learn print("12345".isdigit()) print("hello".isalpha()) print("hello123".isalnum()) print(" ".isspace()) print("HELLO".isupper()) print("hello".islower()) print("Line one\nLine two") print("Name:\tAsha") print("She said \"Hi\"") print("C:\\Users\\Asha") Escape characters Checking what a string contains OUTPUT OUTPUT Somecharactersneedaspecial code that starts with a backslash. Code \n \t \\ \" Meaning New line Tab A backslash A double quote inside double quotes

AI CREATION Python Programming from Zero 31 Chapter summary Formatting strings A practical example shows two decimal places. adds thousands separators. pads with zeros to width 5. shows a percentage. , and ^ align right, left and centre. Hereisasmallprogramthatcleans up a name typed by a user. Strings aresequencesof characters. Indexing starts at 0. Slicing [start:stop:step] extracts parts. [::-1] reverses. Strings are immutable, so methods return new strings. Useful methods: Use escape characters like , , , , , and . Youmetf-stringsinChapter3. They can also control how numbers look. Ravi Kumar Initials: R.K. Notebook: 1234.57 Notebook: 1,234.6 00042 25.6% Notebook Notebook| | Notebook | 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}|") raw_name = " rAVI kUMAR " clean = " ".join(raw_name.split()).title() print(clean) print(f"Initials: {clean[0]}.{clean.split()[1][0]}.") OUTPUT OUTPUT • • • • • • • • • • .2f , 05d % > < upperlowerstripfindcountreplace, split, join. \n \t

AI CREATION Python Programming from Zero 32 • 1. 2. 3. 4. 5. 6. 7. f-strings can format numbers neatly. Ask the user for their name and print it in uppercase, then the number of letters. Check whether a word typed by the user is a palindrome (reads the same backwards), such as "madam". Given "python programming", print it in title case and print only the first word. Count how many vowels are in a sentence entered by the user. Take "2026-11-09" and print the day, month and year separately using split("-"). Replace every space in a sentence with an underscore. Print the number 3.14159 rounded to 3 decimal places using an f-string. Practice Exercises

AI CREATION Python Programming from Zero 33 CHAPTER 6 Lists, Tuples and Dictionaries Why collections? Lists Accessing list items from the end. Alistisan ordered, changeable collection. Write it with square brackets and separate items with commas. Lists use thesameindexingand slicing as strings: the first index is 0 and negative indexes count So fareach 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. apple grape ['banana', 'cherry'] ['apple', 'banana'] ['apple', 'banana', 'cherry'] 3 <class 'list'> fruits = ["apple", "banana", "cherry"] marks = [78, 85, 92, 67] mixed = ["Asha", 25, True, 3.5] empty = [] print(fruits) print(len(fruits)) print(type(fruits)) fruits = ["apple", "banana", "cherry", "mango", "grape"] print(fruits[0]) print(fruits[-1]) print(fruits[1:3]) print(fruits[:2]) print(fruits[::2]) OUTPUT OUTPUT

AI CREATION Python Programming from Zero 34 del fruits[0] print(fruits) last = fruits.pop() print(last) print(fruits) fruits.append("mango") print(fruits) fruits.remove("cherry") print(fruits) fruits.insert(0, "kiwi") print(fruits) numbers = [5, 2, 9, 1, 7] print(len(numbers)) print(sum(numbers)) print(max(numbers)) print(min(numbers)) ['apple', 'cherry', 'grape'] fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" print(fruits) ['apple', 'blueberry', 'cherry'] ['apple', 'blueberry', 'cherry', 'mango'] ['kiwi', 'apple', 'blueberry', 'cherry', 'mango'] ['kiwi', 'apple', 'blueberry', 'mango'] mango ['kiwi', 'apple', 'blueberry'] ['apple', 'blueberry'] Changing a list More list operations Unlikestrings,listsaremutable: you can change them after creating them. OUTPUT clear() Method append(x) insert(i, x) remove(x) pop() What it does Adds x to the end Adds x at position i Removes the first x Removes and returns the last item (or pop(i) for position i) Removes everything

AI CREATION Python Programming from Zero 35 a = [1, 2, 3] b = [4, 5] print(a + b) print(a * 2) print(3 in a) print(10 in a) 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 [1, 2, 3, 4, 5] [1, 2, 3, 1, 2, 3] True False original = [1, 2, 3] alias = original alias.append(4) print(original) numbers.sort() print(numbers) numbers.reverse() print(numbers) print(numbers.index(9)) print(numbers.count(2)) safe_copy = original.copy() safe_copy.append(5) print(original) print(safe_copy) print(sorted(numbers)) print(sorted(numbers, reverse=True)) print(numbers) OUTPUT OUTPUT sorted() .sort()returns a new list and leaves the original alone. changes the list itself. A common trap: copying lists Combining lists and checking membership

AI CREATION Python Programming from Zero 36 OUTPUT OUTPUT OUTPUT COMMON MISTAKE alias = original [1, 2, 3] 6 7 [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5] grid = [ ] print(grid[0]) print(grid[1][2]) print(grid[2][0]) [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 9, 16, 25] [0, 2, 4, 6, 8] ['Asha', 'Ravi', 'Meena'] squares = [n * n for n in range(1, 6)] print(squares) names = ["asha", "ravi", "meena"] print([name.title() for name in names]) evens = [n for n in range(10) if n % 2 == 0] print(evens) list(original) .copy()does not make a copy. Both names point to the same list. Use when you need an independent copy. or Nested lists List comprehensions (a first look) Alistcanholdother lists. This is how you represent a table or grid. Alistcomprehensionbuildsanewlistinoneline. You will love it once you get used to it.

AI CREATION Python Programming from Zero 37 Tuples Dictionaries Tuple unpacking Atupleislike a list, but it is immutable: once created it cannot be changed. Write it with round brackets. Adictionarystores data as key-value pairs, like a real dictionary where each word (key) has a meaning (value). Use curly brackets with key: value pairs. 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,). 10 blue 3 1 Asha 25 Pune person = ("Asha", 25, "Pune") name, age, city = person print(name) print(age) print(city) point = (10, 20) colors = ("red", "green", "blue") print(point[0]) print(colors[-1]) print(len(colors)) print(colors.index("green")) student = { } print(student) print(student["name"]) print(student.get("age")) print(student.get("phone")) print(student.get("phone", "not given")) "name": "Asha", "age": 21, "course": "Data Science", OUTPUT OUTPUT

AI CREATION Python Programming from Zero 38 OUTPUT OUTPUT OUTPUT del student["city"] print(student) removed = student.pop("age") print(removed) print(student) for item, price in prices.items(): print(f"{item} costs {price}") student = {"name": "Asha", "age": 21} student["age"] = 22 student["city"] = "Pune" print(student) {'name': 'Asha', 'age': 22, 'city': 'Pune'} {'name': 'Asha', 'age': 22} 22 {'name': 'Asha'} ['tea', 'coffee', 'juice'] [20, 35, 50] [('tea', 20), ('coffee', 35), ('juice', 50)] tea costs 20 coffee costs 35 juice costs 50 prices = {"tea": 20, "coffee": 35, "juice": 50} print(list(prices.keys())) print(list(prices.values())) print(list(prices.items())) {'name': 'Asha', 'age': 21, 'course': 'Data Science'} Asha 21 None not given Use when the key might not exist. Assigning to a key that exists updates it. Assigning to a new key adds it. would raise a KeyError..get() student["phone"] Changing a dictionary Looping over dictionaries

AI CREATION Python Programming from Zero 39 Sets Nested data Which collection should I use? An empty set must be written , because creates an empty dictionary. Realdataisoftena list of dictionaries, which is the same shape as a table of rows. Asetisan unordered collection of unique items. It removes duplicates automatically. a={1, 2, 3, 4} b={3, 4, 5} print(a & b) print(a | b) print(a - b) Asha 88 Ravi 72 Meena 95 Top scorer: Meena {1, 2, 3} ['code', 'learn', 'python'] {3, 4} {1, 2, 3, 4, 5} {1, 2} numbers = {1, 2, 3, 3, 2, 1} print(numbers) students = [ ] forsin students: {"name": "Asha", "marks": 88}, {"name": "Ravi", "marks": 72}, {"name": "Meena", "marks": 95}, print(s["name"], s["marks"]) best =max(students, key=lambda s: s["marks"]) print("Topscorer:", best["name"]) tags = set(["python", "code", "python", "learn"]) print(sorted(tags)) OUTPUT OUTPUT set() {} Type List Ordered Yes Changeable Yes Duplicates Allowed Use it for A sequence of items that may change

AI CREATION Python Programming from Zero 40 Set Type Tuple Dictionary No Ordered Yes Yes (by insertion) Yes Yes Changeable No Duplicates Allowed Keys must be unique Not allowed Use it for Fixed data like coordinates Looking things up by name Unique items and set maths Chapter summary Practice Exercises • • • • • 1. 2. 3. 4. 5. 6. 7. Lists[ ]are ordered and changeable. Use , Tuples ( ) cannot be changed. Dictionaries {key: value} look values up by key. Use Sets { } hold unique items. list2 = list1 does not copy. Use .copy(). and for safe access. Create a list of fiveofyour favourite foods. Add one, remove one, and print it sorted. Given [4, 8, 15, 16, 23, 42], print the sum, the average, the largest and the smallest. Remove the duplicates from [1, 2, 2, 3, 3, 3, 4] using a set. Create a dictionary for a book with the keys title, author and year. Print each pair. Make a list of squares of the numbers 1 to 10 using a list comprehension. Given a list of student dictionaries, print the names of students with marks above 80. Swap the keys and values of {"a": 1, "b": 2}. .get() appendinsert, remove, pop sort.

AI CREATION Python Programming from Zero 41 CHAPTER 7 Conditional Statements Making decisions if and else The if statement runswhen the condition is False. 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 Aprogram thatalways 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. else You are an adult You cannot vote yet age = 20 if age >= 18: print("You are an adult") age = 15 if age >= 18: print("You can vote") else: print("You cannot vote yet") OUTPUT OUTPUT COMMON MISTAKE Do not forget the colon at the end of the causes a SyntaxError or IndentationError. line, and do not forget to indent the block. Missing eitherif

AI CREATION Python Programming from Zero 42 elif: many choices Truthy and falsy values Using comparison and logical operators Even though matters. Python treats somevaluesas False in a condition: None. Almost everything else counts as True. (empty string), is also True, Python stops at the first match. The order of your conditions and Useelif (shortfor "elseif") to check more than two possibilities. Python checks conditions from top to bottom and runs the first one that is True. 76 >= 60 0, 0.0, "" [], {}, (), set() Grade: A Entry allowed It is the weekend Username is empty 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) items = [] if items: print("Cart has items") age = 25 has_ticket= True ifage>=18 and has_ticket: print("Entry allowed") username = "" if notusername: print("Username is empty") day = "Sunday" ifday=="Saturday" or day == "Sunday": print("It is the weekend") OUTPUT OUTPUT

AI CREATION Python Programming from Zero 43 Confirmed Cart is empty Hello Asha You may drive You may drive name = "Asha" ifname: print("Hello", name) else: print("Cart is empty") age = 22 has_license = True if age >= 18 and has_license: print("You may drive") answer = " YES " if answer.strip().lower() == "yes": print("Confirmed") age = 22 has_license = True if age >= 18: else: if has_license: print("You may drive") else: print("Get a license first") print("You are too young to drive") OUTPUT OUTPUT OUTPUT OUTPUT Comparing text Nested if statements Youcanplacean insideanother Stringcomparisoniscase sensitive, so is not equal to Deep nesting gets hard to read. The same logic can be written more clearly with . Normalise input first: if if. "Yes" "yes" and:

AI CREATION Python Programming from Zero 44 The match statement Chained comparisons The ternary (one-line) if The underscore instead. Python 3.10 added is the default case, like Pythonletsyouwritearangecheck the way you do in maths: Forasimplechoicebetweentwovalues, you can write the decision in one line: . If you use an older Python, use ,atidy way to compare one value against many options. and minor Wednesday Pass class score = 55 if 40 <= score < 60: print("Pass class") day = 3 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case _: print("Another day") age = 17 status = "adult" if age >= 18 else "minor" print(status) OUTPUT OUTPUT OUTPUT _ match else if elif

AI CREATION Python Programming from Zero 45 Example: leap year The pass statement Sometimes you need a blockthat does nothing yet, such as when you are still planning your code. Example: a simple login check Ayearisaleapyearifitisdivisible by 4, except century years, which must be divisible by 400. Python does not allow an empty block, so use pass as a placeholder. Login successful Program continues 2024 is a leap year username = "asha" password = "python123" saved_user = "asha" saved_pass = "python123" age = 30 if age > 18: pass print("Program continues") ifusername == saved_user and password == saved_pass: print("Login successful") username != saved_user:elif print("Unknown user") else: print("Wrong password") 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 OUTPUT OUTPUT

AI CREATION Python Programming from Zero 46 Chapter summary Practice Exercises Common mistakes COMMON MISTAKE COMMON MISTAKE • • • • • 1. 2. 3. 4. 5. 6. 7. Writing Writing always True. Write instead of . A single and expecting it to check both numbers. Python reads or use if x in (1, 2):. on its own as assigns, so Python reports a SyntaxError.if x = 5: if x == 5: ifx== 1 or 2: if x == 1orx==2: = 2 andor not. elif if,elif and elseletprograms choose what to do. Conditions use comparison operators and Indentation shows which lines belong to which block. Empty values (0, "", [], None) are falsy. match (Python 3.10+) is a tidy alternative to many , , lines. Ask for a number and print whether it is positive, negative or zero. Ask for a number and print whether it is even or odd. Ask for three numbers and print the largest without using max(). Write a grading program: 90+ gives A, 80+ gives B, 70+ gives C, otherwise Fail. Ask for a year and print whether it is a leap year. 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. Check whether a password is at least 8 characters and contains at least one digit.

AI CREATION Python Programming from Zero 47 CHAPTER 8 Loops in Python Why loops? Imagine printing the numbers 1 to 100. You could write 100 The for loop A The range() function In each round, the variable body. You can loop over strings too: createsasequenceof numbers. loopgoesthrough the items of a sequence one by one. of three lines. A loop repeats a block of code. Python has two kinds: takes the next value from the list. The indented lines are the loop lines, or you could write a loop loops and while loops. for range() fruit print() for P y t h o n I like apple I like banana I like cherry for i in range(5): print(i) for letter in "Python": print(letter) fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit) OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 48 0 1 2 3 4 1 2 3 4 5 107 41 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 Sum of 1 to 10: 55 for i in range(1, 6): print(i, end=" ") print() for i in range(10, 0, -3): print(i, end=" ") print() total = 0 for n in range(1, 11): total += n print("Sum of 1 to 10:", total) number = 7 for i in range(1, 6): print(f"{number} x {i} = {number * i}") • • • • range(5) range(2, 6) range(0, 10, 2) range(5, 0, -1) gives0, 1, 2, 3, 4 (stops before 5). gives 2, 3, 4, 5. gives 0, 2, 4, 6, 8 (step of 2). counts down: 5, 4, 3, 2, 1. This pattern is the accumulator: start with an empty total and add to it in each round. OUTPUT OUTPUT OUTPUT Multiplication table Using loops to calculate

AI CREATION Python Programming from Zero 49 The while loop break: leave the loop early Asking until the answer is valid loopsareidealforrepeatingaquestionuntil the user gives a good answer. Awhile looprepeats as long as a condition stays True. Use it when you do not know in advance how many times you need to repeat. while Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done First multiple of 35: 35 count = 1 while count <= 5: print("Count is", count) count += 1 print("Done") password = "" while password != "python123": password = input("Enter the password: ") print("Access granted") for number in range(1, 100): if number % 7 == 0 and number % 5 == 0: print("First multiple of 35:", number) break OUTPUT OUTPUT 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.

AI CREATION Python Programming from Zero 50 Nested loops The else clause on loops continue: skip to the next round 1 3 5 7 * ** *** **** 29 is prime for number in range(1, 8): if number % 2 == 0: continue print(number) for i in range(1, 4): for j in range(1, 4): print(i * j, end="\t") print() for row in range(1, 5): for col in range(1, row + 1): print("*", end="") print() number = 29 for i in range(2, number): else: if number % i == 0: print(number, "is not prime") break print(number, "is prime") OUTPUT OUTPUT OUTPUT A loop can havean A multiplication grid: Aloopinsidealoopruns the inner loop fully for each round of the outer loop. blockthatruns only if the loop finished without hittingelse break.

AI CREATION Python Programming from Zero 51 OUTPUT OUTPUT OUTPUT OUTPUT 1 2 3 Largest: 89 1 red 2 green 3 blue Asha scored 88 Ravi scored 72 Meena scored 95 numbers = [34, 12, 89, 5, 61] largest = numbers[0] for n in numbers: if n > largest: largest = n print("Largest:", largest) names=["Asha", "Ravi", "Meena"] marks=[88, 72, 95] forname,mark in zip(names, marks): print(name, "scored", mark) text = "mississippi" counts = {} for ch in text: counts[ch] = counts.get(ch, 0) + 1 print(counts) colors= forindex,color ["red", "green", "blue"] in enumerate(colors, start=1): print(index, color) 2 4 6 3 6 9 enumerate and zip Example: counting characters Looping with a counter and a condition enumerate() zip() Finding the largest value in a list by hand: givesyouthe position and the value together. walks through two lists at once.

AI CREATION Python Programming from Zero 52 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 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) {'m': 1, 'i': 4, 's': 4, 'p': 2} for or while? Common mistakes Example: FizzBuzz Use forwhenyou know what you are looping over (a list, a range, a string). Use while when you repeat until something happens. Thisclassic exerciseisalso 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". OUTPUT COMMON MISTAKE Changing a list while looping over it. Loop over a copy ( instead. COMMON MISTAKE • • Forgetting that programming. stops at 4, not 5. This "off by one" error is one of the most common in ) or build a new list range(5) for x in items[:]

AI CREATION Python Programming from Zero 53 Chapter summary Practice Exercises • • • • • 1. 2. 3. 4. 5. 6. 7. 8. forloopsgo 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. Printthe numbers1to 20 that are divisible by 3. Calculate the factorial of 6 using a loop (6 x 5 x 4 x 3 x 2 x 1). Print the first 10 numbers of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, and so on. Print a pyramid of stars with 5 rows. Write a number-guessing game that keeps asking until the player guesses the secret number. Count how many words in a sentence start with a capital letter. Print all prime numbers between 1 and 50. Reverse a string using a loop, without using slicing.

AI CREATION Python Programming from Zero 54 CHAPTER 9 Functions What is a function? Parameters and arguments Defining and calling a function Usethekeyword Defining a function does not run it. The code inside runs only when you call it. todefineafunction,then call it by writing its name followed by brackets. Parameters arethe namesinthe function definition. Arguments are the actual values you pass when calling. They let a function work with different data. A function isa 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. def say_hello() say_hello() Hello, Asha! Hello, Ravi! greet("Asha") greet("Ravi") Hello! Welcome to Python. Hello! Welcome to Python. def greet(name): print(f"Hello, {name}!") def say_hello(): print("Hello!") print("Welcome to Python.") OUTPUT OUTPUT

AI CREATION Python Programming from Zero 55 When Python reaches A function can take several parameters: , the function ends immediately. 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. 7 35 36 25 add(3, 4) add(10, 25) Adult Minor Invalid age defadd(a, b): print(a + b) def square(n): return n * n print(check_age(25)) print(check_age(10)) print(check_age(-3)) result = square(6) print(result) print(square(3) + square(4)) defcheck_age(age): ifage < 0: return "Invalid age" ifage >= 18: return "Adult" return "Minor" OUTPUT OUTPUT OUTPUT COMMON MISTAKE A function without a return statement returns None. If you see Returning a value return printed the result of a function that only prints, or forgot . in your output, you probablyNone return

AI CREATION Python Programming from Zero 56 Keyword arguments Default parameter values Returning multiple values Variable number of arguments: *args and **kwargs Parameters with defaults must come after those without. Use *args to accept any number of positional arguments, and keyword arguments. Afunctioncanreturnseveralvalues,which Python packs into a tuple. Youcangiveaparameteradefaultvalue. It is used when the caller does not provide one. Youcanpassargumentsbyname, so the order does not matter and the call is easier to read. to accept any number of 1 9 Hello, Asha! Good morning, Asha! def total(*numbers): Bruno is a 3-year-old dog. Misty is a 2-year-old cat. low, high = min_max([4, 9, 1, 7]) print(low, high) defgreet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Asha")) print(greet("Asha", "Good morning")) defmin_max(numbers): return min(numbers), max(numbers) defdescribe_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 OUTPUT OUTPUT **kwargs

AI CREATION Python Programming from Zero 57 50.0 rate = 0.1 Inside: 100 3 50 name: Asha city: Pune job: Analyst calculate() # print(result) print(interest(500)) return sum(numbers) definterest(amount): return amount * rate print(total(1, 2)) print(total(5, 10, 15, 20)) defcalculate(): result = 100 print("Inside:", result) defshow_profile(**details): forkey, value in details.items(): print(f"{key}: {value}") show_profile(name="Asha", city="Pune", job="Analyst") <- NameError: result is not defined here OUTPUT OUTPUT OUTPUT Scope: where variables live Avariablecreated insideafunctionislocal. It exists only while the function runs. A variable created outside functions is global. 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.

AI CREATION Python Programming from Zero 58 Recursion Docstrings Functions calling functions Adocstringisastring in triple quotes right after the Smallfunctionscanbecombinedtosolve bigger problems. Arecursivefunction calls itself. It needs a base case that stops the recursion, otherwise it runs forever. line. It describes what the function does.def 3 120 print(factorial(5)) defcount_evens(numbers): count = 0 fornin numbers: ifis_even(n): count += 1 returncount print(area_of_circle(5)) print(area_of_circle.__doc__) deffactorial(n): ifn <=1: return 1 returnn * factorial(n - 1) print(count_evens([1, 2, 3, 4, 6, 7])) 78.53975 Return the area of a circle with the given radius. defarea_of_circle(radius): """Return the area of a circle with the given radius.""" return 3.14159 * radius ** 2 def is_even(n): return n % 2 == 0 OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 59 Lambda functions Example: a small calculator Alambda is atiny unnamed function written in one line. It is handy for short jobs, especially with sorted(), map() and filter(). 15 2.0 Cannot divide by zero Unknown operation double = lambda x: x * 2 print(double(7)) print(calculate(10, 5, "add")) print(calculate(10, 5, "divide")) print(calculate(10, 0, "divide")) print(calculate(10, 5, "power")) 14 ['fig', 'kiwi', 'apple', 'banana'] [2, 4, 6] [1, 4, 9, 16, 25, 36] words = ["banana", "kiwi", "apple", "fig"] print(sorted(words, key=lambda w: len(w))) defcalculate(a, b, operation): ifoperation == "add": return a + b elif operation == "subtract": return a - b elif operation == "multiply": return a * b elif operation == "divide": ifb == 0: return "Cannot divide by zero" return a / b return"Unknown operation" 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 OUTPUT

AI CREATION Python Programming from Zero 60 Chapter summary Practice Exercises Common mistakes Good function habits • • • • • • • • • • • 1. 2. 3. 4. 5. 6. 7. 8. Forgetting the brackets when calling. Using a mutable default value such as shared across all calls. Use refers to the function. calls it. . The same list is and create the list inside the function. Giveeachfunction one clear job. Choose names that start with a verb: 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. , Definefunctionswith 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. Write is_even(n)that returns True when n is even. Write celsius_to_fahrenheit(c) and test it with 0, 37 and 100. Write count_vowels(text) that returns how many vowels the text contains. Write average(*numbers) that accepts any number of values. Write is_palindrome(word) that returns True or False. Write a recursive function sum_to(n) that adds 1 + 2 + ... + n. Write fizzbuzz(n) that returns the correct word or number for a single value n. Rewrite the grade program from Chapter 7 as a function get_grade(marks). calculate_taxis_valid, get_name. COMMON MISTAKE COMMON MISTAKE greet defadd_item(item,items=[]) items=None greet("Asha")

AI CREATION Python Programming from Zero 61 CHAPTER 10 Object-Oriented Programming The big idea Classes and objects The __init__ method and attributes Class names use CapWords style, such as or Aclassisablueprint.Anobject (also called an instance) is something built from that blueprint. Sofaryouhave 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. Thespecial method __init__runsautomaticallywhen you create an object. It sets up the object's attributes (its data). The first parameter, self, refers to the object being created. Bruno class Dog: pass dog1 = Dog() dog2 = Dog() print(type(dog1)) print(dog1 is dog2) <class '__main__.Dog'> False dog1 dog2 =Dog("Bruno", 3) =Dog("Misty", 5) print(dog1.name) print(dog2.age) class Dog: def__init__(self, name, age): self.name = name self.age = age OUTPUT OUTPUT Dog BankAccount.

AI CREATION Python Programming from Zero 62 5 Bruno says Woof! Bruno is now 4 4 dog=Dog("Bruno", 3) print(dog.bark()) print(dog.birthday()) print(dog.age) class Dog: def__init__(self, name, age): self.name = name self.age = age account=BankAccount("Asha", 1000) defbark(self): return f"{self.name} says Woof!" classBankAccount: def__init__(self, owner, balance=0): self.owner = owner self.balance = balance defbirthday(self): self.age += 1 return f"{self.name} is now {self.age}" defwithdraw(self, amount): ifamount > self.balance: return "Insufficient funds" self.balance -= amount return f"Withdrew {amount}. Balance: {self.balance}" defdeposit(self, amount): ifamount <= 0: return "Deposit must be positive" self.balance += amount return f"Deposited {amount}. Balance: {self.balance}" Each object has its own copy of the attributes. A method is a function inside a class. Every method takes and as its first parameter. are separate.dog1.name self dog2.name Methods Example: a bank account TIP Think of self as meaning "this particular object". When you call as self automatically. OUTPUT , Python passesdog.bark() dog

AI CREATION Python Programming from Zero 63 a=Student("Asha") b=Student("Ravi") print(a.school, b.school) print(Student.count) Deposited 500. Balance: 1500 Withdrew 300. Balance: 1200 Insufficient funds print(account.deposit(500)) print(account.withdraw(300)) print(account.withdraw(5000)) def__init__(self, name): self.name = name Student.count += 1 class Student: school= count = 0 "Greenfield High" Greenfield High Greenfield High 2 class Book: def__init__(self, title, author): self.title = title self.author = author 'Wings of Fire' by A. P. J. Abdul Kalam def__str__(self): return f"'{self.title}' by {self.author}" book =Book("Wings of Fire", "A. P. J. Abdul Kalam") print(book) OUTPUT OUTPUT OUTPUT An attribute defined directly in the class is shared by all objects. By default, printing an object shows an unhelpful message. Define object appears as text. to control how an Notice how the rules (no negative deposits, no overdrafts) live inside the class. Anyone using the account gets those rules for free. Class attributes The __str__ method __str__

AI CREATION Python Programming from Zero 64 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. Using super() Whenachildclassneeds its own super().__init__(). and Cat did not write their own to give their own behaviour. . They inherited it from but still wants the parent's setup, call . They override Bruno says Woof! Misty says Meow! Creature makes a sound class Animal: def__init__(self, name): self.name = name m=Manager("Meena", 90000, 8) print(m.info()) print(m.salary) classEmployee: def__init__(self, name, salary): self.name = name self.salary = salary classDog(Animal): defspeak(self): return f"{self.name} says Woof!" classCat(Animal): defspeak(self): return f"{self.name} says Meow!" defspeak(self): return f"{self.name} makes a sound" classManager(Employee): def__init__(self, name, salary, team_size): super().__init__(name, salary) self.team_size = team_size animals=[Dog("Bruno"), Cat("Misty"), Animal("Creature")] for animalin animals: print(animal.speak()) definfo(self): return f"{self.name} manages {self.team_size} people" OUTPUT Dog speak __init__ __init__ Animal

AI CREATION Python Programming from Zero 65 OUTPUT OUTPUT 100 w = Wallet() w.add(100) w.add(-50) print(w.get_money()) Meena manages 8 people 90000 class Wallet: def__init__(self): self._money = 0 defget_money(self): return self._money @property defradius(self): return self._radius class Circle: def__init__(self, radius): self._radius = radius defadd(self, amount): ifamount > 0: self._money += amount @radius.setter defradius(self, value): ifvalue <= 0: raise ValueError("Radius must be positive") self._radius = value Properties 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 Apropertyletsyou use a method like an attribute while still running checks. Encapsulationmeanskeeping anobject'sdata 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.

AI CREATION Python Programming from Zero 66 3 28.27 78.54 c = Circle(3) print(c.radius) print(c.area) c.radius = 5 print(c.area) classMathTools: @staticmethod defadd(a, b): return a + b print(MathTools.add(2, 3)) print(MathTools.describe()) 5 This is the MathTools class @classmethod defdescribe(cls): return f"This is the {cls.__name__} class" @property defarea(self): return round(3.14159 * self._radius ** 2, 2) OUTPUT OUTPUT COMMON MISTAKE Forgetting self in a method definition. Writing COMMON MISTAKE Forgetting self. when setting attributes. Writing Common mistakes When should you use classes? Class methods and static methods Use classes when youhave 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. a TypeError when you call it. local variable. Write self.name = name. inside instead of changes only a givesdef bark(): name = name __init__ def bark(self):

AI CREATION Python Programming from Zero 67 Chapter summary Practice Exercises • • • • • • 1. 2. 3. 4. 5. 6. Create a Create a average. Add a Create a method to your Student class. class and two child classes method. with a class with , and Aclassis 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. that each override a method. methods. class with width and height, and methods area() and perimeter(). class that stores a name and a list of marks, with a method that returns the Rectangle Student __str__ Vehicle describe() Extend BankAccount Build a Counter Car Bike transfer(other_account, amount) increment()decrement() and reset()

AI CREATION Python Programming from Zero 68 CHAPTER 11 File Handling Why work with files? Writing to a file The with statement (best practice) Always call Usethebuilt-in when you finish, so the data is safely saved. function. The second argument is the mode. Thewithstatement closes the fileforyouautomatically, even if an error occurs. This is the recommended way to work with files. Variables vanish when yourprogram 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. close() open() Mode "r" "w" "a" "r+" Meaning Read (default). The file must exist. Write. Creates the file, or erases it if it already exists. Append. Adds to the end of the file without erasing. Read and write File saved 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() file = open("notes.txt", "w") file.write("Learning Python\n") file.write("File handling is useful\n") file.close() print("File saved") OUTPUT

AI CREATION Python Programming from Zero 69 Line one Line two Line three print(content) with open("log.txt") as f: print(f.read()) #Readall lines into a list withopen("notes.txt") as f: print(f.readlines()) #Readone line with open("notes.txt") as f: print(repr(f.readline())) #Readeverything as one string with open("notes.txt") as f: print(repr(f.read())) 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") 'apple\nbanana\ncherry\n' 'apple\n' ['apple\n', 'banana\n', 'cherry\n'] apple banana cherry with open("notes.txt", "w") as f: f.write("apple\nbanana\ncherry\n") #Loopthrough the file line by line (best for big files) with open("notes.txt") as f: forline in f: print(line.strip()) OUTPUT OUTPUT removes the newline character at the end of each line. The output ends with an empty line because the text itself ends with and adds another. strip() \n print() Appending to a file Reading files in different ways

AI CREATION Python Programming from Zero 70 OUTPUT OUTPUT OUTPUT False True 5 bytes import os Start Step 1 done Step 2 done Sorry, that file was not found. print(os.path.exists("missing.txt")) try: with open("does_not_exist.txt") as f: print(f.read()) except FileNotFoundError: print("Sorry, that file was not found.") with open("present.txt", "w") as f: f.write("hello") print(os.path.exists("present.txt")) print(os.path.getsize("present.txt"), "bytes") def read_number(text): try: value = int(text) except ValueError: print(f"'{text}' is not a valid number") return None Checking whether a file exists Handling errors with try and except 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) Ifyou tryto openafile that doesnot exist,Pythonraises a FileNotFoundError. You can catch that error instead of letting the program crash.

AI CREATION Python Programming from Zero 71 import csv rows = [ ["name", "marks"], ["Asha", 88], ["Ravi", 72], ["Meena", 95], print(read_number("42")) print(read_number("abc")) Conversion worked Finished checking 42 'abc' is not a valid number Finished checking None else: print("Conversion worked") return value finally: print("Finished checking") defsave_tasks(tasks, filename): with open(filename, "w") as f: fortask in tasks: f.write(task + "\n") loaded = load_tasks("todo.txt") print(loaded) print(load_tasks("nothing_here.txt")) ['Buy milk', 'Study Python', 'Call mom'] [] defload_tasks(filename): try: with open(filename) as f: return [line.strip() for line in f] exceptFileNotFoundError: return [] tasks=["Buy milk", "Study Python", "Call mom"] save_tasks(tasks, "todo.txt") OUTPUT OUTPUT Working with CSV files Example: a simple to-do list saved to a file CSV(comma-separated values)files store tables as plain text, and spreadsheets can open them. Python has a built-in csv module.

AI CREATION Python Programming from Zero 72 } import csv import json Asha 88 Ravi 72 Meena 95 Average: 85.0 ['name', 'marks'] ['Asha', '88'] ['Ravi', '72'] ['Meena', '95'] with open("students.csv") as f: reader = csv.reader(f) forrow in reader: print(row) with open("profile.json") as f: data = { "name": "Asha", "skills": ["Python", "SQL"], "active": True, with open("profile.json", "w") as f: json.dump(data, f, indent=2) total = 0 with open("students.csv") as f: forrow in csv.DictReader(f): print(row["name"], row["marks"]) total += int(row["marks"]) print("Average:", total / 3) ] with open("students.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(rows) with open("students.csv", "w", newline="") as f: f.write("name,marks\nAsha,88\nRavi,72\nMeena,95\n") OUTPUT OUTPUT csv.DictReader names. is even friendlier, because each row becomes a dictionary using the header 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. Working with JSON files

AI CREATION Python Programming from Zero 73 11 Asha Python <class 'dict'> Quarterly summary True summary.txt .txt from pathlib import Path loaded = json.load(f) print(loaded["name"]) print(loaded["skills"][0]) print(type(loaded)) 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) with open("menu.txt", encoding="utf-8") as f: print(len(f.read())) with open("menu.txt", "w", encoding="utf-8") as f: f.write("café Python") OUTPUT OUTPUT OUTPUT You can also convert between JSON text and Python objects without a file, using and json.loads(). When you work with text that includes accented or non-English characters, open the file with encoding="utf-8" so letters display correctly everywhere. 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. json.dumps() Encoding File paths

AI CREATION Python Programming from Zero 74 Chapter summary Practice Exercises Common mistakes COMMON MISTAKE COMMON MISTAKE 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. • • • • • 1. 2. 3. 4. 5. 6. Forgetting that int() or Opening a file in mode erases what was there. Use returns text. A number read from a file is a string until you convert it with if you want to add to an existing file."w" read() float(). "a" Use open()withmodes "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. Write a programthat saves three lines of text to a file and then reads them back. Count the number of lines and words in a text file. Ask the user for a note and append it to diary.txt with the date. Read a CSV of student marks and print the highest scorer. Save a dictionary to a JSON file and load it back. Write a safe number-input function that keeps asking until the user types a valid integer.

AI CREATION Python Programming from Zero 75 CHAPTER 12 Python Libraries Modules and libraries Importing math: mathematics Use tobring a module into your program. loads the module. You write math.sqrt(...). loads one item, so you write just gives the module a short nickname. Youdo not have towrite 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. import import math from math import factorial import math as m factorial(...). import math 7.0 3.141592653589793 120 5 import math as m print(m.ceil(4.2)) import math print(math.sqrt(49)) print(math.pi) print(math.floor(7.8)) print(math.ceil(7.2)) print(math.sqrt(144)) print(math.pow(2, 8)) print(math.gcd(12, 18)) from math import factorial print(factorial(5)) TIP Do not name your own file after a module, such as math.py or file instead of the real module, which causes confusing errors. OUTPUT • • • . Python will import yourrandom.py

AI CREATION Python Programming from Zero 76 7 8 12.0 256.0 6 3 1 import random 5 rock [2, 1, 3, 5, 4] [14, 30, 32] 0.824 born = date(2000, 1, 8) print((d - born).days) 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) moment = datetime(2026, 11, 9, 14, 30) print(round(math.log10(1000))) print(round(math.sin(math.radians(90)))) from datetime import date, datetime, timedelta 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 OUTPUT datetime: dates and times random: chance and games 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.

AI CREATION Python Programming from Zero 77 2026-11-09 2026 11 9 09 November 2026 Monday 2026-12-09 9802 02:30 PM print(moment.strftime("%I:%M %p")) 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)) Counter({'tea': 3, 'coffee': 2, 'juice': 1}) [('tea', 3)] {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']} OUTPUT OUTPUT To get today's date, use , and for the current date and time use counts things for you, which replaces the manual counting loop from Chapter 8.Counter date.today() datetime.now(). Code %Y %m %d %B %A %H:%M Meaning Year (4 digits) Month number Day Month name Weekday name Hour and minute (24 hour) Example 2026 11 09 November Monday 14:30 collections: smarter containers

AI CREATION Python Programming from Zero 78 sys and time statistics: quick data summaries os and shutil: working with files and folders import os import time import sys import statistics 79.33333333333333 81.5 85 9.07 start = time.time() total = sum(range(1_000_000)) elapsed = time.time() - start print(total) print(elapsed < 5) print(sys.version_info.major) True ['a.txt', 'b.txt', 'c.py'] ['b.txt', 'c.py', 'renamed.txt'] ['b.txt', 'c.py'] 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)) print(os.getcwd() != "") os.makedirs("demo_folder", exist_ok=True) 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"))) forname with in ["a.txt", "b.txt", "c.py"]: open(os.path.join("demo_folder", name), "w") as f: f.write("x") OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 79 499999500000 True 3 import requests def square(n): return n * n def greet(name): return f"Hello, {name}!" import helpers print(helpers.square(6)) print(helpers.greet("Asha")) response = requests.get("https://api.github.com") print(response.status_code) data = response.json() print(type(data)) Creating your own module requests: talking to the web Installing third-party packages with pip Any In another file in the same folder, you can write: fileisamodule.Supposeyousave these lines in a file called The examples below need those packages installed, so they are shown for reference. Packageswrittenbyotherpeopleareinstalledfromtheterminal. Here are the ones most beginners meet first. .py helpers.py: Package requests pandas numpy matplotlib openpyxl flask beautifulsoup4 Install command pip install requests pip install pandas pip install numpy pip install matplotlib pip install openpyxl pip install flask pip install beautifulsoup4 What it does Talks to websites and web services Tables of data (like Excel in code) Fast number crunching with arrays Charts and graphs Read and write Excel files Build small websites Read and extract data from web pages

AI CREATION Python Programming from Zero 80 Typical output: A status code of pandas can also read a CSV with data analysis. means success. This opens a window with a bar chart. 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. , which makes it a favourite for 200 pd.read_csv("file.csv") matplotlib: drawing charts pandas: working with tables How to find and choose libraries 0 1 2 Meena 85.0 0 2 Meena name Asha Ravi name Asha marks 88 72 95 marks 88 95 importpandas as pd plt.bar(months, sales) plt.title("Monthly Sales") plt.xlabel("Month") plt.ylabel("Sales") plt.show() import math print("sqrt" in dir(math)) import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] sales = [120, 150, 90, 180] df= pd.DataFrame({ "name": ["Asha", "Ravi", "Meena"], "marks": [88, 72, 95], }) print(df) print(df["marks"].mean()) print(df[df["marks"] > 80]) • • • •

AI CREATION Python Programming from Zero 81 help(math.sqrt) sqrt(x, /) Return the square root of x. True Help on built-in function sqrt in module math: OUTPUT COMMON MISTAKE ModuleNotFoundError: the package is not installed. Run make sure you install it for the same Python you run. COMMON MISTAKE Naming your file the same as a library (for example Chapter summary Practice Exercises Common mistakes • • • • • 1. 2. 3. 4. 5. 6. 7. real library. or , and ), which hides therandom.py requests.py pip install packagename Amodule is a Python file, and a library is a collection of modules. Import with , and . The standard library includes json and csv. Third-party packages are installed with pip. The popular ones are and matplotlib. Any .py file can be imported as your own module. , , , Use mathto compute the area of a circle with radius 7. Use random to roll two dice and print the total. Use datetime to calculate how many days remain until your next birthday. Use Counter to find the most common word in a sentence. Use statistics to find the mean and median of a list of 8 numbers. Create your own module with two functions and import it into another file. Install requests and fetch the status code of any website. import from ... import import ... as mathrandomdatetimecollections, statistics, os, requests, pandas, numpy

AI CREATION Python Programming from Zero 82 CHAPTER 13 Practical Python Projects Why build projects? Project 1: Number Guessing Game Skillsused: 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. Reading aboutPython 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. play() import random I am thinking of a number between 1 and 50. Your guess: 25 Too high! Your guess: abc def play(): secret= random.randint(1, 50) attempts = 0 print("I am whileTrue: thinking of a number between 1 and 50.") guess_text = input("Your guess: ") ifnot guess_text.isdigit(): print("Please continue type a whole number.") guess = int(guess_text) attempts += 1 ifguess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print(f"Correct! break You got it in {attempts} attempts.") SAMPLE RUN

AI CREATION Python Programming from Zero 83 import os FILENAME = "todo.txt" 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. defshow_tasks(tasks): ifnottasks: print("Your list is empty.") return fornumber, task in enumerate(tasks, start=1): print(f"{number}. {task}") defload_tasks(): ifnotos.path.exists(FILENAME): return [] with open(FILENAME) as f: return [line.strip() for line in f if line.strip()] def main(): tasks=load_tasks() whileTrue: print("\n1. Show tasks 2. Add task 3.Remove task choice = input("Choose an option: ").strip() ifchoice == "1": show_tasks(tasks) elif choice == "2": task = input("New task: ").strip() if task: tasks.append(task) save_tasks(tasks) 4. Quit") def save_tasks(tasks): with open(FILENAME, "w") as f: for task in tasks: f.write(task + "\n") How it works: 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. •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

AI CREATION Python Programming from Zero 84 main() 1.Showtasks 2. Add task Chooseanoption: 1 Your listis empty. 1.Showtasks 2. Add task Chooseanoption: 2 Newtask:Buy milk Task added. 1.Showtasks 2. Add task Chooseanoption: 2 Newtask:Study Python Task added. 1.Showtasks 2. Add task Chooseanoption: 1 1.Buymilk 2.Study Python 1.Show tasks 2. Add task Choose an option: 3 1. Buy milk 2. Study Python Number to remove: 1 Removed: Buy milk 1.Show tasks 2. Add task Choose an option: 4 Goodbye! 3. Remove task 3. Remove task 3. Remove task 3. Remove task 3. Remove task 3. Remove task 4. Quit 4. Quit 4. Quit 4. Quit 4. Quit 4. Quit 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.") How it works: Here is one session. The tasks are saved to list is still there. 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. , so the next time you run the program thetodo.txt SAMPLE RUN • • •

AI CREATION Python Programming from Zero 85 Try these upgrades: mark tasks as done; add due dates; sort by priority. 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. Project 3: Expense Tracker main() expenses = [] from collections import defaultdict Expense Tracker. Type 'done' as the category to finish. Category: food Amount: 250 def main(): print("Expense whileTrue: Tracker. Type 'done' as the category to finish.") category = input("Category: ").strip().lower() ifcategory == "done": break try: amount = float(input("Amount: ")) except ValueError: print("That is not a number. Try again.") continue add_expense(category, amount) ifexpenses: print_report() else: print("No expenses entered.") defprint_report(): print("--- Expense Report ---") totals= summary_by_category() ordered= sorted(totals.items(), forcategory, amount in ordered: key=lambdax: x[1], reverse=True) share = amount / total_spent() * 100 print(f"{category:<12} {amount:>8.2f} ({share:.0f}%)") print("-" * 24) print(f"{'Total':<12} {total_spent():>8.2f}") defadd_expense(category, amount, note=""): expenses.append({"category": category, "amount": amount, "note": note}) def total_spent(): def summary_by_category(): return sum(e["amount"] for e in expenses) totals = defaultdict(float) for e in expenses: totals[e["category"]] += e["amount"] return dict(totals) SAMPLE RUN

AI CREATION Python Programming from Zero 86 ] def main(): score = 0 forquestion in questions: ifask(question): print("Correct!") score += 1 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 food transport 1500.00 370.00 80.50 (77%) (19%) (4%) ------------------------ Total 1950.50 defask(question): print("\n" + question["q"]) fornumber, option in enumerate(question["options"], start=1): print(f" {number}. {option}") reply=input("Your answer (1-4): ").strip() returnreply.isdigit() and int(reply) == question["answer"] 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}, 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. 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

AI CREATION Python Programming from Zero 87 main() You scored 3 out of 4 (75%). What is the result of 7 // 2? 1. 3.5 2. 3 3. 4 4. 1 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 Which symbol starts a comment in Python? 1. // 2. # 3. -- 4. /* Your answer (1-4): 2 Correct! 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}%).") SAMPLE RUN 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.

AI CREATION Python Programming from Zero 88 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. Suppose computer): contains photo.jpg, report.pdf, notes.txt, clip.mp4, . The output looks like this (the order of the files may differ on your downloads_test archive.zip and logo.PNG } import os import shutil organize("downloads_test") 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. CATEGORIES = { "Images": [".jpg", ".jpeg", ".png", ".gif"], "Documents": [".pdf", ".docx", ".txt", ".xlsx"], "Videos": [".mp4", ".mkv", ".mov"], defcategory_for(filename): extension = os.path.splitext(filename)[1].lower() forcategory, extensions in CATEGORIES.items(): ifextension in extensions: return category return"Other" deforganize(folder): moved = 0 forname in os.listdir(folder): path = os.path.join(folder, name) ifnot 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 moved += 1 {name} -> {category_for(name)}") print(f"Done. {moved} files organized.") SAMPLE RUN 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.

AI CREATION Python Programming from Zero 89 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. When you have an idea, follow these steps: 1. 2. 3. 4. 5. 6. Describe it in one sentence. "A program that tracks my daily water intake." List the inputs and outputs. What does the user type? What should appear? Break it into small functions. One job per function. Build the smallest working version first. Get something running, even if it is ugly. Test it often. Run it after every small change. Improve it step by step. Add one feature at a time. 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. • • • Chapter summary More project ideas How to design your own project Project Password generator Unit converter Contact book Rock, paper, scissors Simple calculator with a menu Word counter for a text file Hangman game Student marks analyzer Birthday reminder Weather lookup What you will practise random, strings, loops functions, conditions, dictionaries dictionaries, JSON files random, conditions, loops functions, error handling files, strings, Counter strings, lists, loops CSV, statistics, functions datetime, files requests, JSON

AI CREATION Python Programming from Zero 90 • 1. 2. 3. 4. 5. 6. Always test programs that change or delete files on practice data first. Add a "give up" option to the guessing game that reveals the number. Add a "mark as done" option to the to-do list. Make the expense tracker save its data to a CSV file and load it on the next run. Add five more questions to the quiz and shuffle the order each time. Extend the file organizer so that it asks which folder to organize. Build one project from the ideas table and write a short description of how it works. Practice Exercises

AI CREATION Python Programming from Zero 91 CHAPTER 14 Common Errors and Debugging Errors are normal Every programmer, from afirst-week beginner to a senior engineer, sees errors every day. An error How to read a traceback The three kinds of errors Whenaruntimeerrorhappens,Python prints a traceback. Read it from the bottom up. Logic errors are the hardest, because Python has nothing to complain about. You find them by checking the results. 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. 1. The last line tells you the error type and a short message: NameError: name 'prices_list' is not defined. The line above it shows the exact line of code that failed, and its line number (line 4). The lines above show how the program got there: calculate_total was called from line 8. 2. 3. Start with the last line and ask: what does this message mean, and which name or value is the problem? Logic error Kind Syntax error Runtime error (exception) When it appears Before the program runs. Python cannot understand the code. While the program runs. Python understood the code but something went wrong. The program runs without any error message but gives the wrong answer. Dividing by zero Example Missing colon or bracket Using + when you meant * 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

AI CREATION Python Programming from Zero 92 NameError Syntax errors IndentationError Pythonrefusestorun 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 Youusedaname that does not exist. Usually it is a typo, or the variable was never created. 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. SyntaxError invalid syntax try: print(scoree) except NameError as e: print(type(e).__name__, "-", e) code = 'if 5 > 3 print("yes")' try: compile(code, "example", "exec") except SyntaxError as e: print(type(e).__name__) print(e.msg) code = "def f():\nreturn 1" try: compile(code, "example", "exec") except IndentationError as e: print(type(e).__name__) print(e.msg) NameError - name 'scoree' is not defined IndentationError expected an indented block after function definition on line 1 OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 93 Fix: convert the value ( You asked for a position that does not exist. The type is right, but the value is not acceptable. You used a value of the wrong type for an operation. ) or use an f-string. Fix: validate the input before converting, or wrap the conversion in and Fix: check the spelling and capital letters, and make sure the variable was assigned before you use it. TypeError IndexError ValueError 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) try: number = int("twelve") except ValueError as e: print(type(e).__name__, "-", e) colors = ["red", "green", "blue"] try: print(colors[3]) except IndexError as e: print(type(e).__name__, "-", e) IndexError - list index out of range TypeError - can only concatenate str (not "int") to str TypeError - object of type 'int' has no len() ValueError - invalid literal for int() with base 10: 'twelve' OUTPUT OUTPUT OUTPUT str(25), int("5") try except.

AI CREATION Python Programming from Zero 94 Fix: use or check with Fix: check the type of the object with Fix: remember that the last valid index is You asked a dictionary for a key it does not have. You used a method or attribute that the object does not have. and look up its real methods with .get() type(x) if key in dictionary. len(list) - 1. dir(x). KeyError AttributeError ZeroDivisionError KeyError - 'city' unknown try: print(10 / 0) except ZeroDivisionError as e: print(type(e).__name__, "-", e) try: "hello".append("!") except AttributeError as e: print(type(e).__name__, "-", e) ZeroDivisionError - division by zero student = {"name": "Asha", "age": 21} try: print(student["city"]) except KeyError as e: print(type(e).__name__, "-", e) print(student.get("city", "unknown")) AttributeError - 'str' object has no attribute 'append' OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 95 A quick error reference Catching exceptions with try and except FileNotFoundError and ModuleNotFoundError print(safe_divide(10, 2)) print(safe_divide(10, 0)) 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) defsafe_divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Please provide numbers" FileNotFoundError ModuleNotFoundError - No module named 'not_a_real_module' OUTPUT You can handle errors gracefully instead of crashing. Fix: check the file name, extension and folder. For modules, run for the package.pip install Error SyntaxError IndentationError NameError TypeError ValueError IndexError KeyError ZeroDivisionError AttributeError FileNotFoundError Usual cause Broken grammar Wrong spacing Unknown name Wrong type Bad value Position too big Missing key Divided by zero Wrong method Wrong path First thing to check Colons, brackets, quotes Four spaces, no mixed tabs Spelling, missing assignment Convert with int(), str() The input being converted len() and the last index Use .get() The divisor type() and dir() Name, folder, extension

AI CREATION Python Programming from Zero 96 All checks passed 5.0 Cannot divide by zero Please provide numbers try: set_age(-5) except ValueError as e: print("Error:", e) print(safe_divide(10, "x")) assert average([2, 4, 6]) == 4 assert average([10]) == 10 print("All checks passed") Error: Age must be between 0 and 120 def average(numbers): return sum(numbers) / len(numbers) def set_age(age): ifage < 0 or age > 120: raise ValueError("Age must be between 0 and 120") return age OUTPUT OUTPUT OUTPUT COMMON MISTAKE Avoid a bare expect. that catches everything. It hides real bugs. Catch the specific errors youexcept: Assertions Raising your own errors Use tosignalthatsomethingis wrong in your own functions. Anassertstatement 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. raise

AI CREATION Python Programming from Zero 97 Finding a logic error Debugging with print() Using the built-in debugger Thesimplest and mostpopulardebugging tool is points to see what is really happening. Remove the debug prints when you have fixed the problem. . Show the values of variables at key This function shouldreturnthe average of a list, but it gives the wrong answer. No error appears, so you have to investigate. Python includesa debuggercalled pdb. Put breakpoint() where you want the program to pause. You can then look at variables and step through the code line by line. 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. print() 21.0 def buggy(numbers): total = 0 for n in numbers: breakpoint() total += n print(average([10, 20, 30])) DEBUG: running subtotal = 100 DEBUG: running subtotal = 300 DEBUG: total = 330.0 defaverage(numbers): total = 0 fornin numbers: total += n returntotal / len(numbers) + 1 deftotal_price(prices, tax_rate): subtotal = 0 forpin prices: subtotal += p print("DEBUG: running subtotal =", subtotal) total=subtotal * (1 + tax_rate) print("DEBUG: total =", total) returntotal total_price([100, 200], 0.1) OUTPUT OUTPUT

AI CREATION Python Programming from Zero 98 return total When it pauses you will see a prompt. The most useful commands are: 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. 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. Read the error message from the bottom up. Do not skip it. Find the line it points to, and check the line just before it too. Reproduce the problem with the smallest example you can. Check your assumptions. Print variables and types. Is the value what you expected? Change one thing at a time, then run again. Search the error message online. Someone has almost certainly seen it before. Include the error type and the key words. 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. Take a break. Fresh eyes spot mistakes that tired eyes miss. (Pdb) Command n s c p variable l q What it does Run the next line Step into a function call Continue until the next breakpoint Print a variable's value Show the code around the current line Quit the debugger Habits that prevent bugs A step-by-step debugging method • • • • • • 1. 2. 3. 4. 5. 6. 7. 8.

AI CREATION Python Programming from Zero 99 Chapter summary Practice Exercises • • • • • 1. 2. 3. 4. 5. 6. Errors give youinformation. 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. For each error typeinthis chapter, write a short line of code that causes it, then fix it. Find the bug: for i in range(1, 5): print(i * i. What is the error and the fix? 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). Write a function safe_int(text) that returns the integer, or None if the text is not a number. Add a try and except to a program that divides two numbers typed by the user. Take any program from Chapter 13, add a deliberate bug, and use print() to track it down.

AI CREATION Python Programming from Zero 100 CHAPTER 15 Exercises and Interview Questions How to use this chapter Part 1: Sample solutions to chapter exercises Chapter 3: area of a rectangle Thischapter hasfourparts: 1. 2. 3. 4. Sample solutions to selected exercises from earlier chapters. Mixed challenges to test everything together. Interview questions with short, clear answers. 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. Chapter 4: splitting seconds into hours, minutes and seconds 1 2 5 Area = 40 length = 8 width = 5 area = length * width print(f"Area = {area}") total_seconds = 3725 hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 print(hours, minutes, seconds) OUTPUT OUTPUT

AI CREATION Python Programming from Zero 101 Chapter 7: ticket pricing Chapter 5: palindrome check and counting vowels Chapter 6: duplicates and swapping dictionary keys True False 6 3 0 10 50 30 100 65 60 [1, 2, 3, 4] {1: 'a', 2: 'b'} def ticket_price(age): ifage< 5: return 0 elif age <= 17: return 50 elif age <= 59: return 100 else: return 60 def is_palindrome(word): word = word.lower() return word == word[::-1] numbers = [1, 2, 2, 3, 3, 3, 4] print(sorted(set(numbers))) foragein[3, 10, 30, 65]: print(age, ticket_price(age)) print(is_palindrome("Madam")) print(is_palindrome("Python")) print(count_vowels("Learning Python is fun")) def count_vowels(text): return sum(1 for ch in text.lower() if ch in "aeiou") original = {"a": 1, "b": 2} swapped = {value: key for key, value in original.items()} print(swapped) OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 102 Chapter 9: recursion Chapter 8: factorial, Fibonacci, pyramid and primes 55 print(sum_to(10)) # Factorial of 6 result = 1 for n in range(1, 7): result *= n print(result) #First10Fibonacci numbers a,b =0,1 fib = [] for_in range(10): fib.append(a) a,b =b, a + b print(fib) def sum_to(n): ifn ==0: return 0 returnn + sum_to(n - 1) #Pyramid with 5 rows forrow in range(1, 6): print(" " * (5 - row) + "*" * (2 * row - 1)) 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] #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 OUTPUT

AI CREATION Python Programming from Zero 103 Chapter 10: Rectangle and Student classes Chapter 11: counting lines and words in a file Lines: 3 Words: 9 24 20 Asha: average 86.3 lines = 0 words = 0 with open("sample.txt") as f: forline in f: lines += 1 words += len(line.split()) print("Lines:", lines) print("Words:", words) class Student: def__init__(self, name, marks): self.name = name self.marks = marks r=Rectangle(4, 6) print(r.area(), r.perimeter()) print(Student("Asha", [88, 92, 79])) 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) def average(self): return sum(self.marks) / len(self.marks) def __str__(self): return f"{self.name}: average {self.average():.1f}" with open("sample.txt", "w") as f: f.write("Python is fun\nFiles are useful\nPractice every day\n") OUTPUT OUTPUT

AI CREATION Python Programming from Zero 104 Beginner level Intermediate level Chapter 14: a safe integer converter 42 None 7 defsafe_int(text): try: return int(text) except ValueError: return None print(safe_int("42")) print(safe_int("forty")) print(safe_int(" 7 ")) OUTPUT Part 2: Mixed challenges Print a multiplication table (1 to 10) for a number the user chooses. Convert kilometres to miles (1 km = 0.621371 miles). Check whether a number is positive, negative or zero. Print the sum of the digits of a number (for 472, the answer is 13). Count how many times a chosen letter appears in a sentence. Make a program that tells the user whether a year is a leap year. Create a list of 10 numbers and print only the even ones. Print the reverse of a number (for 1234, print 4321). Trythesewithoutlookingatsolutions. Each uses several skills from the book. Find the second largest number in a list without sorting it. Write a function that checks whether two words are anagrams (for example, "listen" and "silent"). Count the frequency of every word in a paragraph and print the top three. Write a program that removes duplicates from a list but keeps the original order. Create a dictionary that maps each letter of the alphabet to its position (a is 1, b is 2). Write a simple login system that allows only three password attempts. Read a CSV of products and prices and print the most expensive product. Write a function that generates a random password of a chosen length. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

AI CREATION Python Programming from Zero 105 Advanced level 6. What is the difference between 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. and 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. 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. 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. 17. 18. 19. 20. 21. 22. == checks whether two values are equal. memory. Build a contact book class that saves and loads contacts from a JSON file. Write a function that checks whether brackets in a string are balanced, such as "{[()]}". Build a text-based Hangman game. Write a decorator that prints how long a function takes to run. Create a Library class with Book objects, borrowing and returning. Write a program that reads a text file and reports the number of lines, words, characters and the five most common words. checks whether two names refer to the same object in 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. is Part 3: Interview questions and answers == is? a = [1, 2, 3] b = [1, 2, 3]

AI CREATION Python Programming from Zero 106 True False True c = a print(a == b) print(a is b) print(a is c) [1, 2, [3, 4]] [1, 2, 3, 4] a = [1, 2] a.append([3, 4]) print(a) b=[1, 2] b.extend([3, 4]) print(b) OUTPUT OUTPUT 8. What are 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. and 9. What is a lambda function? A lambda is a small anonymous function written in one expression, such as 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 11. What is the difference between and by one. adds one item (even if that item is a list). in range(5) if n % 2 == 0]. It is usually shorter and faster than the equivalent loop. *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. adds every item of an iterable one . It append() extend() lambda x: x * 2 [n*nfor n *args **kwargs? append() extend()?

AI CREATION Python Programming from Zero 107 14. What are and 15. Explain the four pillars of OOP. 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. 13. What is a function, and how is it different from a method? 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. A function is a reusable block of code defined with class and is called on an object, such as 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. . A method is a function that belongs to a . is the constructor method that runs when an object is created and sets up its attributes. is the first parameter of an instance method and refers to the object itself. import copy [[1, 2, 99], [3, 4]] [[1, 2], [3, 4]] original[0].append(99) print(shallow) print(deep) original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) OUTPUT __init__ self def "hello".upper() self __init__? • • • •

AI CREATION Python Programming from Zero 108 18. What does 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. 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. do?if __name__ == "__main__": 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. Hello HELLO, ASHA [1, 2, 3, 4, 5] def greet(): return "Hello" print(greet("asha")) defcount_up(limit): n = 1 whilen<= limit: yield n n+= 1 print(list(count_up(5))) if__name__ == "__main__": print(greet()) @shout defgreet(name): return f"hello, {name}" defshout(func): defwrapper(*args, **kwargs): return func(*args, **kwargs).upper() return wrapper OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 109 Reverse a string 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. Check for an anagram 25. How do you handle files safely? 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. 23. What are Python's built-in data types? Numbers ( mappings ( 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. Use the ( , , ), sets ( ), text ( ), booleans ( ), binary types ( ), sequences ( , , ) and statement, which closes the file automatically, choose the correct mode ), and handle errors such as FileNotFoundError with try and except. ), with open(...) "r""w", "a" int, floatcomplex str dict set, frozenset bool listtuple, range bytes bytearray NoneType. Part 4: Coding interview problems with solutions True False nohtyp defreverse_string(text): return text[::-1] print(reverse_string("python")) print(is_anagram("listen", "silent")) print(is_anagram("hello", "world")) defis_anagram(a, b): return sorted(a.lower()) == sorted(b.lower()) OUTPUT OUTPUT

AI CREATION Python Programming from Zero 110 Two sum Return the positions of two numbers that add up to a target. Find duplicates in a list Remove duplicates but keep the order [2, 3] [0, 1] [1, 2] [4, 1, 2, 3] def unique_in_order(items): seen =set() result= [] foritem in items: ifitem not in seen: seen.add(item) result.append(item) returnresult def find_duplicates(items): seen =set() duplicates = set() for item in items: ifitem in seen: duplicates.add(item) seen.add(item) returnsorted(duplicates) print(two_sum([2, 7, 11, 15], 9)) print(two_sum([3, 2, 4], 6)) print(unique_in_order([4, 1, 4, 2, 1, 3])) deftwo_sum(numbers, target): seen = {} forindex, number in enumerate(numbers): needed = target - number ifneeded in seen: return [seen[needed], index] seen[number] = index returnNone print(find_duplicates([1, 2, 3, 2, 4, 3, 5])) OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 111 Balanced brackets Flatten a nested list Most common word Second largest number 30 [1, 2, 3, 4, 5, 6, 7] [('the', 3), ('and', 2)] from collections import Counter defsecond_largest(numbers): unique = sorted(set(numbers)) iflen(unique) < 2: return None return unique[-2] defflatten(items): result= [] foritem in items: ifisinstance(item, list): result.extend(flatten(item)) else: result.append(item) returnresult text = "the cat and the dog and the bird" words = text.split() print(Counter(words).most_common(2)) def is_balanced(text): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in text: if ch in "([{": stack.append(ch) elif ch in ")]}": print(second_largest([10, 40, 30, 40, 20])) print(flatten([1, [2, 3], [4, [5, 6]], 7])) OUTPUT OUTPUT OUTPUT

AI CREATION Python Programming from Zero 112 True False False 55 12586269025 print(fib(10)) print(fib(50)) [1, 2, 3, 4, 7, 9, 10] print(is_balanced("{[()]}")) print(is_balanced("{[(])}")) print(is_balanced("(((")) from functools import lru_cache @lru_cache(maxsize=None) def fib(n): ifn <2: return n returnfib(n - 1) + fib(n - 2) defmerge_sorted(a, b): result= [] i = j = 0 whilei< len(a) and j < len(b): ifa[i] <= b[j]: result.append(a[i]) i else: += 1 result.append(b[j]) j += 1 result.extend(a[i:]) result.extend(b[j:]) returnresult print(merge_sorted([1, 4, 7], [2, 3, 9, 10])) if not stack or stack.pop() != pairs[ch]: return False returnnot stack OUTPUT OUTPUT OUTPUT Merge two sorted lists Recursive Fibonacci with memory

AI CREATION Python Programming from Zero 113 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! Where to go from here Tips for the interview itself • • • • • • Younowhaveasolidfoundation.Here is a simple 30-day plan to keep your momentum: 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. Thinkaloud. Interviewers careabout 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. Days 1 to 7 8 to 14 15 to 21 22 to 30 Focus Re-do the chapter exercises from memory. Build Projects 1 and 4 again with your own twists. Solve one small coding problem a day (Part 2 and Part 4). Build one bigger project from the ideas list in Chapter 13. Choose a direction and start learning it