Python for Data Science and Computer Vision
Python Basics
The Language of Code
Think of a programming language like Python as a set of instructions for a computer. Just like any language, it has its own grammar and vocabulary. The rules of this grammar are called syntax. In Python, the syntax is designed to be clean and readable, which is why many people start their coding journey here.
syntax
noun
The set of rules that defines the combinations of symbols that are considered to be correctly structured statements or expressions in a language.
One of the first things you learn in any language is how to say hello. In Python, it's just one simple line.
print("Hello, world!")
This code calls the print() function to display the text "Hello, world!" on the screen. Notice the parentheses and quotation marks. These are part of Python's syntax. Whitespace also matters. Indentation, or the space at the beginning of a line, is used to define blocks of code, which we'll see soon.
Mastering Python fundamentals is like learning the alphabet before writing a novel.
Data and Its Forms
Programs work with data, and that data comes in different types. Python has several built-in data types, but let's start with the most common ones. You can think of a type as the category a piece of information belongs to.
| Data Type | Description | Example |
|---|---|---|
String (str) | A sequence of characters, like text. | "apple" |
Integer (int) | A whole number. | 10 |
Float (float) | A number with a decimal point. | 3.14 |
Boolean (bool) | Represents truth values. | True or False |
We store data in variables. A variable is like a labeled box where you can keep information. You create one using an equals sign.
# A variable named 'fruit' holding a string
fruit = "apple"
# A variable named 'quantity' holding an integer
quantity = 10
# A variable named 'price' holding a float
price = 1.25
# A variable named 'in_stock' holding a boolean
in_stock = True
Python automatically knows the type of data you assign to a variable. This flexibility makes it easy to get started.
Making Decisions and Repeating Actions
Programs rarely run straight from top to bottom. They need to make decisions and perform repetitive tasks. That's where control structures come in. The most common decision-maker is the if statement. It checks if a condition is true and runs a block of code only if it is.
temperature = 30
if temperature > 25:
# This code only runs if the condition is true
print("It's a hot day!")
else:
# This code runs if the condition is false
print("It's not too hot.")
Notice the indentation. The print() statements are indented, which tells Python they belong to the if and else blocks.
To repeat actions, we use loops. A for loop is great for iterating over a sequence of items, like a list of words.
fruits = ["apple", "banana", "cherry"]
for f in fruits:
print(f)
This loop will print "apple", then "banana", then "cherry", each on a new line.
Creating Reusable Code
As your programs get more complex, you'll find yourself writing the same bits of code over and over. Functions let you bundle up a piece of code, give it a name, and run it whenever you want. We've already used a built-in function: print().
Functions help keep your code organized, reusable, and easier to understand. This is a core principle of good programming.
You can define your own functions using the def keyword. Let's create a function that greets someone by name.
# Define the function
def greet(name):
message = "Hello, " + name + "!"
return message
# Call the function and print the result
greeting = greet("Alice")
print(greeting)
Here, name is a parameter, a piece of information the function needs to do its job. The return keyword sends a value back from the function.
Handling the Unexpected
Sometimes, things go wrong. A user might enter text when you expect a number, or you might try to divide by zero. These events cause errors, or exceptions, that can crash your program. Python provides a way to handle these gracefully using try and except blocks.
try:
# Code that might cause an error
result = 10 / 0
print(result)
except ZeroDivisionError:
# Code that runs if that specific error happens
print("Oops! You can't divide by zero.")
The code inside the try block is executed first. If an error occurs, Python jumps to the except block without crashing. This makes your programs more robust and user-friendly.
With these building blocks—syntax, data types, control structures, functions, and error handling—you have the foundation for writing powerful Python programs.
Time to check your understanding of these core concepts.
In Python, what is the primary role of indentation?
Which keyword is used to define a new function in Python?
Understanding these fundamentals is the first and most important step in learning to program in Python.