Pustakam Library

Free Programming learning guide

Python Programming for Beginners: A Step-by-Step Guide

Python Programming for Beginners: A Step-by-Step Guide — a free beginner-level guide covering how to learn python programming from scratch. Learn with...

113 min read12 chaptersbeginner

What you will learn

  1. Getting Started with Python
  2. Variables and Core Data Types
  3. Control Flow and Decision Making
  4. Loops and Repetition
  5. Built-in Data Structures
  6. Functions and Code Reusability
  7. Error Handling and Debugging
  8. File Handling
  9. Object-Oriented Programming Basics
  10. Modules and the Python Ecosystem
  11. Fetching Data from the Web
  12. Final Project Planning and Execution

1. Getting Started with Python

Why Python? Imagine you are an accountant who spends the last Friday of every month manually copying data from fifty different spreadsheets into a single summary report. It takes four hours, it is mind-numbingly boring, and if you lose focus for even a second, you might paste a row in the wrong place and ruin the entire dataset. Now imagine writing a few dozen lines of instructions that tell your computer how to do this for you. The computer completes the task in three seconds. You get your Friday afternoon back. This is the power of programming. Python is simply the language you will use to give the computer those instructions. It is renowned for having a syntax (the rules for how the code must be written) that closely resembles plain English, making it the most popular language in the world for people learning to code from scratch. Before you can automate your spreadsheets, analyze data, or build a web application, you need a place to write and run your code. Installing Python on Your Computer A computer, out of the box, does not inherently know how to read Python. It needs a specific piece of software called an interpreter. An interpreter takes the human-readable Python code you write and translates it into the machine-readable instructions (1s and 0s) that your computer's processor can execute. To get the Python interpreter, you need to download it from the official source. Downloading the Installer 1. Open your web browser and navigate to python.org/downloads. 2. The website will automatically detect your operating system (Windows, macOS, or Linux) and display a button to download the latest stable version of Python. Click it. 3. Once the file finishes downloading, open it to launch the installer. The Golden Rule of Windows Installation If you are using a Mac, the installation process is straightforward: just click "Continue" and "Install" until it finishes. However, if you are using Windows, you will see a setup window with a checkbox at the bottom that says "Add Python to PATH" (or sometimes "Add python.exe to PATH"). Check this box before clicking "Install Now". PATH is a system variable—a list of folder locations—your computer uses to find programs. If you do not add Python to your PATH, your computer will install Python, but it won't know where to find it when you try to run it later. This is the single most common stumbling block for beginners. If you miss this checkbox, you will have to uninstall Python and run the installer again. Verifying the Installation Once the installation finishes, you should verify that your computer now recognizes Python. 1. Open your computer's command line interface: - Windows: Press the Windows key, …

2. Variables and Core Data Types

The Box Analogy: Storing Data in Memory Imagine you are packing for a move. You have a cardboard box, and you write "Kitchen Stuff" on the side with a marker. You fill the box with plates, put a lid on it, and set it in the truck. Later, when you unpack, you look for the box labeled "Kitchen Stuff," open it, and retrieve your plates. In Python, a variable is that labeled box. It is a named location in your computer's memory used to store data. When you create a variable, you give it a name (the label on the box) and assign it a value (the contents inside). Whenever you use that name in your code, Python looks inside the box and uses whatever is stored there. In the previous chapter, we used the REPL to run simple commands. Now, we will write scripts—saved in .py script files—so our code isn't lost when we close the terminal. Open your IDE (like Visual Studio Code), create a new text file, and save it as variables.py. Assigning and Reassigning Variables To put data into a variable, you use the assignment operator, which is the equals sign (=). It takes the value on the right and stores it in the variable name on the left. If you run this script, Python will output 100. Variables are called "variables" because their contents can vary or change. You can reassign a variable by simply giving it a new value. When you reassign a variable, Python throws away the old value and replaces it with the new one. You can also use the variable's current value to calculate its new value. Let's say the player finds a bonus worth 25 points: Python also provides a handy shortcut for this called an augmented assignment operator. Instead of writing score = score + 25, you can write score += 25. It does the exact same thing but requires less typing. Naming Your Variables Python has a few strict rules and some strong conventions for naming variables: Rules: Names can contain letters, numbers, and underscores (), but they cannot start with a number. They also cannot contain spaces. player1 is valid; 1player and player 1 are not. Conventions: Python developers use snakecase for variable names. This means all letters are lowercase, and words are separated by underscores (e.g., firstname, totalprice). Descriptive names: Always name your variables based on what they represent. x = 100 tells you nothing, but daysuntillaunch = 100 makes your code instantly readable. Core Data Types In the previous chapter, we briefly mentioned the word string when discussing text. Now, let's formally define the fundamental building blocks of data in Python. Every value in Python …

