Foundations of Python

Lesson 1: Introduction to Coding and IDE

What is code?

Code is a set of instructions that tell a computer what to do. It's like a recipe for a computer to follow. Just as you follow steps to bake a cake, a computer follows code to perform tasks.

In Python, we write code using simple, English-like commands that the computer can understand and execute.

Quick VS Code walkthrough

  1. Download and install VS Code from https://code.visualstudio.com/
  2. Open VS Code
  3. Create a new file: File > New File
  4. Save the file with a .py extension (e.g., my_first_code.py)
  5. Start typing your Python code in this file
  6. To run your code, use the integrated terminal: View > Terminal

Introduction to print statements

In Python, we use the print() function to display text or values on the screen. It's often the first thing beginners learn because it's simple and helps you see the results of your code.

1print("Hello, World!")
py

This will display "Hello, World!" when you run the code.

You can print multiple items by separating them with commas:

1print("Hello,", "World!")
py

Lab: Print various personal information

Now, let's practice using print statements to display some personal information.

Exercise: Create a new Python file and use print statements to display the following information about yourself:

  1. Your name
  2. Your age
  3. Your favorite color
  4. Your hobby

Here's an example of how your code might look:

1print("My name is Alice")
2print("I am 25 years old")
3print("My favorite color is blue")
4print("My hobby is playing guitar")
py

Try running this code and then modify it with your own information!

Remember, coding is about experimenting and learning. Don't be afraid to try different things and see what happens!

Lesson 2: Variables and Data Types

What are variables?

Variables are containers for storing data values. In Python, you can think of variables as labeled boxes that hold information.

1age = 25
2name = "Alice"
3print(age)    # Output: 25
4print(name)   # Output: Alice
py

Different data types

  • Integers: Whole numbers, positive or negative (e.g., 5, -3, 0)
  • Floats: Decimal numbers (e.g., 3.14, -0.5, 2.0)
  • Strings: Text, enclosed in quotes (e.g., "Hello", 'Python')
  • Booleans: True or False values
1integer_num = 42
2float_num = 3.14
3text = "Python is fun"
4is_true = True
py

Naming conventions for variables

  • Use lowercase letters and underscores for readability (e.g., my_variable)
  • Start with a letter or underscore, not a number
  • Be descriptive but concise
  • Avoid using Python keywords (e.g., if, for, while)
1# Good variable names
2user_age = 30
3first_name = "John"
4
5# Avoid these
61st_place = "Gold"  # Invalid: starts with a number
7for = "Loop"        # Invalid: 'for' is a Python keyword
py

String and variable concatenation

You can combine strings and variables using the + operator or f-strings (formatted string literals).

1name = "Alice"
2age = 25
3
4# Using + operator
5print("My name is " + name + " and I am " + str(age) + " years old.")
6
7# Using f-string (recommended)
8print(f"My name is {name} and I am {age} years old.")
py

Lab: Create and print variables of different types

Practice creating variables of different types and printing them:

1# Create variables of different types
2my_name = "Your Name"
3my_age = 20
4my_height = 1.75
5is_student = True
6
7# Print the variables
8print(f"Name: {my_name}")
9print(f"Age: {my_age}")
10print(f"Height: {my_height} meters")
11print(f"Is a student: {is_student}")
12
13# Create a sentence using the variables
14print(f"{my_name} is {my_age} years old, {my_height} meters tall, and it's {is_student} that they are a student.")
py

Try running this code and then modify it with your own information!

Lesson 3: Arithmetic and Input

Basic arithmetic operations

Python supports basic arithmetic operations using the following symbols:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
1a = 10
2b = 3
3print(f"Addition: {a + b}")        # Output: 13
4print(f"Subtraction: {a - b}")     # Output: 7
5print(f"Multiplication: {a * b}")  # Output: 30
6print(f"Division: {a / b}")        # Output: 3.3333...
py

Advanced operations

  • % for modulus (remainder of division)
  • ** for exponentiation (power)
  • // for floor division (division rounded down to nearest integer)
1a = 10
2b = 3
3print(f"Modulus: {a % b}")           # Output: 1
4print(f"Exponentiation: {a ** b}")   # Output: 1000
5print(f"Floor division: {a // b}")   # Output: 3
py

Order of operations (PEMDAS)

Python follows the PEMDAS rule for the order of operations:

  1. Parentheses
  2. Exponents
  3. Multiplication and Division (from left to right)
  4. Addition and Subtraction (from left to right)
1result = 5 + 3 * 2 ** 2 - (6 + 2) / 2
2print(f"Result: {result}")  # Output: 15.0
py

Using the input() function

The input() function allows you to get user input from the console.

1name = input("Enter your name: ")
2print(f"Hello, {name}!")
py

Converting input to different data types

