Task 4a · Python Basics
up to +100 XP
Stop 4a.2 · Task 4a · 7 min

Python Basics

Master fundamental Python programming concepts and syntax

Learning Objectives:
  • Understand Python syntax and basic programming concepts
  • Learn variables, data types, and operators
  • Master control structures (if, loops)
  • Apply functions and basic input/output operations
  • Develop problem-solving skills with Python

Introduction to Python

Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in web development, data science, automation, and software development.

Key Features

Variables and Data Types

Variables store data values and Python has several built-in data types.

Variable Assignment

# Variable assignment
name = "Alice"
age = 25
height = 5.6
is_student = True

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

Basic Data Types

# Integers
count = 42
negative = -10

# Floats
price = 19.99
temperature = -5.5

# Strings
message = "Hello, World!"
single_quotes = 'Python is great'

# Booleans
is_valid = True
is_complete = False

# Check data type
print(type(count))      # 
print(type(price))      # 
print(type(message))    # 

Operators

Python provides various operators for performing operations on variables and values.

Arithmetic Operators

# Basic arithmetic
a = 10
b = 3

addition = a + b        # 13
subtraction = a - b     # 7
multiplication = a * b  # 30
division = a / b        # 3.333...
floor_division = a // b # 3
modulus = a % b         # 1
exponentiation = a ** b # 1000

Comparison Operators

# Comparison operators
x = 5
y = 10

equal = x == y          # False
not_equal = x != y      # True
greater = x > y         # False
less = x < y            # True
greater_equal = x >= y  # False
less_equal = x <= y     # True

Logical Operators

# Logical operators
a = True
b = False

and_result = a and b    # False
or_result = a or b      # True
not_result = not a      # False

# With conditions
age = 20
has_license = True
can_drive = age >= 18 and has_license  # True

Strings

Strings are sequences of characters used to store text data.

String Operations

# String creation
name = "Python"
greeting = 'Hello'

# String concatenation
message = greeting + " " + name  # "Hello Python"

# String repetition
repeated = "Ha" * 3  # "HaHaHa"

# String indexing
first_char = name[0]    # "P"
last_char = name[-1]    # "n"

# String slicing
substring = name[1:4]   # "yth"

String Methods

# Common string methods
text = "  Hello World  "

upper_text = text.upper()           # "  HELLO WORLD  "
lower_text = text.lower()           # "  hello world  "
stripped = text.strip()             # "Hello World"
replaced = text.replace("World", "Python")  # "  Hello Python  "
split_text = text.strip().split()   # ["Hello", "World"]

# String formatting
name = "Alice"
age = 25
formatted = f"My name is {name} and I am {age} years old"
print(formatted)

Input and Output

Python provides simple functions for getting user input and displaying output.

Output with print()

# Basic printing
print("Hello, World!")
print("The answer is", 42)

# Multiple values
name = "Alice"
age = 25
print("Name:", name, "Age:", age)

# Formatted output
print(f"Name: {name}, Age: {age}")

# Print with separators
print("A", "B", "C", sep="-")  # A-B-C

Input with input()

# Getting user input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Converting input to numbers
age_str = input("Enter your age: ")
age = int(age_str)

# Direct conversion
height = float(input("Enter your height: "))

Control Structures

Control structures determine the flow of program execution.

Conditional Statements

# if statement
age = 18
if age >= 18:
    print("You are an adult")

# if-else statement
score = 85
if score >= 60:
    print("You passed!")
else:
    print("You failed!")

# if-elif-else statement
grade = 85
if grade >= 90:
    print("Grade: A")
elif grade >= 80:
    print("Grade: B")
elif grade >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Loops

# for loop with range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# for loop with range parameters
for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

# for loop with step
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# while loop
count = 0
while count < 5:
    print(count)
    count += 1

# Loop control
for i in range(10):
    if i == 3:
        continue  # Skip iteration
    if i == 7:
        break     # Exit loop
    print(i)

Lists

Lists are ordered collections that can store multiple items.

List Basics

# Creating lists
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]

# Accessing elements
first = numbers[0]      # 1
last = numbers[-1]      # 5

# List slicing
subset = numbers[1:4]   # [2, 3, 4]

# List length
length = len(numbers)   # 5

List Methods

