Introduction To Python Programming pdf

Introduction To Python Programming pdf

Chapter 1: What is Python and Why Should You Care?

Section 1.1: What is Python?

Alright, let’s start with the basics—what exactly is Python? Well, think of Python as a way to talk to computers. Just like we use words to communicate with each other, Python is a language that lets us give instructions to a computer. The cool part? It’s designed to be super easy for humans to understand.

Imagine you’re telling your friend how to make a sandwich. You’d say something like, “Grab two slices of bread, put some cheese in between, and voilà!” Python works kind of the same way. You write simple instructions, and the computer follows them step by step. For example, if you want the computer to say “Hello,” you just type:

 python

print("Hello")

 And boom—the computer will display “Hello” on the screen. No stress, no complicated rules. That’s why people love Python. It’s clean, straightforward, and doesn’t feel like you’re deciphering a secret code.

Another thing that makes Python special is that it’s used everywhere. Whether it’s building websites, analyzing data, or even creating video games, Python can handle it all. And don’t worry—you don’t need to be a math genius or a tech wizard to get started. If you can read and follow instructions, you’re already halfway there.

So, in short, Python is like a friendly helper that translates your ideas into something the computer can understand. Ready to dive in? Let’s go!

 Section 1.2: Why Learn Python?

Now that you know what Python is, you might be wondering, “Why should I spend my time learning it?” Great question! The truth is, Python is kind of like a Swiss Army knife—it’s super versatile and can help you do all sorts of cool things. Let me break it down for you.

First off, Python is used in so many areas. Ever heard of YouTube or Spotify? Both of those were built using Python. It’s also behind some of the coolest tech out there, like apps that recommend your next favorite song or tools that analyze data to predict trends. Even scientists use Python to study space or track climate change. So, whether you’re into music, gaming, science, or just making life easier, Python has something for you.

But here’s the best part: Python isn’t just for experts. It’s designed to be simple and beginner-friendly, which makes it perfect for someone like you who’s just starting out. Plus, it’s one of the most in-demand skills in the job market right now. That means if you learn Python, you’ll have a powerful tool under your belt—not just for fun projects but also for future opportunities.

And let’s not forget how satisfying it feels to build something yourself. Imagine creating a program that helps you organize your homework, keeps track of your budget, or even plays a game you designed. With Python, all of that is totally possible. So, why learn Python? Because it’s useful, easy to pick up, and opens doors to endless possibilities.

 Section 1.3: Setting Up Python

Okay, so you’re excited to start coding—awesome! But before we dive in, we need to set up your computer so it can understand Python. Don’t worry, it’s not as scary as it sounds. Think of this step as downloading an app on your phone—it’s quick, painless, and you only have to do it once.

Here’s what you need to do:

1.Download Python:

Go to the official Python website (python.org) and look for the download section. There, you’ll find an installer for your computer—whether you’re using Windows, Mac, or Linux. Click the download button, and follow the instructions. It’s like installing any other program.

2.Get a Code Editor:

A code editor is where you’ll write your Python programs. Think of it like a notebook for your ideas. There are lots of options, but two great ones for beginners are:

   Thonny: Super simple and made specifically for learning Python.

   VS Code: A bit more advanced but widely used by professionals (and free!).

Just pick one, download it, and install it. Again, it’s as easy as setting up any other app.

3. Test It Out:

 Once everything’s installed, open your code editor and type this line of code:

  

   print("You’re ready to code!")

  

Then run the program. If you see the message pop up, congrats—you’ve officially set up Python!

If you run into any trouble during setup, don’t panic. Most issues are super common and easy to fix. Just search online for help (e.g., “How to install Python on Windows”) or ask someone who knows a bit about computers. Trust me, once you’re done with this step, you’ll feel unstoppable.

 

 Chapter 2: Getting Started with Python Basics 

Alright, you’ve got Python set up on your computer—awesome job! Now it’s time to start playing around with it and see what it can do. In this chapter, we’ll cover the absolute basics of Python. Don’t worry—we’ll keep things simple and fun. Think of this as learning the alphabet before writing full sentences. By the end of this chapter, you’ll have written your first few lines of code and understood how they work. Let’s jump in!

 

Section 2.1: Writing Your First Program