The input() function always returns a string. To use it as a number, you need to convert it:

1age_str = input("Enter your age: ")
2age = int(age_str)
3print(f"Next year, you will be {age + 1} years old.")
4
5height_str = input("Enter your height in meters: ")
6height = float(height_str)
7print(f"Your height in centimeters is {height * 100} cm.")
py

Lab: Create a simple calculator

Let's create a simple calculator that can perform basic arithmetic operations:

1# Simple calculator
2num1 = float(input("Enter the first number: "))
3num2 = float(input("Enter the second number: "))
4operation = input("Enter the operation (+, -, *, /): ")
5
6if operation == "+":
7    result = num1 + num2
8elif operation == "-":
9    result = num1 - num2
10elif operation == "*":
11    result = num1 * num2
12elif operation == "/":
13if num2 != 0:
14    result = num1 / num2
15else:
16    result = "Error: Division by zero"
17else:
18    result = "Error: Invalid operation"
19
20print(f"Result: {result}")
py

Try running this code and test it with different numbers and operations!

Lesson 4: Conditional Statements

If statements

If statements allow you to execute code based on certain conditions. The basic syntax is:

1if condition:
2    # code to execute if condition is True
py

Example:

1age = 18
2if age >= 18:
3    print("You are an adult.")
py

Else and elif statements

'else' provides an alternative when the 'if' condition is False. 'elif' (else if) allows you to check multiple conditions.

1age = 15
2if age >= 18:
3    print("You are an adult.")
4elif age >= 13:
5    print("You are a teenager.")
6else:
7    print("You are a child.")
py

Logical conditions

Python uses these comparison operators:

  • > greater than
  • < less than
  • == equal to
  • != not equal to
  • >= greater than or equal to
  • <= less than or equal to
1x = 5
2y = 10
3print(x > y)   # False
4print(x < y)   # True
5print(x == y)  # False
6print(x != y)  # True
7print(x >= 5)  # True
8print(y <= 7)  # False
py

Combining conditions with logical operators

You can combine conditions using 'and', 'or', and 'not':

  • and: Both conditions must be True
  • or: At least one condition must be True
  • not: Inverts the condition (True becomes False, False becomes True)
1age = 25
2has_license = True
3
4if age >= 18 and has_license:
5    print("You can drive.")
6
7temperature = 28
8if temperature > 30 or temperature < 0:
9    print("Extreme weather!")
10
11is_raining = False
12if not is_raining:
13    print("It's a sunny day!")
py

Lab: Create a program with multiple conditions

Let's create a simple program that determines a person's life stage and activities based on their age:

1# Life stage and activity determiner
2
3age = int(input("Enter your age: "))
4
5if age < 0:
6    print("Invalid age entered.")
7elif age < 5:
8    print("You're a baby. Time for a nap!")
9elif age < 13:
10    print("You're a child. Let's play some games!")
11elif age < 20:
12    print("You're a teenager. How about learning a new skill?")
13elif age < 65:
14    print("You're an adult. Time to work or pursue your passions!")
15else:
16    print("You're a senior. Enjoy your retirement!")
17
18# Additional conditions
19if age >= 18:
20    print("You can vote in elections.")
21if age >= 21:
22    print("You can also run for political office.")
23
24if age < 16:
25    print("You can't drive yet.")
26elif 16 <= age < 18:
27    print("You can drive with restrictions.")
28else:
29    print("You can drive without restrictions.")
py

Try running this code with different ages and see how the output changes!

Lesson 5: Lists and Loops

Introduction to Lists

Lists are ordered collections of items in Python. They can contain elements of different types.

1# Creating a list
2fruits = ["apple", "banana", "cherry"]
3print(fruits)
4
5# Lists can contain different types
6mixed_list = [1, "hello", 3.14, True]
7print(mixed_list)
py

List Operations

Python provides various operations to work with lists:

1fruits = ["apple", "banana", "cherry", "date"]
2
3# Indexing (accessing elements)
4print(fruits[0])   # First element
5print(fruits[-1])  # Last element
6
7# Slicing
8print(fruits[1:3])  # Elements from index 1 to 2
9
10# Appending (adding to the end)
11fruits.append("elderberry")
12print(fruits)
13
14# Removing
15fruits.remove("banana")
16print(fruits)
17
18# Length of a list
19print(len(fruits))
py

For Loops

For loops allow you to iterate over sequences like lists.

1fruits = ["apple", "banana", "cherry"]
2
3# Looping through a list
4for fruit in fruits:
5    print(f"I like {fruit}")
6
7# Using range() function
8for i in range(5):
9    print(i)
10
11# Looping with index
12for index, fruit in enumerate(fruits):
13    print(f"Index {index}: {fruit}")
py

While Loops

