More Python

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Python boolean expressions

Python has the same set of boolean operators you’re used to

Exceptions:

  • logical operators &&, ||, ! use the words and, or, not
  • comparison chaining is allowed.
    • a < b < c is run as a < b and b < c

    • you can do some weird stuff with this:

      a == b < c > d != q

      a == b and b < c and c > d and d != q

Python control flow

  • conditionals (if statements)
  • loops

if statements

if num_cuts > 4:
  print("That's a lot of cuts. Don't do it!")
  • whitespace denotes code blocks
  • don’t miss the colon which marks the beginning of a block
  • whitespace characters must match exactly - careful with spaces and tabs

if, elif and else statements

if num_cuts > 4:
  print("That's a lot of cuts. Don't do it!")
elif num_cuts == 0:
  print("Purrfectly safe")
else:
  print("your risk")
  • multiple conditions can be checked with if .. elif .. else
  • elif not “else if”

Exercise

Write a Python function named classify_triangle in a file called triangle.py.

What it does: Given the lengths of three sides, decide what kind of triangle they form (if any). Parameters (in this order):

  1. a: integer (length of the first side)
  2. b: integer (length of the second side)
  3. c: integer (length of the third side)

Returns: a string — one of “invalid”, “equilateral”, “isosceles”, or “scalene”.

Exercise

  1. Return “invalid” if any side is zero or negative.
  2. Return “invalid” if the sides can’t form a triangle. Three lengths form a triangle only when each pair of sides adds up to more than the remaining side (e.g. a + b must be greater than c).
  3. Otherwise, classify it:
    • “equilateral” — all three sides are equal
    • “isosceles” — exactly two sides are equal
    • “scalene” — no two sides are equal

Exercise

Test cases:

assert classify_triangle(5, 5, 5) == "equilateral"
assert classify_triangle(5, 5, 8) == "isosceles"
assert classify_triangle(3, 4, 5) == "scalene"
assert classify_triangle(1, 2, 10) == "invalid"  # 1 + 2 is not more than 10
assert classify_triangle(1, 2, 3) == "invalid"   # 1 + 2 is not MORE than 3
assert classify_triangle(4, 0, 4) == "invalid"   # zero-length side
assert classify_triangle(-1, 5, 5) == "invalid"  # negative side

Submit your solution (name your file triangle.py) to gradescope

Solution 1

def classify_triangle(a, b, c):
    # return "invalid" if any side is zero or negative.
    if a <= 0 or b <= 0 or c <= 0:
        return "invalid"

    # return "invalid" if the sides can't form a triangle. 
    if a + b <= c or a + c <= b or b + c <= a:
        return "invalid"

    # "equilateral" — all three sides are equal
    if a == b == c:
        return "equilateral"
 
    # "isosceles" — exactly two sides are equal
    if (a == b and b != c) or (a == c and b != a) or (c == b and c != a):
        return "isosceles"

    return "scalene"

Solution 2

def classify_triangle(a, b, c):
    # return "invalid" if any side is zero or negative.
    if a <= 0 or b <= 0 or c <= 0:
        return "invalid"

    # return "invalid" if the sides can't form a triangle.
    if a + b <= c or a + c <= b or b + c <= a:
        return "invalid"

    # "equilateral" — all three sides are equal
    if a == b and b == c:
        return "equilateral"
    # "isosceles" — exactly two sides are equal
    elif a == b or b == c or a == c:
        return "isosceles"
    else:
        return "scalene"

Type Hints (type annotations)

  • Optional syntax used to state the expected data types of variables, function arguments, and return values.
  • Remember that Python is a dynamically-typed language and so it does not enforce type annotations at runtime.
  • Type hints are used by external tools (IDEs, linters, etc) and also for documenting code.
def classify_triangle(a: int, b: int, c: int) -> str: 

import statements

You can import a module that already exists in base python:

import random

print(random.randint(1,128))
98

Or create a .py file and import that (overwrites the standard library if you create a .py file with its name)

Solution of circle area with math.pi

import math

def circle_area(r):
    '''
    Given a radius r, this function calculates and returns the area of that circle
    Arguments:
        r (integer or float) -- radius of the circle
    Returns:
        And float (rounded at two decimals) representing the area of the circle of radius r
    '''
    area = math.pi * r**2
    # return rounded area at two decimals
    return round(area, 2)

if __name__ == "__main__":
    assert circle_area(1) == 3.14
    assert circle_area(2) == 12.57 
    assert circle_area(3) == 28.27
    assert circle_area(4) == 50.27
    assert circle_area(15) == 706.86

    print("Passed all tests")
Passed all tests

Prompt for generative AI: Give me a list of circle radii and their corresponding area rounded to two decimals

Writing code for future importing

# Useful and general functions and variable definitions
if __name__ == " __main__ ":
  # This file has been run directly
  # interact with the user , call functions , etc.

Importing your own modules

test.py

def square_root(n):
  '''Given an integer argument n, it returns square root of n'''
  return n ** 0.5

import_test.py

import test

if __name__ == "__main__":
  # print out to standard output the doc string for the square_root function
  print(test.square_root.__doc__)