No history yet

Python Basics

The Building Blocks of Python

Think of Python's syntax as its grammar. These are the rules you follow to write instructions the computer can understand. The most basic concept is a variable, which is just a name you give to a piece of data so you can refer to it later. It’s like labeling a box to remember what's inside.

For example, you could create a variable to store a client's name or the value of a stock. You assign a value to a variable using the equals sign (=).

# Assigning a string (text) to a variable
client_name = "Alex Chen"

# Assigning a number to a variable
portfolio_value = 500000

# You can print the value to see it
print(client_name)
print(portfolio_value)

Handling Different Data

Python needs to know what kind of data it's working with. Is it a whole number, a decimal, or text? These categories are called data types. The most common ones you'll use are integers for whole numbers, floats for numbers with decimals, strings for text, and booleans for true or false values.

Data TypeDescriptionExample
Integer (int)Whole numbers100
Float (float)Numbers with a decimal point125.50
String (str)Text, enclosed in quotes"Apple Inc."
Boolean (bool)Represents True or FalseTrue

Knowing the data type is crucial because it determines what you can do with the data. You can perform math on integers and floats, but not on strings. You can find out a variable's type using the type() function.

interest_rate = 0.05       # This is a float
account_is_active = True   # This is a boolean

print(type(interest_rate))
print(type(account_is_active))

Making Decisions and Repeating Actions

Your programs will often need to make decisions. This is where control structures come in. The most common is the if-else statement. It checks if a condition is true and runs a block of code if it is. If not, it can run a different block of code.

client_age = 67

if client_age >= 65:
    print("Client is eligible for retirement benefits.")
else:
    print("Client is not yet eligible for retirement.")

Sometimes you need to repeat an action. Instead of writing the same code over and over, you can use a loop. A for loop runs a block of code for each item in a list.

# A list of stock tickers
stocks = ["AAPL", "GOOG", "MSFT"]

for stock in stocks:
    print("Analyzing stock:", stock)

Creating Reusable Code

As you write more code, you'll find yourself performing the same calculations repeatedly, like finding the future value of an investment. Instead of rewriting the logic each time, you can package it into a function. A function is a named, reusable block of code that performs a specific task.

You define a function using the def keyword, give it a name, and specify any inputs (called arguments) it needs. The function can then return a result.

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

# Use the function
initial_investment = 10000
annual_rate = 0.05
years = 10

earned_interest = calculate_simple_interest(initial_investment, annual_rate, years)

print(f"Interest earned: 💲{earned_interest}")

Functions make your code organized, easier to read, and less prone to errors. If you need to update the calculation, you only have to change it in one place.

Handling Errors

No matter how careful you are, errors will happen. A user might enter text where a number is expected, or you might try to divide a number by zero. If you don't plan for these situations, your program will crash.

Python provides a way to handle potential errors gracefully using a try...except block. 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 continues running.

numerator = 100
denominator = 0

try:
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

print("Program continues after the error.")

Error handling makes your programs more robust and user-friendly. It allows you to anticipate problems and provide helpful feedback instead of just crashing.

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

Quiz Questions 1/6

What is the primary purpose of a variable in Python?

Quiz Questions 2/6

What would be the output of the following Python code?

print(type(15.0))

These are the essential building blocks of Python. By mastering variables, data types, control structures, functions, and error handling, you have a solid foundation for building powerful tools for financial analysis.