No history yet

Python Basics

The Building Blocks

Python is known for its clean and readable syntax. It's designed to look a lot like plain English, which makes it easier to learn than many other programming languages. The rules for writing Python code are straightforward. For example, whitespace, like indentation, is part of the syntax itself. You don't use brackets to group code; you use consistent spacing.

Let's start with the most basic command: printing something to the screen. To do this, you use the print() function.

print("Hello, world!")

Just as important are variables. A variable is like a labeled box where you can store information. You give it a name and assign a value to it using the equals sign (=).

# A variable named 'greeting' holding a piece of text
greeting = "Hello, world!"

# A variable named 'year' holding a number
year = 2024

# You can then use the variable name to access its value
print(greeting)
print(year)

Types of Data

Variables can hold different kinds of information. These are called data types. Python automatically figures out the type of data you're storing. The most common types are text, numbers, and booleans.

Data TypeDescriptionExample
String (str)A sequence of characters, used for text."Hello" or 'Python'
Integer (int)A whole number, without a decimal point.10, -5, 2024
Float (float)A number that has a decimal point.3.14, -0.5, 100.0
Boolean (bool)Represents one of two values: True or False.True or False

Here’s how you'd create variables for each of these types:

# A string
book_title = "A Brief History of Time"

# An integer
publication_year = 1988

# A float
price = 25.99

# A boolean
is_bestseller = True

Making Decisions and Repeating Actions

A program’s real power comes from its ability to make decisions and perform repetitive tasks. Python uses control structures for this.

To make a decision, you use an if statement. It checks if a condition is true and runs a block of code only if it is. You can add elif (else if) for more conditions and else for a default action.

temperature = 75

if temperature > 80:
    print("It's a hot day!")
elif temperature < 60:
    print("It's a bit chilly.")
else:
    print("The weather is pleasant.")

To repeat actions, you use loops. A for loop is great for when you want to go through a sequence of items, like a list.

# This loop will run three times
for fruit in ["apple", "banana", "cherry"]:
    print(f"I am eating a {fruit}.")

A while loop is used to repeat code as long as a certain condition is true.

countdown = 3

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

print("Blast off!")

Reusable Code with Functions

As your programs get bigger, you'll find yourself writing the same code over and over. Functions solve this by letting you bundle a set of instructions into a reusable block. You define a function once and can then "call" it whenever you need it.

Think of a function like a recipe. You write the instructions down once, but you can follow them to bake a cake as many times as you want. Functions can also take inputs, called arguments, just like a recipe might need you to provide eggs or flour.

# Define a function that takes one argument, 'name'
def greet(name):
    message = f"Hello, {name}! Welcome."
    return message

# Call the function with different arguments
greeting_for_alice = greet("Alice")
greeting_for_bob = greet("Bob")

print(greeting_for_alice)
print(greeting_for_bob)

Handling Errors

Things don't always go as planned. Sometimes, code produces an error, or "exception." This can happen if you try to divide a number by zero or access a file that doesn’t exist. An unhandled error will crash your program.

To prevent this, you can anticipate potential problems and handle them gracefully using a try...except block. Python will "try" to run the code in the try block. If an error occurs, it will skip to the except block instead of stopping.

numerator = 10
denominator = 0

try:
    # This line will cause a ZeroDivisionError
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    # This code runs only if the specific error occurs
    print("Error: You can't divide by zero!")

This lets your program continue running even when it encounters a problem.

Now, let's test your understanding of these core concepts.

Quiz Questions 1/6

What is the primary purpose of indentation in Python?

Quiz Questions 2/6

Consider the following code snippet:

item_count = 5
item_name = "widget"
is_in_stock = True

What are the data types of item_count, item_name, and is_in_stock respectively?

These are the fundamental concepts of Python. With a solid grasp of variables, data types, control structures, functions, and error handling, you're ready to build more complex programs.