Python for AI: Hash Maps, State Machines, and Similarity
Python Basics
Variables and Data Types
Think of a variable as a labeled box where you can store information. You give the box a name, and inside you place a piece of data. This makes it easy to refer to that data later on.
In Python, the data you store comes in different flavors, or data types. The most common ones are:
- Integers: Whole numbers, like 10, -5, or 0.
- Floats: Numbers with a decimal point, like 3.14 or -0.5.
- Strings: Text, enclosed in single or double quotes. For example, 'hello' or "Python".
- Booleans: Represents one of two values:
TrueorFalse. They're essential for making decisions in your code.
# Variable assignments
# An integer
user_age = 25
# A float
pi_value = 3.14159
# A string
user_name = "Alex"
# A boolean
is_learning = True
# You can print them to see their values
print(user_name)
print(user_age)
Making Decisions and Repeating Actions
Programs aren't just lists of instructions executed one after another. They need to react to different situations and perform repetitive tasks. That's where control structures come in.
To make decisions, we use if statements. An if statement checks if a certain condition is true. If it is, the code inside that statement runs. You can also provide alternative paths with elif (else if) and a final fallback with else.
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.")
For repetitive tasks, we use loops. A for loop is great for when you want to do something for each item in a list. For example, you could loop through a list of names and print a greeting for each one.
A while loop is different. It keeps running as long as a certain condition remains true. It's useful when you don't know exactly how many times you'll need to repeat the action.
# A for loop that iterates through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")
# A while loop that counts down
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blast off!")
Packaging and Reusing Code
As your programs get bigger, you'll find yourself writing the same bits of code over and over. Functions let you package a block of code, give it a name, and run it whenever you want just by calling its name. It's like creating your own custom tool.
A function can take inputs, called arguments, and can produce an output, called a return value.
# Define a function that adds two numbers
def add_numbers(num1, num2):
result = num1 + num2
return result
# Call the function and store its return value
sum_result = add_numbers(5, 7)
print(sum_result) # Output will be 12
Python also comes with a rich standard library, organized into modules. A module is simply a file containing Python definitions and statements. To use the tools from a module, you just need to import it. For instance, the math module gives you access to more advanced mathematical functions.
# Import the math module
import math
# Use the sqrt function from the math module
number = 16
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}.")
Talking to Your Program
A program is more useful when it can interact with a person. We've already been using one key function for this: print(). It displays information to the user.
To get information from the user, you can use the input() function. It shows the user a prompt and then waits for them to type something and press Enter. The text they type is then returned as a string, which you can store in a variable.
# Ask the user for their name
name = input("What is your name? ")
# Print a personalized greeting
print(f"Hello, {name}! Nice to meet you.")
These are the fundamental building blocks of Python. With variables, control structures, functions, and a way to communicate with the user, you can start writing simple but powerful programs.
What is the data type of the value 9.8 in Python?
Which type of loop is best suited for iterating over a known sequence of items, like a list of names?