[ Jocelyn Ireson-Paine's Home Page | Python notes and links ]

Some Python Functions

These are some simple Python functions I wrote or adapted for The Oxford Institute. The file as a .py is here.

# pyfuncs.py


import math
#
# For 'sqrt' in 'area'.


# Greet someone by displaying "Hello ", their name,
# and an exclamation mark.
def greet( name ):
  print( "Hello " + name + "!" )


# As 'greet', but builds the complete message
# in a variable and then displays that.
#
def greet2( name ):
  message = "Hello " + name + "!"
  print( message )


# Returns the largest of three numbers.
#
def largest( num1, num2, num3 ):

  # Adapted from 
  # https://www.programiz.com/python-programming/examples/largest-number-three .

  if ( num1 >= num2 ) and ( num1 >= num3 ):
    largest = num1 
  elif ( num2 >= num1 ) and ( num2 >= num3 ):
    largest = num2 
  else:
    largest = num3
  return largest


# Returns the area of the triangle with the
# specified three sides.
#
def area( a, b, c ):

  # Adapted from 
  # https://www.programiz.com/python-programming/examples/area-triangle .
  # This calculates the area using Heron's formula,
  # explained in 
  # https://en.wikipedia.org/wiki/Heron%27s_formula .

  s = (a + b + c) / 2.0
  # Calculates the semi-perimeter. 
  # I've written 2.0 rather than 2, because otherwise
  # Python 2 will return an integer, giving the wrong
  # answer. 
  # See https://stackoverflow.com/questions/2958684/python-division .

  area = math.sqrt( s * (s-a) * (s-b) * (s-c) )  
  # Calculates the area.

  return area


# Given a number of days, returns a list containing
# the number of complete weeks, and the number of
# days left over.
#
def days_to_weeks( ndays ):
  nweeks = ndays // 7
  ndays_left = ndays % 7
  return [ nweeks, ndays_left ]


# Given a list of numbers, plots it as a graph 
# sideways on the console. Each number y is
# plotted as (y-1) spaces followed by a star.
# So for this to work well, the numbers need
# to fit within the console linewidth. They
# must also be integers.
# 
def plot( ys ):

  # Adapted from j08lue's answer to
  # https://stackoverflow.com/questions/20295646/python-ascii-plots-in-terminal .

  for y in ys:
    line = ' '*(y-1) + '*' 
    print line


# Tries 'plot' with some sample data. According to
# the above link, this is basically ( sin(x)+1 )*20 .
#
def try_plot():
  ys = [20, 26, 32, 37, 39, 40, 38, 35, 30, 23, 17, 
        10,  5,  2,  0,  1,  3,  8, 14, 20]
  plot( ys )


def count_words( filename ):

  # Adapted from 
  # http://pythonforengineers.com/create-a-word-counter-in-python/ .

  f = open( filename, "r" )
  data = f.read()
  f.close()
  #
  # Read the text from the specified file.
  
  words = data.split( ' ' )
  #
  # Split the data on spaces, giving a list.
  # The list isn't quite words, since some elements
  # will contain newlines as well. That doesn't
  # matter for this demo.

  count = len( words )
  #
  # Get its length.

  return count