While loops repeat as long as a condition is true.

1# Counting up
2count = 0
3while count < 5:
4    print(count)
5    count += 1
6
7# User input loop
8while True:
9    answer = input("Do you want to continue? (yes/no): ")
10    if answer.lower() != 'yes':
11        break
12print("Loop ended")
py

Lab: Create a program that manipulates lists using loops

Let's create a simple task management program using lists and loops:

1# Task Management Program
2
3tasks = []
4
5while True:
6print("\n--- Task Manager ---")
7print("1. Add task")
8print("2. View tasks")
9print("3. Mark task as done")
10print("4. Exit")
11
12choice = input("Enter your choice (1-4): ")
13
14if choice == '1':
15    task = input("Enter a new task: ")
16    tasks.append(task)
17    print("Task added successfully!")
18
19elif choice == '2':
20    if tasks:
21        print("\nYour tasks:")
22        for index, task in enumerate(tasks, start=1):
23            print(f"{index}. {task}")
24    else:
25        print("No tasks yet!")
26
27elif choice == '3':
28    if tasks:
29        print("\nYour tasks:")
30        for index, task in enumerate(tasks, start=1):
31            print(f"{index}. {task}")
32        task_num = int(input("Enter the number of the completed task: "))
33        if 1 <= task_num <= len(tasks):
34            done_task = tasks.pop(task_num - 1)
35            print(f"Task '{done_task}' marked as done!")
36        else:
37            print("Invalid task number!")
38    else:
39        print("No tasks to mark as done!")
40
41elif choice == '4':
42    print("Thank you for using Task Manager. Goodbye!")
43    break
44
45else:
46    print("Invalid choice. Please try again.")
py

This program demonstrates the use of lists and loops to create a simple task management system. It allows users to add tasks, view tasks, mark tasks as done, and exit the program.

Lesson 6: Functions and Modules

Defining Functions

1# Functions are reusable blocks of code
2# They help organize and simplify your program
3
4def say_hello():
5    print("Hello!")
6
7# Using the function
8say_hello()
py

Function parameters and return values

1# Parameters: inputs to a function
2# Return values: output from a function
3
4def add(a, b):
5    return a + b
6
7result = add(3, 4)
8print(result)  # Prints: 7
py

Importing modules

1# Modules are pre-written code you can use
2# We'll use 'random' for generating random numbers
3
4import random
5
6# Generate a random number between 1 and 10
7number = random.randint(1, 10)
8print(number)
py

Lesson 7: Advanced Flow Control

Nested if statements

1# An if inside another if
2   
3age = 16
4if age >= 13:
5    print("You're a teenager")
6    if age >= 18:
7       print("You're also an adult")
py

Nested loops

1# A loop inside another loop
2
3for i in range(3):
4    for j in range(2):
5        print(f"{i}-{j}")
py

Break statement

1# Exits a loop early
2   
3for i in range(5):
4    if i == 3:
5        break
6    print(i)
7# Prints: 0, 1, 2
py

Continue statement

1# Skips to the next loop iteration
2
3for i in range(5):
4    if i == 2:
5        continue
6    print(i)
7# Prints: 0, 1, 3, 4
py

Simple lab: Number guessing game

1secret = 5
2guess = int(input("Guess a number (1-10): "))
3
4if guess == secret:
5    print("You got it!")
6else:
7    if guess < secret:
8        print("Too low")
9    else:
10        print("Too high")
11    
12    guess = int(input("Try again: "))
13    if guess == secret:
14        print("You got it on the second try!")
15    else:
16        print(f"Sorry, it was {secret}")
py

Lesson 8: Object-Oriented Programming Basics

Introduction to Object-Oriented Programming (OOP)

  • OOP is a way to organize code by creating "objects"
  • Objects are like containers that hold related data and functions
  • This helps make code more organized and reusable

Defining classes and objects

1# A class is like a blueprint for creating objects
2# An object is an instance of a class
3   
4class Dog:
5    pass
6
7my_dog = Dog()  # Creating an object
py

Attributes and methods

1# Attributes are variables that belong to a class
2# Methods are functions that belong to a class
3   
4class Dog:
5    # Attribute
6    breed = "Labrador"
7
8    # Method
9    def bark(self):
10        print("Woof!")
11
12my_dog = Dog()
13print(my_dog.breed)  # Prints: Labrador
14my_dog.bark()  # Prints: Woof!
py

Constructor functions (__init__)

1# The __init__ method is called when creating a new object
2# It's used to set up initial values for the object
3   
4class Dog:
5    def __init__(self, name, age):
6        self.name = name
7        self.age = age
8
9my_dog = Dog("Buddy", 3)
10print(my_dog.name)  # Prints: Buddy
11print(my_dog.age)  # Prints: 3
py