Let’s start with something super easy: teaching the computer to say “Hello.” This is like the classic “first day of school” icebreaker for coding. Here’s how you do it:

Open your code editor (the one you installed earlier) and type this line:

 

print("Hello, world!")

 

Now run the program. If everything’s set up correctly, you should see the words Hello, world! appear on your screen. Pretty cool, right?

Here’s what’s happening: 

- The word print is like telling the computer, “Hey, show this message to the user.” 

- The stuff inside the parentheses (`"Hello, world!"`) is what you want the computer to display. Those quotation marks tell Python, “This is text, not a command.”

Go ahead and change the message to something else, like "I’m learning Python!" or "Python is awesome!" Then run the program again. See how the output changes? You’re already controlling the computer—it’s listening to you!

Section 2.2: Variables—Storing Information

Now that you’ve made the computer say hello, let’s talk about variables. A variable is just a way to store information so you can use it later. Think of it like labeling a box: you put something inside, give the box a name, and then you can grab it whenever you need it.

Here’s an example:

 

name = "Alex"

age = 17

 

In this case, we’ve created two variables: 

- name holds the value "Alex". 

- age holds the value 17.

You can think of these variables as little containers. Whenever you want to use the value stored in a variable, you just call its name. For example:

 

print("My name is " + name)

print("I am " + str(age) + " years old.")

 

If you run this, it’ll print: 

My name is Alex 

I am 17 years old.

 Notice how we used + to combine text and variables. That’s called concatenation—a fancy word for “sticking things together.” And don’t worry about the str() part for now; it’s just there to make sure Python knows how to handle numbers when mixing them with text.

Want to try something? Change the values of name and age to your own info and run the program again. Cool, right? Variables let you personalize your code and reuse information without typing it over and over.

 

Section 2.3: Data Types

Okay, so we’ve talked about storing information in variables, but what kinds of things can you store? Python has a few basic types of data, and they’re all pretty straightforward.

1.Strings

These are just pieces of text. Anything inside quotes (`"like this"`) is a string. 

   Example:

 

   greeting = "Hi there!"

  

2. Integers:

Whole numbers, like 5, 10, or -3. No decimals here. 

   Example:

 

   score = 100

  

3. Floats:

Numbers with decimals, like 3.14 or 98.6. 

   Example:

 temperature = 98.6

4. Booleans:

These are just yes/no answers, written as True or False. 

   Example:

  

   is_student = True

  

Why does this matter? Well, different types of data behave differently. For instance, you can add two numbers together, but you can’t add a number to a piece of text without converting it first. Here’s an example:

 

age = 17

message = "I am " + str(age) + " years old."

print(message)

 

The str(age) part converts the number 17 into text so Python can combine it with the rest of the sentence. It’s like translating between languages!

 

Mini-Project: Create a Personalized Greeting**

Now that you know about variables and data types, let’s put it all together with a mini-project. Write a program that asks for someone’s name and age, then prints out a personalized message.

Here’s how you can do it:

 

name = input("What’s your name? ")

age = input("How old are you? ")

print("Nice to meet you, " + name + "! You’re " + age + " years old.")

 

When you run this, the program will ask you for your name and age, then print out a friendly message. Try running it and see how it works!

 

Congrats—you’ve made it through the basics! You’ve learned how to write your first program, store information in variables, and understand different types of data. These are the building blocks of Python, and everything else you learn will build on top of them.

Take a moment to play around with what you’ve learned. Change the messages, experiment with different variables, and see what happens. Coding is all about trial and error, so don’t be afraid to mess around. You’ve got this! 

 

Chapter 3: Making Decisions with If Statements

Alright, so far you’ve learned how to make the computer say stuff, store information in variables, and understand different types of data. But here’s the thing—real-life problems often involve making choices. For example, “If it’s raining, I’ll take an umbrella; otherwise, I’ll leave it at home.” Computers can do the same thing using something called if statements 

In this chapter, we’ll learn how to tell Python to make decisions based on conditions. By the end of this chapter, you’ll be able to write programs that react differently depending on what’s happening. Let’s get started!

 

Section 3.1: Conditional Logic

Imagine you’re writing a program that checks if someone is old enough to vote. You’d want the program to say one thing if they’re 18 or older and something else if they’re younger. That’s where if statements

come in—they let you tell the computer, “Do this if something is true; otherwise, do something else.”