3. Control Flow and Decision Making

The Crossroads of a Program Imagine you are writing a script to manage access to a building. If the person scanning their badge is an employee, the door should unlock. If they are a visitor, the system should ask them to sign in at the front desk. If their badge is unrecognized, the door should stay locked, and an alarm should sound. Up to this point, the Python scripts you have written likely execute strictly from top to bottom. The interpreter reads your script files line by line, assigning variables and processing data sequentially. But real-world applications rarely follow a single, straight path. They encounter crossroads where they must evaluate information and choose a specific direction. This concept is called control flow. It is the mechanism that allows you to dictate the execution path of your program based on specific conditions. By using conditional logic, you transform your code from a rigid, linear sequence into a dynamic system capable of making decisions. Evaluating Conditions: Booleans and Comparison Operators Before a program can make a decision, it needs something to base that decision on. It must evaluate a condition. A condition is simply a statement that can be evaluated as either True or False. In Python, True and False are special keywords of the boolean data type. While we discussed core data types like strings and integers previously, booleans are the foundation of decision-making because they represent binary truth values. To generate these boolean values, we use comparison operators. These operators compare two values and return True if the comparison is valid, or False if it is not. Here are the primary comparison operators in Python: == (Equal to): Checks if two values are exactly the same. Note the double equals sign. A single = is used to assign variables, while == is used to compare them. != (Not equal to): Checks if two values are different. (Greater than): Checks if the value on the left is larger than the value on the right. < (Less than): Checks if the value on the left is smaller than the value on the right. = (Greater than or equal to): Checks if the left value is larger than or exactly equal to the right. <= (Less than or equal to): Checks if the left value is smaller than or exactly equal to the right. You can test these directly in the REPL (Read-Evaluate-Print Loop). Open your terminal and type the following: Notice that the interpreter evaluates the expression and prints the resulting boolean value. When we write full scripts in an IDE (Integrated Development Environment) like Visual Studio Code (VS Code), we will use these same comparison operators to trigger actions based on …

4. Loops and Repetition

