Python Automation and AI Integration
Python Basics
Getting Started with Python
Python is a popular programming language known for its clear, readable syntax. It's like writing in a simplified version of English, which makes it a great choice for beginners.
First, you'll need to install Python on your computer. You can download the latest version from the official website, python.org. The installer includes a program called IDLE, which is a simple environment where you can write and run your first lines of code.
Once installed, open IDLE. You'll see a window with a >>> prompt. This is the Python shell, where you can type commands and see immediate results. Think of it as a direct line of communication with the Python interpreter.
Your First Program
A long-standing tradition in programming is to make your first program display the text "Hello, World!". In Python, this is incredibly simple. You just need one command.
The print() function is used to display output to the screen. Whatever you put inside the parentheses (and inside quotes, if it's text) will be printed.
print("Hello, World!")
Type that line into the IDLE shell and press Enter. Python will immediately execute the command and show you the result.
Hello, World!
Congratulations, you've just written and run your first Python program.
Storing Information
Programs need to work with information, like numbers, text, or more complex data. To keep track of this information, we use variables. A variable is like a labeled box where you can store a value.
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.
You create a variable by choosing a name and using the equals sign (=) to assign it a value. This is called an assignment statement.
# Assigning the text "Alice" to the variable named 'user_name'
user_name = "Alice"
# Printing the value stored in the variable
print(user_name)
The information you store comes in different forms, or data types. For now, let's look at the most common ones.
| Data Type | Description | Example |
|---|---|---|
| String | A sequence of characters (text) | "Hello" or 'Python' |
| Integer | A whole number | 10, -5, 1234 |
| Float | A number with a decimal point | 3.14, -0.5, 2.0 |
| Boolean | Represents truth values | True or False |
Python is smart enough to figure out the data type on its own. You don't have to tell it that 10 is an integer or that "Alice" is a string. This feature is called dynamic typing.
Making Decisions and Repeating Actions
So far, our code runs straight from top to bottom. But what if we want to run certain code only if a condition is met? Or repeat a task multiple times? This is where control structures come in.
Conditional statements (
if,elif,else) let you execute different blocks of code based on whether a condition is true or false.
Imagine checking if you're old enough to vote. You can use an if statement to make a decision.
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Notice the indentation (the space before print). In Python, indentation is not just for looks; it's how you group statements together. The code that is indented under the if line runs only when the condition age >= 18 is true.
Now, let's talk about repetition. Loops allow you to execute a block of code multiple times. The for loop is perfect for when you want to repeat an action a specific number of times.
# This loop will run 5 times
# range(5) generates numbers from 0 up to (but not including) 5
for number in range(5):
print("This is loop number", number)
Another type is the while loop, which repeats as long as its condition remains true. It's useful when you don't know in advance how many times you need to loop.
count = 1
while count <= 3:
print("Executing while loop, count is", count)
count = count + 1 # This increases the count by 1 each time
Organizing Code with Functions
As your programs get bigger, you'll find yourself writing the same chunks of code over and over. Functions let you package a block of code, give it a name, and reuse it whenever you need it. We've already used a built-in function: print().
You can define your own functions using the def keyword. Here's a simple function that greets a user by name.
# Define the function
def greet(name):
print("Hello, " + name + "!")
# Call the function with different arguments
greet("Alice")
greet("Bob")
In this example, name is a parameter, a placeholder for the value you'll provide when you call the function. The values "Alice" and "Bob" are arguments passed to the function.
Python also comes with many pre-written functions organized into modules. A module is a file containing Python code that you can import and use in your own programs. For example, the math module gives you access to mathematical functions and constants.
# Import the 'math' module to use its contents
import math
# Use the sqrt function from the math module
root = math.sqrt(16)
print(root)
# Use the pi constant from the math module
print(math.pi)
Interacting with the User
So far, our programs have been self-contained. To make them interactive, we need a way to get input from the user. The input() function does exactly that. It displays a prompt to the user and waits for them to type something and press Enter.
# Prompt the user for their name
user_name = input("What is your name? ")
# Use the user's input in a greeting
print("Nice to meet you, " + user_name + "!")
One important detail: the input() function always returns the user's input as a string. If you need to treat it as a number, you have to convert it using functions like int() or float().
age_string = input("How old are you? ")
age_number = int(age_string) # Convert the string to an integer
next_year = age_number + 1
print("Next year, you will be " + str(next_year)) # Convert back to string to print
These are the fundamental building blocks of Python. With variables, control structures, functions, and I/O, you can start writing simple yet powerful programs to solve all sorts of problems.