Here’s a simple example:

 

age = int(input("How old are you? "))

if age >= 18:

    print("You can vote!")

else:

    print("You’ll be able to vote soon.")

`

Let’s break it down: 

- The if part checks whether the condition (`age >= 18`) is true. 

- If it is, the program prints, “You can vote!” 

- If it’s not, the else part kicks in, and the program says, “You’ll be able to vote soon.”

Notice how the program behaves differently depending on the input. That’s the power of if statements—they let your code adapt to different situations.

 

Section 3.2: Multiple Choices with elif

Sometimes, you’ll need more than just two options. For example, imagine a program that tells you how much you should study based on your grade: 

- If your grade is A, it says, “Great job! Keep it up.” 

- If it’s B, it says, “Not bad, but you can improve.” 

- If it’s C or lower, it says, “You might want to study harder.”

Here’s how you can write that:

 

grade = input("What’s your grade? (A, B, C, etc.) ")

if grade == "A":

    print("Great job! Keep it up.")

elif grade == "B":

    print("Not bad, but you can improve.")

else:

    print("You might want to study harder.")

 

What’s going on here? 

- The elif (short for “else if”) lets you add extra conditions. 

- The program checks each condition in order and stops as soon as it finds one that’s true. 

- If none of the conditions are true, it falls back to the else part.

This is super useful when you have more than two possible outcomes. Think of it like a flowchart—the program follows the path that matches the input.

 

Section 3.3: Hands-On Practice

Now it’s your turn to try it out! Let’s build a simple decision-making program together. Here’s an idea: write a program that checks if a number is positive, negative, or zero. 

Here’s how you can do it:

 

 

number = int(input("Enter a number: "))

if number > 0:

    print("The number is positive.")

elif number < 0:

    print("The number is negative.")

else:

    print("The number is zero.")

 

When you run this, the program will ask you for a number and then tell you whether it’s positive, negative, or zero. Try running it with different numbers to see how it works.

Want to make it more fun? You can tweak the program to do something else—like checking if a number is even or odd. Here’s an example:

 

number = int(input("Enter a number: "))

if number % 2 == 0:

    print("The number is even.")

else:

    print("The number is odd.")

 

The % symbol is called the modulus operator—it gives you the remainder after dividing. If the remainder is 0, the number is even; otherwise, it’s odd. Pretty neat, right?

 

Mini-Project : Build a Simple Quiz Game

Now that you know how to use if, elif, and else, let’s put it all together with a mini-project. We’ll create a simple quiz game with multiple-choice questions. Here’s an example:

 

print("Welcome to the Quiz Game!")

print("Question 1: What is the capital of France?")

print("A) London")

print("B) Paris")

print("C) Berlin")

answer = input("Your answer (A, B, or C): ")

if answer == "B":

    print("Correct! Paris is the capital of France.")

else:

    print("Oops! The correct answer is B) Paris.")

 

Run this program and see how it works. Then, try adding more questions! You can make it as long or as short as you want. It’s a great way to practice decision-making in Python.

Nice work—you’ve learned how to make Python make decisions! With if, elif, and else, you can write programs that adapt to different inputs and conditions. Whether you’re building a quiz game, checking grades, or deciding what to wear based on the weather, you now have the tools to handle it.

Take some time to experiment with what you’ve learned. Try tweaking the examples, adding new conditions, or coming up with your own projects. The more you practice, the better you’ll get. 

Ready for the next step? In Chapter 4, we’ll learn how to repeat tasks efficiently using loops.

Chapter 4: Loops—Repeating Tasks Efficiently

Alright, so far you’ve learned how to make Python say things, store information, and make decisions. But what if you need to do the same thing over and over again? For example, imagine counting from 1 to 100 by hand—it’s boring and takes forever. Luckily, Python has something called loops that let you repeat tasks without rewriting the same code a hundred times. 

In this chapter, we’ll explore two types of loops: for loops and while loops. By the end, you’ll be able to automate repetitive tasks and save yourself a ton of time. Let’s dive in!

 

Section 4.1: For Loops

A for loop is like telling Python, “Do this for every item in a list.” For example, if you want to print numbers from 1 to 5, you don’t have to type print(1), print(2), and so on. Instead, you can use a for loop:

 

for i in range(1, 6):

    print(i)

 

Here’s what’s happening: 

- range(1, 6) creates a sequence of numbers starting at 1 and ending just before 6 (so it includes 1, 2, 3, 4, and 5). 

- The for loop goes through each number in the sequence, one at a time, and prints it. 

You can also use for loops with lists. For example, if you have a list of your favorite foods, you can print them all like this:

 

 

foods = ["Pizza", "Burgers", "Pasta"]

for food in foods:

    print("I love " + food + "!")

 

When you run this, it’ll say: 

I love Pizza!

I love Burgers!

I love Pasta!

 

So, whenever you need to repeat something for a specific number of times or go through a list, think of a for loop. It’s like having a robot helper that does the boring stuff for you.

 

Section 4.2: While Loops

Sometimes, you don’t know exactly how many times you need to repeat something—you just want to keep going until a condition is met. That’s where while loops come in. 

For example, imagine writing a program that keeps asking for input until the user types “quit”:

 

command = ""

while command != "quit":

    command = input("Type 'quit' to exit: ")

    print("You typed: " + command)

 

Here’s how it works: 

- The while loop runs as long as the condition (`command != "quit"`) is true. 

- Inside the loop, the program asks for input and checks if it’s “quit.” If it’s not, it prints what you typed and asks again. 

Be careful with while loops, though—if the condition never becomes false, the loop will run forever! This is called an infinite loop, and it can freeze your program. To avoid this, always double-check your conditions.

 

Mini-Project: Build a Guessing Game

Now that you know about loops, let’s put them to work with a fun project: a guessing game! Here’s how you can do it:

 

import random

number_to_guess = random.randint(1, 10)

guess = int(input("Guess a number between 1 and 10: "))

while guess != number_to_guess:

    print("Wrong! Try again.")

    guess = int(input("Guess a number between 1 and 10: "))

print("Congratulations! You guessed the correct number.")

`