The Power of Repeating Yourself Imagine you are writing a program to send a personalized welcome message to five new users of your app. Using the tools from the first three modules, you might write something like this: This works perfectly. But what happens tomorrow when you have 50 new users? Or 500? Or what if you need to send a message to every user in a database that updates every second? Typing out hundreds of identical lines of code is tedious, slow, and highly prone to mistakes. Programmers have a golden rule for situations like this: DRY (Don't Repeat Yourself). To achieve this, Python provides loops. A loop is a programming structure that allows you to execute a block of code multiple times automatically. Instead of copying and pasting code, you write the instruction once, and tell Python how many times to repeat it. In this chapter, we will explore the two primary loops in Python—the for loop and the while loop—along with tools to control how they behave. Iterating with for Loops The most common loop you will use in Python is the for loop. A for loop is used to iterate (a programming term meaning "to travel through items one by one") over a sequence. You already met a sequence in Module 2: the string. A string is a sequence of characters. Later modules will introduce other sequences like lists and dictionaries, but the logic of the for loop remains exactly the same. The Anatomy of a for Loop A for loop in Python has a specific structure: Let's look at a concrete example using a string: If you run this code in your IDE (like VS Code) or the REPL, the interpreter will output: Here is exactly what Python did behind the scenes: 1. It saw the sequence "Python". 2. It looked at the first item in that sequence ('P'). 3. It temporarily assigned that item to the variable letter. 4. It ran the indented code block (print(letter)). 5. It went back to the top, grabbed the next item ('y'), assigned it to letter, and repeated the process until it ran out of items. Real-World Example: Formatting Usernames Imagine you have a string representing a username, and you want to count how many vowels are in it. You can use a for loop to check each character one by one. Output: Notice how we combined the if statement from Module 3 (Control Flow and Decision Making) with our new for loop. The loop checks every letter, but only updates the vowelcount variable when the if condition is met. Generating Number Sequences with range() Strings are great, but often you just want a loop to run a …

5. Built-in Data Structures

Moving Beyond Single Variables Imagine you are writing a program to manage your weekly grocery list. If you only need to track three items, you could easily create three separate variables: But what happens when your list grows to twenty items? Or what if you are building an application to track the daily high temperatures for an entire year? Creating 365 separate variables (tempday1, tempday2, etc.) is tedious, difficult to read, and practically impossible to maintain. In Chapter 2, we explored Python’s core data types like strings, integers, and booleans. These are designed to hold a single piece of information. To write useful, scalable programs, we need a way to group multiple values into a single collection variable. Python provides four built-in data structures specifically for this purpose: lists, tuples, dictionaries, and sets. Each one organizes data differently, serving a unique purpose in your code. Storing Ordered Collections Using Lists A list is a data structure that holds an ordered collection of items. In Python, lists are incredibly flexible: you can add items to them, remove items, or change existing items after the list has been created. In programming terms, this makes lists mutable (changeable). Creating and Accessing Lists You create a list by placing your items inside square brackets [], separated by commas. Lists can hold any data type, and they can even hold a mix of different data types in the same list. Because lists maintain the order of their items, you can retrieve a specific item using its position. In Python, positions are called indices (plural of index). Python uses zero-based indexing, meaning the first item is at index 0, the second is at index 1, and so on. We introduced this concept briefly when looking at strings, and it works exactly the same way here. You can also count backward from the end of the list using negative indices. An index of -1 gives you the last item, -2 gives the second-to-last, etc. Modifying Lists Because lists are mutable, you can change an item by assigning a new value to a specific index. You can also add new items to the end of a list using the .append() method, or insert them at a specific position using .insert(). (We will cover creating your own methods in Chapter 9, but for now, know that a method is simply a function that belongs to a specific data type, called using a dot .). Real-World Example: A Shopping Cart Imagine you are building the checkout logic for an online store. A list is the perfect structure for a shopping cart because the user will constantly add and remove items before finalizing their purchase. Grouping Immutable Data Using Tuples A …

6. Functions and Code Reusability

The Problem with Repetition Imagine you are writing a program to calculate the total cost of a shopping cart. To find the total, you need to add up the prices of all items, apply a discount code, calculate the sales tax, and print the final formatted price. If your program only did this once, you might write out all those steps linearly from top to bottom in your script files. But what happens when you have three different shopping carts? You could copy and paste the code three times. However, if you later realize your sales tax calculation was wrong, you have to find and fix that calculation in three separate places. In programming, repeating code is a recipe for errors. It makes your programs longer, harder to read, and incredibly difficult to maintain. The solution to this problem is code reusability—the ability to write a piece of code once and use it as many times as needed. In Python, the primary tool for achieving code reusability is the function. You have already used several built-in functions throughout previous chapters, such as print() for displaying output or len() for finding the length of a string. In this chapter, you will move from being a consumer of functions to a creator, learning how to encapsulate your own logic into reusable blocks. Defining Functions with def A function is essentially a named, self-contained block of code designed to perform a specific task. You can think of it as a mini-program within your main program. To create a function in Python, you use the def keyword, followed by the function name, a set of parentheses (), and a colon :. The code that makes up the function—called the function body—is written on the following indented lines. Here is the basic anatomy of a function definition: A few important rules to remember: Naming: Function names follow the same rules as variables. They can contain letters, numbers, and underscores, but cannot start with a number. Indentation: Just like the loops and control flow structures you learned about in previous chapters, Python uses indentation to know which lines belong to the function. Everything indented under the def statement is part of the function. Definition vs. Execution: Writing def greetuser(): does not run the code inside it. It simply teaches the Python interpreter what this function does. To actually execute the code, you must call the function by typing its name followed by parentheses. When you run a .py script containing the definition and the call above, the interpreter reads the definition, stores it in memory, and then executes the call, resulting in the two print statements displaying on your screen. Passing Arguments to Functions A function …

7. Error Handling and Debugging

The Anatomy of a Crash Imagine you are writing a simple program to calculate the average score of a student. You ask the user for the total points earned and the number of tests taken, then divide the two numbers. If the user enters 85 and 2, everything works perfectly. But what if they enter 0 for the number of tests? Or what if they accidentally type the word "five" instead of the number 5? Instead of calculating an average, the program will abruptly crash, and the interpreter will spit out a block of red text. In Python, a crash like this is called an exception. An exception is simply an event that occurs during the execution of a program that disrupts the normal flow of instructions. When Python encounters a situation it doesn't know how to handle, it "raises" an exception. If your code doesn't explicitly catch and deal with that exception, the program halts completely. As a beginner, seeing a wall of red error text can feel intimidating. However, Python’s errors are actually incredibly helpful. They are not there to scold you; they are detailed messages designed to tell you exactly what went wrong and on which line. Learning to read these messages—and more importantly, learning how to prevent them from crashing your program—is a massive leap forward in your coding journey. Common Python Exceptions Before we can catch errors, we need to know what they look like. Python has dozens of built-in exceptions, but as a beginner, you will encounter a few of them much more frequently than others. Let's look at the most common culprits. ValueError A ValueError occurs when a function receives an argument with the correct type, but an inappropriate value. We saw in Functions and Code Reusability that functions take inputs. If a function expects a number, but you give it text that cannot be converted to a number, Python complains. The int() function expects a string (which is the correct data type), but the value of the string ("twenty") cannot be mathematically converted to an integer. ZeroDivisionError This is one of the most famous errors in programming. It happens when you try to divide a number by zero. Mathematically, dividing by zero is undefined, so Python refuses to guess what the answer should be. TypeError A TypeError happens when you try to perform an operation on two incompatible data types. We discussed data types back in Variables and Core Data Types. Python is strictly typed in the sense that it will not magically convert types for you in the middle of an operation. Python sees a string and an integer (int) and doesn't know whether to add them mathematically or join them …

8. File Handling

Why Files Matter Imagine you are writing a program to track your daily expenses. You enter your morning coffee, lunch, and an afternoon snack. The program calculates your total spending for the day and displays it on your screen. You close your laptop, feeling financially responsible. The next morning, you open your program again. Your total is back to zero. All your data from yesterday has vanished into the ether. So far in your Python journey, every variable, string, and data structure you have created has lived entirely in your computer's short-term memory (RAM). When your program finishes running, or when you close your interpreter or IDE, that memory is wiped clean. To make data survive after a program closes, we must save it to the computer's long-term storage—a hard drive or solid-state drive. We do this by writing to a file. File handling is the bridge between the temporary world of your Python scripts and the permanent world of your computer's storage. By the end of this chapter, you will be able to save your program's output permanently, read data back into your programs, and manage those files safely. Understanding File Paths Before we can open a file, Python needs to know exactly where it is located on your computer. The location of a file is described by its path. A path is simply a string that tells the operating system how to navigate through folders (often called directories) to find the file. There are two main ways to specify a path: 1. Absolute Path: This is the complete, detailed directions to a file, starting from the very root of your hard drive. - On Windows: C:\Users\YourName\Documents\notes.txt - On macOS: /Users/YourName/Documents/notes.txt 2. Relative Path: This gives directions to the file relative to where your Python script files (.py) are currently located. If your script is in the Documents folder, you can simply refer to notes.txt without writing out the whole path. When you are just starting out, the easiest approach is to save your Python script and your text files in the exact same folder. This allows you to use just the file name as the path, keeping things simple. Opening and Closing Files In Python, you cannot directly edit a file sitting on your hard drive. Instead, you must open it, which creates a connection between your program and the file. Python provides a built-in function called open() to do this. Let's look at the most basic way to open a file: When you run this code, Python opens the file and assigns a file object to the variable myfile. A file object is a special type of variable that acts as your remote control for interacting with …

9. Object-Oriented Programming Basics

From Blueprints to Objects Imagine you are managing a small library. You need to keep track of every book. For each book, you need to store its title, author, and whether it is currently checked out. You also need a way for someone to borrow the book and a way for them to return it. If we relied strictly on the tools from Built-in Data Structures, you might try to manage this by creating a dictionary for every single book: But where do you put the functions to check out or return a book? You could write separate functions in your script files, but as your library grows to hundreds of books, mixing scattered dictionaries and loose functions becomes a tangled mess. Object-Oriented Programming (OOP) is a way of writing code that solves this problem by grouping related data (the title, author, and status) and behavior (checking out, returning) together into a single, cohesive unit called an object. Classes and Objects To understand OOP, you need to understand the relationship between a class and an object. A class is a blueprint. It defines what properties and actions a specific type of thing should have, but it doesn't actually contain any real data. Think of a class like the architectural blueprint for a house. The blueprint shows where the walls and doors go, but you can't live inside a blueprint. An object is a concrete instance created from a class. It is the actual house built from the blueprint. You can build many houses from the exact same blueprint, and each house is its own distinct object. They all share the same structure, but the furniture inside (the data) is different for each one. Let's look at our first class definition: Here, we use the class keyword followed by the name of our class. By convention in Python, class names use PascalCase (also known as CapitalizedWords), meaning each word starts with a capital letter with no underscores. The pass keyword simply tells Python, "I haven't written the inside of this yet, but don't throw an error." Even with an empty class, we can create objects from it: We just instantiated two objects. Instantiation is the process of creating a new, unique object from a class. Even though mybook and yourbook are both built from the Book blueprint, they are entirely independent entities in your computer's memory. Modeling State with init An object needs to hold data to be useful. The data stored inside an object represents its state. For a Book, its state includes its title and author. To set up an object's state the moment it is created, Python uses a special method called init. A method is simply a …

10. Modules and the Python Ecosystem

The Box of Batteries Included Imagine you are building a house. You wouldn’t forge your own nails, mill your own lumber, and forge your own hammers from raw iron. You would buy those components from a hardware store and focus your energy on the actual design and construction of the house. Programming works the exact same way. So far in this book, you’ve built a strong foundation: you understand variables, control flow, loops, data structures, functions, and the basics of Object-Oriented Programming (OOP). With these tools, you can logically instruct the computer to do almost anything. But writing all the underlying logic from scratch every time is exhausting and inefficient. Python’s true superpower isn’t just the syntax you’ve learned; it’s the massive ecosystem of pre-written code available for you to use. This code comes in two forms: the Python Standard Library, which comes bundled with every Python installation, and third-party packages, which are created by the global community and available for anyone to download. What is a Module? At its core, a module is simply a file containing Python code. It is a .py script file just like the ones you have been writing. The difference is that a module is designed to be imported and used inside other Python files. Why do we use modules? The primary reason is code reusability. Back in our chapter on functions, we learned how to wrap repetitive logic into a named block so we wouldn't have to copy and paste it. Modules take this concept to the next level. Instead of copying functions or classes from one script to another, you can leave them in a dedicated file and simply import them wherever you need them. Structuring Code Across Multiple Files As your programs grow, keeping all your code in a single file becomes unmanageable. Imagine a 5,000-line script file where you have to scroll endlessly to find the one function you want to update. By splitting your code across multiple files, you create a structured project. For example, if you are building a game, you might separate your code into different .py files: player.py, enemies.py, and main.py. Let’s look at how this works. Create a new file named mathtools.py and add the following code: Now, in the exact same folder, create another file called main.py. To use the code from mathtools.py, we use the import statement: When you run main.py, the Python interpreter reads the import statement, finds the mathtools.py file, and makes its contents available. Notice the dot notation (mathtools.calculatearea). This tells Python, "Look inside the mathtools module and use the calculatearea function." You are already familiar with this concept from Object-Oriented Programming, where we used dots to access methods and …

11. Fetching Data from the Web

The Web as a Giant Conversation Imagine you want to know the current weather in Tokyo, the latest price of Bitcoin, or the top trending news story right now. You could open your web browser, type in a URL, and look at a beautifully designed webpage. But what if you are building a Python program that needs to make decisions based on that constantly changing information? Your Python script cannot "look" at a webpage the way a human does. Instead, it needs to ask a server for raw data and receive it in a format that is easy for a computer to read. This is done through an API (Application Programming Interface). You can think of an API as a waiter in a restaurant. You (the Python program) look at the menu and tell the waiter what you want. The waiter takes your order to the kitchen (the server), and brings back your food (the data) on a clean plate, ready to consume. To make this request, your program uses a set of rules called HTTP (Hypertext Transfer Protocol), which is the foundational language of the web. Every time you load a webpage, watch a video, or fetch data in an app, an HTTP conversation is happening behind the scenes. Understanding HTTP Basics When you use a web browser, you usually interact with HTTP using a GET request. A GET request simply means "Please give me this information." Every HTTP request goes to a specific URL (Uniform Resource Locator), which is essentially a web address. When Python sends a GET request to a URL, the server at the other end processes it and sends back an HTTP Response. Every HTTP response contains two main things: 1. A status code: A three-digit number telling you what happened (e.g., "Success!" or "Not found!"). 2. The payload (or body): The actual data you requested, often formatted as text. In Chapter 10, "Modules and the Python Ecosystem," you learned that Python has a vast library of pre-written code you can import into your scripts. While Python has a built-in module for handling HTTP, it is notoriously clunky and difficult for beginners to use. Instead, the Python community overwhelmingly relies on a third-party module called requests to handle web conversations. Installing and Using the requests Library Because requests is a third-party library, it doesn't come pre-installed with the Python interpreter. You need to download it from the internet and install it into your environment. You do this using a tool called pip, which is Python’s package manager. Open your terminal or command prompt—just like you did when you first checked your Python installation in "Getting Started with Python"—and run this command: Note: On some systems …

12. Final Project Planning and Execution

You have spent eleven chapters learning the individual gears of Python programming. You learned how to store data using Variables and Core Data Types, how to guide your program's logic with Control Flow and Decision Making, and how to automate repetitive tasks using Loops and Repetition. You organized data with Built-in Data Structures, wrapped logic into reusable chunks with Functions and Code Reusability, and modeled the real world using Object-Oriented Programming Basics. You even learned how to handle unexpected crashes (Error Handling and Debugging), save data permanently (File Handling), use external code (Modules and the Python Ecosystem), and pull live data from the internet (Fetching Data from the Web). But knowing how to build individual gears is not the same as building a clock. Imagine being handed a box of car parts—an engine, four tires, a steering wheel, and some bolts. If you try to bolt the steering wheel directly to the engine, you won't get very far. Software development works the same way. Jumping straight into typing code without a plan usually leads to a tangled, broken mess. This final chapter is about assembling your parts into a complete, functional machine. We will walk through the lifecycle of building a real application from scratch, focusing on how to plan, build, test, and document your code just like professional software developers do. Breaking Down a Project When you look at a fully developed app—like a weather app on your phone—it’s easy to feel overwhelmed. How did someone write all that code? The secret is that they didn’t write it as one giant, monolithic block. They broke it down. Decomposition is the process of breaking a large, complex problem into smaller, manageable, and solvable components. Instead of asking, "How do I build a weather app?" you ask, "How do I get the user's location?", "How do I fetch the weather data?", and "How do I display the data?" Defining the Minimum Viable Product (MVP) Before writing a single line of code, you need to define your Minimum Viable Product (MVP). An MVP is the most basic version of your application that still works and provides value to the user. It strips away fancy graphics, extra settings, and complex edge cases. For our practice project, let's build a Command-Line Interface (CLI) application called WeatherCLI. A CLI app runs entirely in your terminal or command prompt—no graphical windows, no buttons, just text input and text output. The MVP for WeatherCLI: 1. Ask the user to type in a city name. 2. Fetch the current weather for that city from the internet. 3. Print the temperature and a brief description of the weather to the screen. 4. Save the search to a local text …

Continue learning