No history yet

Python Basics

The Rules of the Road

Python is famous for being easy to read. One of the main reasons for this is its strict use of indentation. While other programming languages might use curly braces {} or keywords to group code, Python uses whitespace. How you indent your code isn't just for style, it's a rule that Python enforces.

This means that lines of code that are part of the same block must be indented by the same amount. This simple rule makes Python code incredibly clean and consistent, no matter who writes it.

# This is a comment. Python ignores lines starting with #.

# This code block is part of the 'if' statement because it's indented.
if 5 > 2:
  print("Five is greater than two!")

# An error would occur if the line above was not indented.
# if 5 > 2:
# print("This line has the wrong indentation.")

Python's Building Blocks

Every piece of information your program works with has a type. Think of them as different categories of data. Let's look at the most common ones.

Strings are used for text. You can create them by enclosing characters in either single quotes ' or double quotes ".

greeting = "Hello, world!"
name = 'Alice'

print(greeting)
print(name)

Numbers in Python are straightforward. You have integers (whole numbers like 10 or -3) and floating-point numbers (numbers with a decimal, like 3.14).

age = 30           # An integer
pi = 3.14159     # A float

# You can perform math operations
sum = age + 5
print(sum)

Booleans are simple but powerful. They can only have one of two values: True or False. They are essential for making decisions in your code.

is_learning = True
is_bored = False

print(is_learning)

Making Decisions and Repeating Actions

Programs rarely run straight from top to bottom. They need to make decisions and perform repetitive tasks. This is where control structures come in.

The if statement lets you run code only if a certain condition is true. You can also provide an else block to run if the condition is false.

temperature = 75

if temperature > 80:
  print("It's a hot day!")
else:
  print("It's not too hot.")

When you need to do something over and over, you use a loop. The for loop iterates over a sequence of items, like a list of numbers or characters in a string.

# This loop will run 5 times, for numbers 0 through 4
for i in range(5):
  print("Loop number:", i)

# You can also loop through the letters in a string
for letter in "Python":
    print(letter)

The while loop runs as long as its condition is true. Be careful with these, as you can accidentally create an infinite loop if the condition never becomes false.

count = 0
while count < 3:
  print("Count is", count)
  count = count + 1  # This line prevents an infinite loop!

Packaging Your Code

As your programs get bigger, you'll want to organize your code to keep it tidy and reusable. Functions and modules are the tools for the job.

A function is a named block of code that performs a specific task. You define it once and can then "call" it whenever you need it. This helps avoid repeating yourself. Functions can take inputs, called arguments, to make them more flexible.

# Define a function that takes one argument, 'name'
def greet(name):
  print("Hello, " + name + "!")

# Call the function with different arguments
greet("Bob")
greet("Charlie")

A module is simply a Python file containing functions and variables that you can use in other programs. Python has a rich standard library with many built-in modules for tasks like math, working with dates, or generating random numbers. You use the import keyword to access them.

# Import the 'math' module to get access to advanced math functions
import math

# Now we can use the sqrt function from the math module
root = math.sqrt(64)
print(root)

Handling the Unexpected

Sometimes, things go wrong. A user might enter text where a number is expected, or a file you're trying to read might not exist. If you don't plan for these errors, your program will crash.

Python provides try and except blocks to handle these situations gracefully. You put the code that might cause an error in the try block. If an error occurs, the code in the except block is executed, and the program can continue running instead of crashing.

try:
  # This code will cause a ZeroDivisionError
  result = 10 / 0
  print(result)
except ZeroDivisionError:
  # This block runs because the specific error occurred
  print("Oops! You can't divide by zero.")

print("The program didn't crash!")

Now let's review some of the key terms we've covered.

Ready to test your knowledge?

Quiz Questions 1/6

How does Python use indentation to structure code?

Quiz Questions 2/6

Which of the following values is a Boolean data type?

These are the fundamental building blocks of Python. Mastering them will give you a solid base for tackling more complex programming challenges.