This program picks a random number between 1 and 10 and keeps asking you to guess until you get it right. Try running it and see how it feels!

 

 

 

Chapter 5: Functions—Reusable Code Blocks

So far, your programs have been pretty straightforward. But as you start building bigger projects, you might notice that you’re repeating the same chunks of code over and over again. That’s where functions come in—they let you group code into reusable blocks. 

Think of functions as mini-programs inside your main program. Once you write a function, you can call it whenever you need it, saving you time and effort. In this chapter, we’ll learn how to create and use functions. Let’s go!

 

Section 5.1: What Are Functions?

A function is like a recipe—it’s a set of instructions that you can follow whenever you need to do something specific. For example, if you often calculate the area of a rectangle, you can write a function to do it for you:

 

def calculate_area(length, width):

    return length * width

area = calculate_area(5, 3)

print("The area is: " + str(area))

 

Here’s how it works: 

- The def keyword tells Python you’re defining a function. 

- calculate_area is the name of the function, and length and width are inputs (called parameters). 

- Inside the function, you multiply the inputs and use return to send the result back.  Once you’ve written the function, you can call it with different values whenever you need it. No more rewriting the same calculation over and over!

Section 5.2: Creating and Using Functions

Let’s try another example. Imagine you want to write a program that greets users by name. Instead of typing the greeting code every time, you can create a function:

 

def greet(name):

    print("Hello, " + name + "! Welcome to the program.")

greet("Alex")

greet("Sam")

 

When you run this, it’ll print: 

 

Hello, Alex! Welcome to the program.

Hello, Sam! Welcome to the program.

 

Notice how clean and organized the code looks? Functions help you keep your programs tidy and easy to read.

 

Mini-Project: Build a Simple Calculator

Now that you know how to write functions, let’s build a simple calculator. Here’s an example:

 

 

 

 

 

def add(x, y):

    return x + y

 

def subtract(x, y):

    return x - y

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

print("Addition result: " + str(add(num1, num2)))

print("Subtraction result: " + str(subtract(num1, num2)))

 

This program defines two functions (`add` and subtract) and uses them to perform calculations. Try running it and see how it works!

 

Chapter 6: Lists and Dictionaries—Organizing Data 

By now, you’ve worked with variables to store single pieces of data like numbers or text. But what if you need to store multiple items, like a list of groceries or a collection of student grades? That’s where lists and dictionaries come in—they let you organize and manage groups of data efficiently. In this chapter, we’ll explore how to use lists and dictionaries to keep your data neat and accessible. Let’s get started!

 

