Python for Everyday Productivity
Python Basics
The Grammar of Python
Every language has rules, and programming languages are no different. In Python, these rules are called syntax. Think of it as the grammar that allows us to communicate clearly with the computer. Luckily, Python's syntax is known for being clean and readable.
One of the most important rules in Python is indentation. Unlike other languages that use brackets or keywords to group code, Python uses whitespace. Blocks of code that belong together, like the steps inside a loop, must be indented at the same level. This makes the code visually organized and easy to follow.
print("Hello, world!")
# This is a comment. Python ignores anything after a # symbol.
# Notice there's no semicolon at the end. Python doesn't need them.
Data in Different Shapes
Programming is all about working with data. Python needs to know what kind of data it's handling, whether it's a number, a piece of text, or a simple true/false value. These categories are called data types.
Let's look at the most common ones. We store data in variables, which are like labeled containers.
# An integer (a whole number)
age = 30
# A float (a number with a decimal)
price = 19.99
# A string (text, enclosed in quotes)
name = "Alice"
# A boolean (True or False)
is_active = True
You can check a variable's type using the type() function. For example, type(age) would tell you it's an int (short for integer).
Making Decisions and Repeating Actions
A program that just runs straight from top to bottom isn't very smart. We need ways to control the flow of execution, making decisions and repeating actions. These are called control structures.
To make decisions, we use if, elif (else if), and else. The program checks a condition, and if it's true, it runs a specific block of code.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("Better bring a jacket.")
else:
print("The weather is perfect.")
To repeat actions, we use loops. A for loop is great for iterating over a sequence of items, like a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")
A while loop keeps running as long as a certain condition remains true. It's useful when you don't know exactly how many times you need to repeat.
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blast off!")
Reusable Code Blocks
If you find yourself writing the same piece of code over and over, it's time to create a function. A function is a named, reusable block of code that performs a specific task. You define it once and can call it whenever you need it.
Functions can take inputs, called arguments, to make them more flexible. Here, we define a function greet that takes a name as an argument.
# Defining the function
def greet(name):
print(f"Hello, {name}!")
# Calling the function with different arguments
greet("Bob")
greet("Charlie")
Functions can also process data and return a result.
def add_five(number):
return number + 5
result = add_five(10)
print(result) # This will print 15
Handling the Unexpected
Sometimes, code doesn't work as planned. Users might enter text where a number is expected, or a program might try to divide by zero. These events cause errors, or exceptions, that can crash your script. Error handling allows you to anticipate these problems and manage them gracefully.
Python uses a try...except block for this. You put the risky code in the try block. If an error occurs, the code in the except block is executed instead of the program crashing.
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
This prevents the program from stopping and lets you provide a helpful message or try an alternative action.
In Python, what is used to define a block of code, such as the body of a function or a conditional statement?
What would the following code print to the console? ```python print(type(15.0))
These are the fundamental building blocks of Python. With variables, data types, control structures, and functions, you have the tools to start writing simple scripts to automate your own tasks.