Python for Data Science Essentials
Python Basics
Your First Steps in Python
Python is known for its clean and readable syntax. It’s designed to feel a lot like writing in English, which makes it a great language for beginners. The most basic instruction you can give is to display a message. In programming, the traditional first step is to make the computer say "Hello, World!".
# This is a comment. Python ignores lines starting with #.
# The print() function displays text to the screen.
print("Hello, World!")
That's it. One line of code is a complete Python program. The text inside the quotation marks is called a string, which is just a sequence of characters. The print() part is a function, a reusable block of code that performs a specific action. We'll look more at functions later.
Storing Information
To do anything useful, programs need to store and manage information. We do this using variables. Think of a variable as a labeled box where you can keep a piece of data. You give the box a name, and you can put things in it, take things out, or just see what's inside.
variable
noun
A named location in memory used to store a value that can be referenced and manipulated by a program.
The information you store comes in different types. For now, let's focus on four fundamental data types:
| Data Type | Description | Example |
|---|---|---|
Integer (int) | Whole numbers, without decimals. | 42, -100 |
Float (float) | Numbers with decimals. | 3.14, -0.5 |
String (str) | A sequence of text characters. | "Hello", 'Python' |
Boolean (bool) | Represents truth values. | True, False |
Assigning a value to a variable is simple. You use the equals sign (=), which is known as the assignment operator.
# Assigning different data types to variables
student_name = "Alex"
student_id = 78153
current_gpa = 3.85
is_enrolled = True
# You can print variables to see their values
print(student_name)
print(current_gpa)
Making Things Happen
Once you have data stored in variables, you can perform actions with them using operators. These are special symbols that carry out arithmetic or logical computations.
Arithmetic operators are straightforward. They let you perform mathematical calculations.
a = 15
b = 4
# Basic arithmetic
print(a + b) # Addition: 19
print(a - b) # Subtraction: 11
print(a * b) # Multiplication: 60
print(a / b) # Division: 3.75
print(a % b) # Modulo (remainder): 3
Comparison operators, on the other hand, are used to compare two values. The result of a comparison is always a Boolean value: True or False.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | a == b (False) |
!= | Not equal to | a != b (True) |
> | Greater than | a > b (True) |
< | Less than | a < b (False) |
>= | Greater than or equal to | a >= 15 (True) |
You can combine these comparisons using logical operators like and, or, and not to build more complex conditions.
Controlling the Flow
A program doesn't always run straight from top to bottom. Often, you need it to make decisions or repeat actions. This is called control flow.
The most common way to make a decision is with an if statement. It checks if a condition is true, and if it is, it runs a block of code. You can also provide alternative paths with elif (else if) and else.
temperature = 25
if temperature > 30:
print("It's a hot day!")
elif temperature < 10:
print("It's a cold day!")
else:
print("The weather is mild.")
To repeat actions, you use loops. A for loop is great for when you want to repeat a task a specific number of times. For example, you can iterate over a sequence of numbers.
# The range(5) function generates numbers from 0 up to (but not including) 5.
for number in range(5):
print("This is loop number", number)
A while loop is used to repeat a block of code as long as a certain condition remains true. It's like telling your program, "Keep doing this until I say stop."
count = 0
while count < 3:
print("Count is:", count)
count = count + 1 # This is crucial to avoid an infinite loop!
Creating Reusable Code with Functions
If you find yourself writing the same piece of code over and over, it's a good idea to package it into a function. A function is a named, reusable block of code that performs a single, related action.
Defining a function is simple. You use the def keyword, give the function a name, and specify any inputs (called parameters) it needs.
# Define a function that greets a person
def greet(name):
message = "Hello, " + name + "!"
return message
# Call the function with an argument and store the result
greeting_for_maria = greet("Maria")
print(greeting_for_maria)
greeting_for_sam = greet("Sam")
print(greeting_for_sam)
Functions help make your code more organized, readable, and efficient. By breaking down a large program into smaller, manageable functions, you make it much easier to build and maintain.
With these building blocks—syntax, variables, operators, control flow, and functions—you have the foundation for writing powerful Python programs.
Let's test your understanding of these core concepts.
Which line of Python code correctly prints the message 'Hello, World!' to the console?
In Python, what is the primary role of a variable?