No history yet

Python Basics

Giving the Computer Instructions

Programming is how we give instructions to a computer. Think of it like a recipe. Each step must be clear and in the right order for the final dish to turn out correctly. Python is a popular programming language because its instructions look a lot like plain English, which makes it easier to read and write.

Let's start with the most basic building block: storing information. To do anything useful, our program needs to remember things, like a username, the score in a game, or the price of an item.

Variables and Data Types

We store information in variables. A variable is like a labeled box where you can keep a piece of information. You give the box a name, and you can look at what's inside or change it later. The name you choose for your variable should be descriptive, like user_name or final_score.

The information itself comes in different forms, or data types.

  • Integers (int): Whole numbers, like 10, -5, or 1,200.
  • Floats (float): Numbers with a decimal point, like 3.14 or -0.5.
  • Strings (str): Plain text, which we wrap in single or double quotes. For example, 'hello' or "Python".
  • Booleans (bool): Represents one of two values: True or False. These are crucial for making decisions.
# Let's create some variables

# An integer
player_score = 150

# A float
item_price = 24.95

# A string
player_name = "Ryu"

# A boolean
is_game_over = False

By assigning a value to a name with the equals sign (=), we create a variable. Python automatically figures out the data type based on the value you give it.

Making Things Happen

Variables are great for storing data, but the real power comes from performing operations on them. We do this with operators.

First up are arithmetic operators. These are the familiar symbols from math class for addition (+), subtraction (-), multiplication (*), and division (/).

coconuts_in_bunch = 6
bunches = 4
total_coconuts = coconuts_in_bunch * bunches # Result is 24

money = 100
lunch_cost = 12.50
money_left = money - lunch_cost # Result is 87.5

Next are comparison operators, which we use to compare two values. The result of a comparison is always a boolean: True or False.

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to

Notice that checking for equality uses a double equals sign (==). A single equals sign (=) is for assigning a value to a variable.

We also have logical operators (and, or, not) for combining boolean values. For example, you might check if a player has a key and is at the door.

Controlling the Flow

Programs rarely run straight from top to bottom. Often, they need to make decisions or repeat actions. This is called control flow.

The most common way to make a decision is with an if statement. An if statement runs a block of code only if a certain condition is true.

age = 18

if age >= 18:
    print("You are old enough to vote.")
else:
    print("You are not old enough to vote.")

The indented code under if only runs when age >= 18 is True. The code under else runs if the condition is False. This indentation is very important in Python; it’s how the language groups lines of code together.

When you need to repeat an action, you use a loop. A for loop is great for repeating a task a specific number of times.

# This loop will run 5 times (for 0, 1, 2, 3, 4)
for i in range(5):
    print("Hello!")

A while loop is used to repeat an action as long as a condition remains true. It's useful when you don't know ahead of time how many times you need to loop.

countdown = 3

while countdown > 0:
    print(countdown)
    countdown = countdown - 1 # Decrease the count by 1

print("Liftoff!")

Input and Output

A program isn't very useful if it can't communicate with the user. We've already seen the print() function, which is the standard way to display output to the screen.

To get input from a user, we use the input() function. It shows the user a message, waits for them to type something and press Enter, and then returns the text they entered.

user_name = input("What is your name? ")
print("Hello, " + user_name + "!")

Important: The input() function always returns a string. If you need to treat the input as a number, you have to convert it using int() or float().

age_text = input("How old are you? ")
age_number = int(age_text)

if age_number < 13:
    print("You're a kid!")
else:
    print("You're a teenager or older.")

Handling Errors

What happens if a user types "ten" instead of "10" in the example above? The int() function won't know how to convert that into a number, and the program will crash with an error. This is a common problem.

Good programs are prepared for unexpected input. We can handle potential errors gracefully using a try...except block. This tells Python to try running some code, but if a specific error occurs, to run a different block of code instead of crashing.

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

try:
    # Try to convert the input to an integer
    age_number = int(age_text)
    print(f"Next year you will be {age_number + 1}.")
except ValueError:
    # This code runs only if the conversion fails
    print("That doesn't look like a number. Please enter a number.")

Now, instead of crashing, our program gives the user a helpful message. Learning to anticipate and handle errors is a key step in writing robust, user-friendly programs.

Quiz Questions 1/6

What is the primary purpose of a variable in programming?

Quiz Questions 2/6

In Python, what is the data type of the value "10"?

These are the fundamental building blocks of Python. With variables, operators, and control structures, you can write simple but powerful scripts.