Object-Oriented Python for PET Imaging
Python Basics
The Grammar of Python
Every language, whether spoken or programmed, has rules. In programming, these rules are called syntax. Python is famous for its clean and readable syntax, which often resembles plain English. This makes it a great language for beginners.
At the heart of Python are variables. Think of a variable as a labeled box where you can store information. You give the box a name and put something inside it. You can change what's inside the box later.
# Create a variable named 'greeting'
# and store the text "Hello, world!" in it.
greeting = "Hello, world!"
# Print the contents of the variable to the screen.
print(greeting)
The equal sign = is the assignment operator. It takes the value on the right and assigns it to the variable on the left. The print() command is a built-in function that displays output to the screen. But what kind of information can we store in these variables? That brings us to data types.
Different Kinds of Data
Data comes in many forms, and Python needs to know what kind of data it's dealing with. Is it a number? A piece of text? A simple yes or no? These categories are called data types.
Let's look at the most common ones:
# String: Text, enclosed in quotes.
book_title = "The Hitchhiker's Guide to the Galaxy"
# Integer: A whole number, without a decimal.
publication_year = 1979
# Float: A number with a decimal point.
average_rating = 4.2
# Boolean: Represents truth, can only be True or False.
is_science_fiction = True
Understanding these types is crucial because they determine what you can do with the data. You can perform math on integers and floats, but you can't multiply two book titles together. Here's a quick summary:
| Data Type | Description | Example |
|---|---|---|
String (str) | A sequence of characters (text) | "Python" |
Integer (int) | Whole numbers | 10 or -50 |
Float (float) | Numbers with a decimal point | 3.14 |
Boolean (bool) | Logical values | True or False |
Controlling the Flow
A program isn't just a list of instructions executed from top to bottom. It needs to make decisions and perform repetitive tasks. This is where control structures come in. They direct the flow of your code.
Conditionals let your code react differently to different situations. The most common conditional is the if statement. It checks if a condition is true, and if it is, it runs a block of code.
temperature = 75
if temperature > 70:
print("It's a warm day!")
elif temperature > 50:
print("It's a bit cool.")
else:
print("It's cold outside.")
Here, the code checks the temperature. Since 75 is greater than 70, it prints "It's a warm day!" and skips the rest. elif (else if) lets you check another condition, and else runs if no previous conditions were true.
What about repeating actions? That's where loops come in. A for loop is great for when you want to do something a specific number of times or for each item in a list.
# This loop runs for numbers 0, 1, 2, 3, and 4.
for number in range(5):
print("The current number is", number)
A while loop is different. It keeps running as long as its condition remains true. You have to be careful that the condition eventually becomes false, or you'll create an infinite loop!
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Decrease the value
print("Liftoff!")
Creating Reusable Code
Sometimes you need to perform the same task over and over again in different parts of your program. Instead of copying and pasting code, you can package it into a reusable block called a function. You give the function a name and can then "call" it whenever you need it.
Functions can also take in data, called arguments, to work with. Here's a function that takes a name as an argument and prints a personalized greeting.
# Define a function named 'greet'
# It accepts one argument, 'name'.
def greet(name):
message = "Hello, " + name + "!"
print(message)
# Now, call the function with different arguments.
greet("Alice")
greet("Bob")
Functions can also process data and return a result. This is incredibly powerful. Let's create a function that adds two numbers.
# This function adds two numbers and returns the result.
def add_numbers(a, b):
return a + b
# Call the function and store the returned value in a variable.
sum_result = add_numbers(5, 7)
print("The sum is:", sum_result)
Using functions makes your code more organized, easier to read, and less repetitive. Mastering variables, data types, control structures, and functions will give you a solid foundation for building almost anything in Python.
Ready to test your knowledge?
What is the data type of the variable price after this line of code is executed? price = 19.99
Which control structure is designed to execute a block of code repeatedly as long as a specific condition remains true?