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 called absolute that takes one numeric argument (integer or float) n and returns the absolute value of n: if n is positive, it results n, if n is negative, it returns n * -1

Test cases:

assert absolute(4) == 4
assert absolute(-4) == 4
assert absolute(0) == 0

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

Solution 1

def absolute(n):
  if n < 0:
    return n * -1
  return n

if __name__ == "__main__":
  assert absolute(4) == 4
  assert absolute(-4) == 4
  assert absolute(0) == 0
  print("Passed all tests")

Solution 2

def absolute(n):
    if n >= 0:
        return n
    else:
        return n * -1

import statements

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

import random

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

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__)