Python for Automation
Python Basics
Storing Information
To get anything done in Python, you need to work with information, or data. The most basic way to manage data is by using variables. Think of a variable as a labeled box where you can store something. You give the box a name, and you can put data inside it. Later, you can refer to the box by its name to see what's inside or to change its contents.
Python works with several basic types of data. The most common ones are:
Integers: Whole numbers, like 10, -5, or 1,200. Floats: Numbers with a decimal point, like 3.14 or -0.5. Strings: Plain text, wrapped in single or double quotes, like 'hello' or "Python". Booleans: Represent truth values, and can only be
TrueorFalse.
Here’s how you create variables to store these different data types.
# A variable holding a whole number (integer)
user_age = 25
# A variable holding a number with a decimal (float)
item_price = 19.99
# A variable holding text (string)
user_name = "Alex"
# A variable holding a truth value (boolean)
is_logged_in = True
# You can print the value of a variable to see it
print(user_name)
print(item_price)
Making Decisions and Repeating Tasks
Programs aren't just lists of instructions executed one after another. They need to make decisions and perform repetitive actions. This is handled by control structures.
To make a choice, you use an if statement. It checks if a condition is true and runs a block of code only if it is. You can also provide an else block for what to do if the condition is false.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("You might need a jacket.")
else:
print("The weather is pleasant.")
For repetitive tasks, we use loops. A for loop is great for when you want to repeat an action for every item in a collection, like a list of names. A while loop is used to repeat an action as long as a certain condition remains true.
# A 'for' loop that prints each name in a list
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")
# A 'while' loop that counts down from 5
count = 5
while count > 0:
print(count)
count = count - 1 # This is important to avoid an infinite loop!
print("Blast off!")
Packaging Your Code
As your scripts get bigger, you'll want to organize your code to keep it tidy and avoid repeating yourself. Functions and modules are the tools for this job.
function
noun
A named, reusable block of code that performs a specific task.
You define a function using the def keyword. This packages up a piece of logic that you can call by its name whenever you need it. This is much better than copying and pasting the same code everywhere.
# Define a simple function that greets a user
def greet_user(name):
print(f"Welcome, {name}!")
# Now, call the function with different names
greet_user("Maria")
greet_user("David")
Modules are simply Python files that contain functions and variables. Python has a rich standard library of built-in modules you can use. To use a function from a module, you first have to import it.
# Import the 'random' module to get access to its functions
import random
# Use a function from the module to pick a random number
random_number = random.randint(1, 10)
print(f"The random number is: {random_number}")
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. When these situations occur, Python raises an exception, which normally crashes your script.
To prevent this, you can use try...except blocks. You put the code that might fail inside the try block. If an error occurs, the code inside the except block is executed, and your program can continue running instead of crashing.
# Get input from the user
user_input = input("Enter a number: ")
try:
# Try to convert the input to a number (this might fail)
number = int(user_input)
result = 100 / number
print(f"100 divided by your number is: {result}")
except ValueError:
# This runs if the input wasn't a valid number
print("That's not a number! Please enter a numeric value.")
except ZeroDivisionError:
# This runs if the user entered 0
print("You can't divide by zero!")
This technique, called error handling, makes your scripts more robust and user-friendly.
Now, let's test your understanding of these core concepts.
In Python, what is the primary role of a variable?
What is the data type of the value assigned to the variable is_active in the following code? ```python
is_active = True
With variables, control structures, functions, and error handling, you now have the fundamental tools to start writing simple but powerful Python scripts.