Python Functions

Writing a function

  • Start with def followed by the name of the function
  • Add parameters inside the parentheses in the function definition
  • Return a value
def double(n):
  result = n * 2
  return result

def main():
  print( double(5) )

main()
10

Using round()

Use the round() function to get a floating-point number rounded to the specified number of decimals.

Syntax:

round(number, ndigits*)

The number of digits (ndigits) is optional, but we will often round number to two decimals:

round(392.68750000000006)
393
round(392.68750000000006, 2)
392.69

Using format()

age = 20
name = 'Philip'

Here’s how we can do concatenation using the + operator:

name + ' is ' + str(age) + ' years old'
'Philip is 20 years old'

We can do the same with the .format() method, using {} as place holders for our variables:

'{} is {} years old'.format(name, age)
'Philip is 20 years old'

If statements

We can use logical expressions in if statements to return different things from a function:

def is_positive(number):
  if number > 0:
    return "Number is positive"
  if number < 0:
    return "Number is negative"
  return "Number is zero"

def main():
  print( is_positive(10) )
  print( is_positive(0) )
  print( is_positive(-10) )
  
main()
Number is positive
Number is zero
Number is negative

Short Project

Instructions for Short Project of the Week