No history yet

Python Basics

The Rules of the Road

Think of Python's syntax as its grammar. It’s a set of rules that dictate how to write code the computer can understand. Unlike many other languages that use brackets and semicolons to organize code, Python uses something much simpler: indentation. This makes the code clean and easy to read.

In Python, how you space your code matters. Consistent indentation isn't just for style; it's a rule the language enforces.

You also need to know about variables. A variable is just a name you give to a piece of data so you can refer to it later. Assigning a value to a variable is straightforward.

my_age = 30
greeting = "Hello, world!"

# This is a comment. Python ignores it.
# Use comments to explain what your code does.

Different Kinds of Data

Python works with various types of data. You don't have to tell Python what type a variable is; it figures it out on its own. The most common data types are simple and intuitive.

integer

noun

A whole number, without a fractional part.

Integers (int) are for whole numbers, and floats (float) are for numbers with decimal points.

# An integer
subscriber_count = 1000

# A float
price = 19.99

Text is stored as a string (str). You can create strings using single or double quotes.

user_name = 'Alice'
message = "Welcome back!"

Finally, there’s the boolean (bool) type, which can only be True or False. Booleans are essential for making decisions in your code.

is_logged_in = True
has_errors = False

Controlling the Flow

Your code doesn't always run straight from top to bottom. Control structures let you make decisions and repeat actions. The most common way to make a decision is with an if statement. It checks if a condition is true and runs a block of code only if it is.

temperature = 75

if temperature > 70:
    print("It's a warm day!")

You can add elif (else if) to check other conditions or else to run code if none of the conditions are met.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C or lower")

To repeat actions, you use loops. A for loop runs a block of code for each item in a sequence, like a list of numbers or names.

# This loop will print each name on a new line.
students = ["Alice", "Bob", "Charlie"]
for student in students:
    print(student)

A while loop keeps running as long as a certain condition remains true. It's useful when you don't know how many times you need to repeat the action.

count = 1
while count <= 5:
    print(f"Count is {count}")
    count = count + 1 # Increment the count

Reusable Code Blocks

As your programs get bigger, you'll find yourself writing the same lines of code over and over. Functions solve this problem. A function is a named, reusable block of code that performs a specific task. You define it once and can call it whenever you need it.

To define a function, you use the def keyword, give it a name, and specify any inputs (called parameters) it needs. The function can then perform its task and optionally return a result.

# Define a function that adds two numbers
def add_numbers(x, y):
    result = x + y
    return result

# Call the function and store the output
sum_result = add_numbers(5, 3)
print(sum_result) # Output: 8

Functions make your code more organized, easier to read, and simpler to debug.

Handling Errors Gracefully

Even the best programmers make mistakes, and sometimes code fails for reasons outside your control, like bad user input. When Python encounters an error, it stops and raises an exception. If you don't handle the exception, your program will crash.

To prevent this, you can use a try...except block. You put the code that might fail in the try block. If an error occurs, the code in the except block is executed, and the program can continue running.

numerator = 10
denominator = 0

try:
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    print("Error: You can't divide by zero!")

print("The program continued without crashing.")

Error handling is a key part of writing robust, reliable programs. It allows you to anticipate potential problems and manage them without interrupting the user's experience.

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

Quiz Questions 1/6

What is the primary way Python structures its code blocks, such as the body of a loop or an if statement?

Quiz Questions 2/6

After the following code is executed, what will be the data type of the result variable?

result = 10 / 4