IS4010: AI-Enhanced Application Development

Week 3: Python Basics & Control Flow

Brandon M. Greenwell

Session 1

Python fundamentals

What is a variable?

  • Think of a variable as a labeled box where you can store a piece of information.
  • We assign a value to a variable using the equals sign (=).
  • The basic syntax is variable_name = value.
  • Naming convention: we use snake_case for variable names in python (e.g., first_name, user_age). Names should be descriptive.
# Example of variables
first_name = "grace"
last_name = "hopper"
year_of_birth = 1906

Core data types

  • Python has several built-in types to represent different kinds of data.
  • str (string): used for text. enclosed in single (') or double (") quotes.
  • int (integer): used for whole numbers.
  • float (floating-point): used for numbers with a decimal point.
  • bool (boolean): used for True or False values.

Getting user input

  • We can get input from a user in the terminal using the built-in input() function.
  • Important: the input() function always returns the data as a string.
  • If you need a number, you must convert the string using int() or float().
# Get a user's name (which is already a string)
name = input("what is your name? ")

# Get a user's age (which needs to be converted to an integer)
age_string = input("what is your age? ")
age_integer = int(age_string)

Let’s build something (part 1)

  • The first part of lab 03 will be to build a “mad libs” generator.
  • This simple application will use all the concepts we just discussed.
  • You will use input() to ask the user for nouns, verbs, and adjectives.
  • Then, you will use print() with an f-string to plug their words into a story.

Session 2

Controlling the flow

Making decisions with if

  • Often, we only want to run code if a certain condition is true. This is called conditional logic.
  • We use the if, elif (else if), and else keywords to control which blocks of code are executed.
  • The code inside a block must be indented.
age = 20

if age >= 21:
    print("you are old enough to enter.")
elif age >= 18:
    print("you are old enough to vote, but not to enter.")
else:
    print("you are not old enough to enter.")

Repeating actions with loops

  • Loops allow us to run the same block of code multiple times.
  • for loop: use this when you want to do something for every item in a collection.
  • while loop: use this when you want to keep doing something as long as a certain condition is true.
# A for loop that prints each name in a list
names = ["grace", "ada", "katherine"]
for name in names:
    print(name)

# A while loop that counts down from 3
count = 3
while count > 0:
    print(count)
    count = count - 1
print("liftoff!")

Let’s build something (part 2)

  • The second part of lab 03 will be to build a “number guessing game.”
  • This game will use the control flow concepts we just covered.
  • It will use a while loop to keep the game running until the user guesses correctly.
  • It will use if/elif/else statements to tell the user if their guess is too high, too low, or correct.

A new development workflow

  • Starting this week, we are adding a crucial component to our workflow: automated testing.
  • In professional development, we write code that tests our application code.
  • This ensures that our functions work as expected and that new changes don’t break existing features.
  • This process of frequently integrating and testing code is called continuous integration or CI.

Our tool #1: pytest

  • pytest is a popular Python framework for writing tests.
  • It looks for files with specific names to run. By convention:
    • Test filenames must start with test_ (e.g., test_lab03.py).
    • Test function names must also start with test_ (e.g., def test_...():).
  • We will provide these test files for you for each lab.

The anatomy of a pytest test

  • A test function checks if a piece of your code produces the correct output.
  • The assert keyword is the core of the test.
  • If the condition after assert is True, the test passes. If it’s False, the test fails.
# In your lab03.py file
def add(a, b):
    return a + b

# In the provided test_lab03.py file
def test_add():
    """This function tests the add function."""
    assert add(2, 3) == 5 # Test passes if add(2, 3) returns 5
    assert add(-1, 1) == 0 # Test also passes

Our tool #2: GitHub Actions

  • So, how do we run these tests automatically? With GitHub Actions.
  • GitHub Actions is a tool built into GitHub that can automate tasks for us.
  • We will configure it to do one primary job in this course: run pytest every single time you git push your code.

Understanding the workflow file

  • In Lab 03, you will create a file at .github/workflows/main.yml.
  • This file tells GitHub Actions what to do. Here’s a high-level summary of its job:
    • on: [push]: “Run this workflow every time someone pushes code.”
    • runs-on: ubuntu-latest: “Spin up a fresh, new virtual computer running Linux.”
    • steps:: “Then, follow these steps in order:”
      1. Check out a copy of your code.
      2. Set up the correct version of Python.
      3. Install the pytest library.
      4. Run the pytest command.

The feedback loop: your automated grade

  • Once you push your code, you can go to the Actions tab of your repository on GitHub.
  • You will see your workflow running. After a minute or two, you’ll get the result:
    • A green checkmark ✅ means all tests passed. Your lab is correct.
    • A red X ❌ means at least one test failed. You need to debug your code, commit, and push again.
  • This is your instant feedback and, for most labs, your grade!

Introducing lab 03 & CI/CD

  • This week’s lab will have you build the two small python applications we just discussed.
  • New for this lab: we will also set up automated testing for your code using pytest and continuous integration with github actions.
  • This is a one-time setup that will automatically check your code for all future labs, giving you instant feedback.
  • Please navigate to labs/lab03/README.md for full instructions.