Section 6.1: Lists

A list is like a shopping list—it’s a collection of items stored in order. You can add, remove, or change items as needed. Here’s an example:

 

fruits = ["Apple", "Banana", "Cherry"]

print(fruits[0])  # Output: Apple

print(fruits[1])  # Output: Banana

 

Lists are indexed, which means each item has a position number starting at 0. So, fruits[0] gives you the first item, fruits[1] gives you the second, and so on.

You can also modify lists. For example:

 

fruits.append("Orange")  # Adds "Orange" to the end

fruits.remove("Banana")  # Removes "Banana"

print(fruits)  # Output: ['Apple', 'Cherry', 'Orange']

 

Lists are great for keeping track of things like scores, names, or tasks.

 

Section 6.2: Dictionaries

A dictionary is like a phone book—it stores pairs of keys and values. For example, you might use a dictionary to store student grades:

 

grades = {"Alice": 90, "Bob": 85, "Charlie": 95}

print(grades["Alice"])  # Output: 90

 

Here’s how it works: 

- "Alice" is the key, and 90 is the value. 

- You can access a value by using its key, like looking up someone’s grade.

 

You can also add or update entries:

grades["David"] = 88  # Adds David with a grade of 88

grades["Alice"] = 92  # Updates Alice’s grade to 92

print(grades)

 

Dictionaries are perfect for storing related data, like user profiles or inventory items.

 

Mini-Project: Manage a Shopping List

Now that you know about lists and dictionaries, let’s combine them into a mini-project: a shopping list manager. Here’s an example:

 

shopping_list = []

while True:

    item = input("Add an item to your shopping list (or type 'done' to finish): ")

    if item == "done":

        break

    shopping_list.append(item)

print("Your shopping list:")

for item in shopping_list:

    print("- " + item)

This program lets you add items to a list until you type “done,” then prints your final shopping list. Try running it and see how useful lists can be! Great job! You’ve learned how to use loops to repeat tasks, functions to organize your code, and lists/dictionaries to manage data. These tools are essential for writing efficient, clean, and powerful programs. Take some time to experiment with the examples and come up with your own projects.  Ready for the next step? In Chapter 7, we’ll learn how to handle errors and troubleshoot your code. Stay tuned!

 Chapter 7: Error Handling—Dealing with Mistakes 

Let’s face it: everyone makes mistakes, especially when coding. Whether it’s a typo, a missing parenthesis, or forgetting to define a variable, errors are just part of the process. The good news? Python gives you tools to handle these mistakes gracefully instead of letting your program crash. In this chapter, we’ll learn how to deal with errors using error handling techniques. By the end, you’ll be able to write programs that don’t break easily—even when things go wrong.

 

Section 7.1: Common Errors

Before we dive into fixing errors, let’s talk about the kinds of mistakes you’re likely to make as a beginner. Here are three common ones:

1. Syntax Errors:

