Python for Business Development Automation
Python Basics
The Building Blocks of Code
Think of a variable as a labeled box where you can store information. You give it a name, and inside, you place a piece of data. This makes it easy to refer to that data later in your program. In business development, you might create variables to store a client's name, a deal's value, or the number of new leads.
Variable
noun
A symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name.
Creating a variable in Python is simple. You just pick a name and use the equals sign (=) to assign it a value.
client_name = "Innovate Corp"
quarterly_revenue = 500000
The kind of information you store determines its data type. Python has several built-in types, but let's focus on the most common ones.
- Strings are used for text. You create them by wrapping text in single or double quotes.
- Integers are whole numbers, like 10, -5, or 1500.
- Floats are numbers with a decimal point, like 3.14 or 99.99.
- Booleans represent truth values. They can only be
TrueorFalse.
# A string for a company name
company = "Tech Solutions Inc."
# An integer for the number of employees
num_employees = 250
# A float for the stock price
stock_price = 145.75
# A boolean to track if a contract is signed
is_signed = True
Python automatically figures out the data type when you create a variable, which makes it very flexible to work with.
Making Decisions and Repeating Actions
Programs rarely run in a straight line. They need to make decisions and perform repetitive tasks. This is where control structures come in. They control the flow of your code.
The most common way to make a decision is with an if statement. It checks if a condition is True. If it is, a specific block of code runs. You can add an else to run code if the condition is False, and elif (short for "else if") to check multiple conditions.
Imagine checking if a salesperson met their quarterly goal. If they did, they get a bonus; otherwise, they don't.
sales_target = 100000
actual_sales = 125000
if actual_sales >= sales_target:
print("Congratulations! You've earned a bonus.")
else:
print("Keep pushing to meet the next target.")
For repetitive tasks, we use loops. A for loop is great for iterating over a sequence, like a list of items.
# A list of potential clients
leads = ["Acme Co", "Beta LLC", "Gamma Inc"]
# Loop through the list and print a follow-up reminder for each
for lead in leads:
print(f"Send follow-up email to {lead}")
A while loop runs as long as a certain condition is true. This is useful when you don't know exactly how many times you need to repeat something.
tasks_in_queue = 5
while tasks_in_queue > 0:
print(f"Processing a task. {tasks_in_queue - 1} remaining.")
tasks_in_queue = tasks_in_queue - 1 # Decrease the count
print("All tasks are complete.")
Creating Reusable Code
As you write more code, you'll find yourself repeating the same steps. Instead of copying and pasting, you can package that code into a function. A function is a named, reusable block of code that performs a specific action. You define it once and can call it whenever you need it.
Function
noun
A block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
You define a function using the def keyword, followed by a name, parentheses, and a colon. Inside the parentheses, you can specify parameters, which are variables that hold the input values the function needs. The function can also send a value back using the return keyword.
Let's create a function to calculate the final price after applying a discount. It will take the original price and the discount percentage as inputs and return the new price.
# Define the function
def calculate_discounted_price(price, discount_percent):
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price
# Use the function to calculate the price for two different items
item1_price = calculate_discounted_price(200, 10) # 10% off π²200
item2_price = calculate_discounted_price(1500, 25) # 25% off π²1500
print(f"Item 1 final price: π²{item1_price}")
print(f"Item 2 final price: π²{item2_price}")
Handling the Unexpected
Sometimes, code doesn't work as planned. Users might enter text where a number is expected, or a file you're trying to read might not exist. These situations cause errors, or exceptions, which can crash your program.
To prevent this, you can use error handling. In Python, this is done with a try...except block. You put the code that might cause an error inside the try block. If an error occurs, the code inside the except block is executed, and the program continues running instead of stopping.
Imagine asking a user for their age, but they type "thirty" instead of 30. Trying to use this text in a calculation would cause an error.
user_input = "thirty"
try:
# This line will cause a ValueError because "thirty" isn't a number
age = int(user_input)
print(f"Next year you will be {age + 1}.")
except ValueError:
# This code runs because the error occurred
print("Invalid input. Please enter a number.")
By anticipating potential problems with try...except, you can build more robust and user-friendly programs that don't break easily.
Ready to check your understanding? Let's tackle a few questions on these core concepts.
After running the code client_name = "Global Tech", what is the data type of the client_name variable?
What is the primary purpose of a function in programming?
These are the fundamentals of Python. With variables, control structures, functions, and error handling, you have the essential tools to start writing scripts that can automate tasks and analyze data.