# Modifying lists
fruits = ["apple", "banana"]

# Adding elements
fruits.append("orange")         # ["apple", "banana", "orange"]
fruits.insert(1, "grape")       # ["apple", "grape", "banana", "orange"]

# Removing elements
fruits.remove("banana")         # ["apple", "grape", "orange"]
last_fruit = fruits.pop()       # "orange", list becomes ["apple", "grape"]

# Other operations
fruits.sort()                   # Sort in place
fruits.reverse()                # Reverse in place
count = fruits.count("apple")   # Count occurrences

Functions

Functions are reusable blocks of code that perform specific tasks.

Defining Functions

# Basic function
def greet():
    print("Hello, World!")

# Call the function
greet()

# Function with parameters
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")

# Function with return value
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)  # 8

Function Parameters

# Default parameters
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")              # Hello, Alice!
greet("Bob", "Hi")          # Hi, Bob!

# Multiple return values
def get_name_age():
    return "Alice", 25

name, age = get_name_age()

# Variable arguments
def sum_all(*numbers):
    return sum(numbers)

total = sum_all(1, 2, 3, 4, 5)  # 15

Error Handling

Handle errors gracefully to prevent program crashes.

Try-Except Blocks

# Basic error handling
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# General exception handling
try:
    # Some risky operation
    pass
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    print("This always executes")

File Operations

Read from and write to files for data persistence.

Reading Files

# Reading entire file
try:
    with open("data.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found!")

# Reading line by line
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

Writing Files

# Writing to file
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Python is great!")

# Appending to file
with open("output.txt", "a") as file:
    file.write("\nAppended text")

Common Programming Patterns

Useful patterns for solving common programming problems.

Input Validation

# Validate numeric input
def get_valid_number(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please enter a valid number!")

age = get_valid_number("Enter your age: ")

Menu Systems

# Simple menu system
def show_menu():
    print("1. Option 1")
    print("2. Option 2")
    print("3. Exit")

while True:
    show_menu()
    choice = input("Enter choice: ")
    
    if choice == "1":
        print("You chose option 1")
    elif choice == "2":
        print("You chose option 2")
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Invalid choice!")

Best Practices

Guidelines for writing clean, readable Python code.

Code Style

Example: Well-Structured Program

# Calculator program with good structure
def add(a, b):
    """Add two numbers and return the result."""
    return a + b

def subtract(a, b):
    """Subtract b from a and return the result."""
    return a - b

def get_number(prompt):
    """Get a valid number from user input."""
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please enter a valid number!")

def main():
    """Main program function."""
    print("Simple Calculator")
    
    num1 = get_number("Enter first number: ")
    num2 = get_number("Enter second number: ")
    
    print(f"Addition: {add(num1, num2)}")
    print(f"Subtraction: {subtract(num1, num2)}")

if __name__ == "__main__":
    main()
Quick check · 13 questions · up to 100 XP

Check what stuck.

+10 XP each
Question 1

Question 1 of 13

Which function is used to display output in Python?

Question 2

Question 2 of 13

What operator is used for exponentiation in Python?

Question 3

Question 3 of 13

Which function gets input from the user?

Question 4

Question 4 of 13

What is the correct way to create a list in Python?

Question 5

Question 5 of 13

Which keyword is used to define a function?

Question 6

Question 6 of 13

What does the len() function return?

Question 7

Question 7 of 13

Which statement is used to handle exceptions?

Question 8

Question 8 of 13

What is the standard indentation in Python?

Question 9

Question 9 of 13

Which loop is best for iterating a specific number of times?

Question 10

Question 10 of 13

What is the recommended way to open files in Python?

Question 11

Question 11 of 13 · Coding

Write average(numbers) that returns the mean of a list, or 0 for an empty list.

Open the IDE
Hint

sum(numbers) / len(numbers), but check for an empty list first.

Question 12

Question 12 of 13 · Coding

Write money(amount) that formats a number as pounds with a comma and two decimal places, for example money(1234.5) gives "£1,234.50".

Open the IDE
Hint

An f-string can do it: f"£{amount:,.2f}"

Question 13

Question 13 of 13 · Coding

Write count_model(models, name) that returns how many times name appears in the list models, without using .count().

Open the IDE
Hint

Start a counter at 0 and add 1 each time an item equals name.