Python Fundamentals OOP Frameworks
Python Basics
Getting Started with Python
Python is a powerful and versatile programming language, but its biggest strength is its simplicity. The code is designed to be readable and straightforward, which makes it an excellent choice for anyone new to programming.
Before you can write any code, you need to install Python on your computer. The best place to get it is from the official website, python.org. The site automatically suggests the right version for your operating system, whether you're on Windows, macOS, or Linux. The installation process is guided and usually just involves clicking 'Next' a few times. During installation on Windows, make sure to check the box that says 'Add Python to PATH' to make it easier to run from your command line.
Once installed, you'll have access to the Python interpreter and a simple code editor called IDLE. You're now ready to start programming.
Storing and Using Data
In programming, we need a way to store information that we can use later. We do this with variables. Think of a variable as a labeled box where you can put something. You give the box a name (the variable name) and place some data inside it (the value).
score = 100
username = "Alex"
Here, score and username are variable names. The first holds a number, and the second holds some text. Python automatically figures out the type of data you're storing.
The most common data types you'll encounter are:
- String (
str): Used for text. You create strings by wrapping text in single (') or double (") quotes. - Integer (
int): Used for whole numbers, like -5, 0, or 150. - Float (
float): Used for numbers with a decimal point, like 3.14 or -0.5. - Boolean (
bool): Represents one of two values:TrueorFalse. Booleans are essential for making decisions in your code.
# A string for text
greeting = "Hello, world!"
# An integer for a whole number
user_age = 30
# A float for a decimal number
item_price = 19.99
# A boolean for a true/false value
is_logged_in = True
Now that we know how to store data, let's look at how to manipulate it.
Operators and Decisions
Operators are special symbols that perform operations on values and variables. You already know some of them from math.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 10 / 2 | 5.0 |
% | Modulo | 10 % 3 | 1 |
** | Exponent | 2 ** 3 | 8 |
The modulo operator (%) gives you the remainder of a division. It's surprisingly useful, especially for checking if a number is even or odd.
Besides math, we also have comparison operators to compare values. These always result in a Boolean (True or False).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 5 <= 3 | False |
Be careful! A single equals sign (
=) is used for assigning a value to a variable, while a double equals sign (==) is used for comparing two values.
These comparisons are the building blocks of control structures, which allow your program to make decisions. The most common is the if statement. It runs a block of code only if a certain condition is True.
temperature = 30
if temperature > 25:
print("It's a hot day!")
elif temperature > 15:
print("It's a nice day.")
else:
print("It's cold.")
Notice the indentation. In Python, whitespace is important. The indented code belongs to the if, elif, or else block above it. This structure makes the code clean and easy to read.
What if you want to repeat an action multiple times? For that, we use loops. The for loop is great for iterating over a sequence of items, while the while loop runs as long as a condition is true.
# A for loop that prints numbers 0 through 4
for i in range(5):
print(i)
# A while loop that counts down from 3
count = 3
while count > 0:
print(count)
count = count - 1 # or count -= 1
print("Liftoff!")
Reusable Code and Interaction
As your programs get more complex, you'll find yourself writing the same bit of code over and over. A function is a reusable block of code that performs a specific task. You define it once and can call it whenever you need it.
# Define the function
def greet(name):
message = "Hello, " + name + "!"
return message
# Call the function and store its result
welcome_message = greet("World")
print(welcome_message)
In this example, greet is the function name. It takes one piece of information, name, as its input. Inside the function, it constructs a message and then uses return to send a value back as its output. Functions help keep your code organized, readable, and efficient.
Finally, most programs need to interact with the user. Python makes this easy with built-in functions for input and output. We've already been using print() to display output. To get input from the user, we use input().
# Get the user's name
name = input("What is your name? ")
# Print a personalized greeting
print("Nice to meet you, " + name + "!")
The input() function shows the user a prompt and waits for them to type something and press Enter. Whatever they type is returned as a string, which you can then store in a variable.
Let's test what you've learned.
When installing Python on Windows, which option is important to check to ensure you can easily run Python from the command line?
What will the following Python code snippet print to the screen?
score = 85
if score > 90:
print("A")
elif score > 80:
print("B")
else:
print("C")
These are the fundamental building blocks of Python. With variables, operators, control structures, and functions, you can start writing simple yet powerful programs.