These happen when you write something Python doesn’t understand. For example:

  

   print("Hello"  # Missing closing parenthesis

  

Python will complain and tell you there’s a problem. Syntax errors are usually easy to spot because they stop your program from running.

2. Name Errors:

These occur when you use a variable or function that doesn’t exist. For example:

 

   print(name)  # "name" hasn't been defined yet

  

   Python will say something like, “Hey, I don’t know what ‘name’ is!”

3.Type Errors:

These happen when you try to do something impossible, like adding a number to a string:

 

   age = 17

   print("I am " + age + " years old.")  # Oops! You can’t add a number to text

  

Don’t worry—these errors are normal, and even experienced programmers run into them all the time. The key is learning how to fix them quickly.

 

Section 7.2: Try and Except

Python has a special way to handle errors so your program doesn’t crash: the try and except block. It’s like telling Python, “Try this code, but if something goes wrong, do this instead.”

Here’s an example:

 

try:

    num = int(input("Enter a number: "))

    result = 10 / num

    print("The result is:", result)

except ZeroDivisionError:

    print("Oops! You can’t divide by zero.")

 

What’s happening here? 

- The try block contains the code that might cause an error (like dividing by zero). 

- If an error occurs, Python jumps to the except block and runs the backup code instead. 

This way, your program won’t crash—it’ll just tell the user what went wrong.

You can also handle multiple types of errors. For example:

 

try:

    num = int(input("Enter a number: "))

    result = 10 / num

    print("The result is:", result)

except ZeroDivisionError:

    print("You can’t divide by zero!")

except ValueError:

    print("That’s not a valid number!")

 

Now your program can handle both division-by-zero errors and invalid inputs. Pretty cool, right?

 

Mini-Project: Build a Safe Calculator**

Let’s put error handling into practice by building a calculator that doesn’t crash, even if the user enters bad input:

 

 

 

 

 

while True:

    try:

        num1 = float(input("Enter the first number: "))

        num2 = float(input("Enter the second number: "))

        result = num1 / num2

        print("The result is:", result)

        break

    except ZeroDivisionError:

        print("You can’t divide by zero. Try again.")

    except ValueError:

        print("Please enter valid numbers. Try again.")

 

This program keeps asking for input until the user enters valid numbers and avoids dividing by zero. Try running it and see how smooth it feels!

 

 

Chapter 8: Building a Real Project

Congratulations—you’ve learned the basics of Python! Now it’s time to put everything together and build something real. In this chapter, we’ll walk through creating a simple project step by step. By the end, you’ll have a fully functional program that you can show off to friends or use for yourself. Let’s get started!

 

Section 8.1: Planning Your Project

Before you start coding, it’s important to plan what you want to build. Think about something useful or fun. Here are a few ideas: 

- A quiz game with multiple questions and a score tracker. 

- A budget tracker that lets you add expenses and calculate totals. 

- A random password generator that creates strong passwords for you. 

For this example, let’s build a quiz game. The program will ask a series of questions, keep track of the score, and display the final result at the end.

 

Section 8.2: Writing the Code

Here’s how you can create the quiz game:

 score = 0

print("Welcome to the Quiz Game!")

print("Answer the following questions. Each correct answer earns you 1 point.")

# Question 1

answer1 = input("What is the capital of France? ")

if answer1.lower() == "paris":

    print("Correct!")

    score += 1

else:

    print("Wrong! The correct answer is Paris.")

# Question 2

answer2 = input("What is 5 + 7? ")

if answer2 == "12":

    print("Correct!")

    score += 1

else:

    print("Wrong! The correct answer is 12.")

 

# Final Score

print("Quiz complete! Your score is:", score, "out of 2.")

 

How does it work? 

- The program starts by setting the score to 0. 

- It asks two questions and checks the answers using if statements. 

- If the answer is correct, it adds 1 to the score. 

- At the end, it displays the total score.

You can expand this program by adding more questions, categories, or even a leaderboard!

 

Section 8.3: Testing and Debugging

Once you’ve written your program, test it thoroughly. Run it multiple times with different inputs to make sure it works as expected. If you find any bugs (mistakes in the code), don’t panic—debugging is part of the process. Use print statements or error messages to figure out what’s going wrong, then fix it.

For example, if the user types “PARIS” instead of “Paris,” the program might mark it as wrong. To fix this, you can convert the input to lowercase using .lower() (as shown in the example above).

 

Conclusion: Keep Learning and Exploring 

Wow—you’ve come a long way! From writing your first line of code to building a full project, you’ve learned the essentials of Python programming. But guess what? This is just the beginning. Python is a vast language with endless possibilities, and there’s always more to explore.

Here’s what you can do next: 

- Dive Deeper:

Learn about libraries like matplotlib for data visualization or pygame for game development. 

- Build More Projects:

Create apps, automate tasks, or analyze data. The more you build, the better you’ll get. 

- Join Communities:

 Connect with other coders online or in person. Sharing ideas and solving problems together is a great way to grow. 

Remember, coding isn’t about being perfect—it’s about experimenting, making mistakes, and learning along the way. Every expert programmer started exactly where you are now. So keep practicing, stay curious, and most importantly, have fun!

You’ve got this. Go out there and build something amazing! 

 

 

 

 

 

 

 

 

 

 

To view or add a comment, sign in

More articles by Harron Wanga

  • List Indexing in Python

    As a data scientist and a python developer, I have frequently used list indexing to access and modify elements within…

    2 Comments

Insights from the community

Others also viewed

Explore topics