No history yet

Python Basics

Your First Steps in Python

Every language, whether spoken or for programming, has its own set of rules. This is its syntax. Python's main goal is readability, so its syntax is clean and straightforward. Unlike many other languages that use brackets or keywords to group code, Python uses simple indentation. This might seem strange at first, but it forces code to be neat and easy to read.

syntax

noun

The set of rules that defines the combinations of symbols that are considered to be correctly structured programs in a specific programming language.

Let's start with the classic first program. To tell the computer to display a message, you use the print() function.

# This is a comment. Python ignores lines starting with #
# The print() function displays text to the screen.
print("Hello, World!")

Data and Variables

Programs work with information, or data. To keep track of this data, we store it in variables. Think of a variable as a labeled box where you can put a piece of information. You give the box a name, and then you can refer to it later.

Creating a variable in Python is simple. You just choose a name, use the equals sign (=), and provide the value you want to store.

# Store the text "Welcome to Python" in a variable named 'greeting'
greeting = "Welcome to Python"

# Store the number 42 in a variable named 'answer'
answer = 42

# Now we can print the contents of the variables
print(greeting)
print(answer)

Python handles several basic types of data. You don't need to tell Python what type of data a variable will hold; it figures it out automatically. The most common types are:

  • Strings: Used for text. You create them by wrapping text in single (') or double (") quotes.
  • Integers: Used for whole numbers, like -5, 0, or 100.
  • Floats: Used for numbers with a decimal point, like 3.14 or -0.5.
  • Booleans: Used for representing truth values. They can only be True or False.
# A string
user_name = "Alex"

# An integer
user_age = 25

# A float
account_balance = 150.75

# A boolean
is_active = True

Making Decisions and Repeating Actions

So far, our code runs straight from top to bottom. But what if we want it to make decisions? We can control the flow of our program using if, elif (short for "else if"), and else statements. This lets our code react differently based on certain conditions.

temperature = 22

if temperature > 30:
    print("It's a hot day!")
elif temperature > 20:
    print("It's a nice day.")
else:
    print("It might be a bit cold.")

# Output will be: It's a nice day.

Notice the indentation. In Python, the indented code "belongs" to the statement above it. The print statements are inside the if, elif, or else blocks.

What if you need to repeat an action multiple times? That's where loops come in. The for loop is great for when you want to repeat something a specific number of times or go through each item in a list.

# This loop will run 5 times
# range(5) generates numbers from 0 up to (but not including) 5
for number in range(5):
    print("Hello!")

The while loop is used when you want to keep repeating an action as long as a certain condition is True.

count = 0

while count < 3:
    print("Still counting...")
    # This line increases the value of count by 1 each time the loop runs
    count = count + 1

print("Done counting.")

Building Reusable Code Blocks

If you find yourself writing the same piece of code over and over, you can package it into a function. A function is a named, reusable block of code that performs a specific task. You define it once and can then "call" it whenever you need it.

Functions are defined with the def keyword, followed by the function's name and parentheses (). You can also pass data into a function by putting variables inside the parentheses. These are called parameters.

# Define a function named 'greet' that takes one parameter, 'name'
def greet(name):
    # This is the code inside the function
    print(f"Hello, {name}!")

# Now, call the function with different arguments
greet("Alice")
greet("Bob")

Functions can also send a value back to the code that called them. This is called returning a value, and it's done with the return keyword.

# This function takes two numbers and returns their sum
def add_numbers(num1, num2):
    result = num1 + num2
    return result

# Call the function and store the returned value in a variable
sum_result = add_numbers(5, 3)
print(sum_result) # This will print 8

With these building blocks, you can start writing simple yet powerful programs. Let's review what we've learned.

Quiz Questions 1/6

How does Python group blocks of code, such as the body of an if statement or a loop?

Quiz Questions 2/6

What is the data type of the value 10.5 in Python?