No history yet

Python Basics

The Building Blocks

Python's syntax is designed to be clean and readable. Unlike many other programming languages that use a lot of punctuation, Python uses simple English keywords and indentation. This makes the code look less cluttered and easier to understand at a glance.

At the core of any program are variables. Think of a variable as a labeled box where you can store information. You give the box a name and put something inside it. You can change the contents later if you need to.

# In Python, you create a variable by assigning a value to it.
# The '=' sign is the assignment operator.

transaction_id = 1507
account_balance = 5420.50
client_name = "Alice"
is_flagged = False

The information you store in variables comes in different forms, or data types.

  • Integers are whole numbers, like 1507.
  • Floats are numbers with a decimal point, like 5420.50.
  • Strings are sequences of characters, like text. You create them by wrapping text in quotes, like "Alice".
  • Booleans represent one of two values: True or False. They're useful for tracking states, such as whether an account is flagged.

Controlling the Flow

Programs often need to make decisions. For this, we use conditional statements. An if statement checks if a certain 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 if none of the conditions are met.

transaction_amount = 12000

# Check if a transaction amount is suspicious
if transaction_amount > 10000:
    print("This transaction is large and requires review.")
elif transaction_amount > 5000:
    print("This transaction is moderately large.")
else:
    print("This transaction is within the normal range.")

Sometimes you need to repeat an action multiple times. Loops are perfect for this. A for loop runs a block of code for each item in a sequence, like a list of names. A while loop runs as long as a certain condition remains true.

# Using a for loop to check multiple accounts
accounts_to_check = ["ACC001", "ACC002", "ACC003"]

for account in accounts_to_check:
    print(f"Checking status for {account}...")

# Using a while loop to process transactions
# until a condition is met
transactions_left = 5
while transactions_left > 0:
    print(f"{transactions_left} transactions remaining.")
    transactions_left = transactions_left - 1 # Decrease the count

Packaging Your Code

As your programs grow, you'll find yourself writing the same bits of code over and over. Functions let you package a block of code, give it a name, and run it whenever you want just by calling its name. This keeps your code organized and avoids repetition.

# Define a function to calculate interest
def calculate_simple_interest(principal, rate, time):
    interest = principal * rate * time
    return interest

# Call the function with some values
my_interest = calculate_simple_interest(10000, 0.05, 2) # 💲10,000 at 5% for 2 years
print(f"The calculated interest is: {my_interest}")

Python also has a vast standard library of pre-written code organized into modules. A module is simply a file containing Python definitions and statements. To use a module, you just need to import it into your script. This gives you access to powerful tools without having to write them from scratch.

# Import the 'math' module to use its functions
import math

# Now we can use functions from the math module
number = 81
square_root = math.sqrt(number)

print(f"The square root of {number} is {square_root}.")

Handling Errors

Even with careful planning, code can sometimes fail. A user might enter text where a number is expected, or you might try to divide a number by zero. These events are called exceptions, and if you don't handle them, they will crash your program.

Python provides a clean way to deal with potential errors using a try...except block. You put the risky code in the try block, and the code to run if an error occurs goes in the except block. This way, your program can handle the problem gracefully instead of stopping.

numerator = 100
denominator = 0

try:
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    # This block runs only if a ZeroDivisionError occurs
    print("Error: Cannot divide by zero.")

Now that you've learned the fundamentals, let's test your knowledge.

Quiz Questions 1/6

What is the primary role of indentation in Python?

Quiz Questions 2/6

Which of the following data types would be most suitable for storing the value True?

Understanding these core concepts is the first step toward using Python for more complex tasks. With a solid grasp of variables, control flow, functions, and error handling, you have the foundation you need to start building powerful applications.