Basic Function Definitions

  1. Define a function greet() that receives a string name as a parameter and prints Hi, followed by the value of name. E.g., if name is “Georgia”, it prints Hi, Georgia.

    The function returns nothing.

    A function definition starts with def and then the name of the function. The contents (or “body”) of the function is indented.
  1. Define a function greet() that receives a string name as a parameter and returns Hi, followed by the value of name. (Note: the previous question had the code print the result. Here you should return the result.)

    Build the string and then return it. You can assume that the parameter name is a string. The test cases are:

    greet('Susan')             # returns "Hi, Susan"
    greet('James')             # returns "Hi, James"
    greet('')                  # returns "Hi, "
    
  1. Define a function add() that receives two numbers and returns the sum of the numbers.

    The function prints nothing. It returns the sum of the two values passed in.

    The test cases are:

    add(1, 2)             # returns 3
    add(1.5, 2.0)         # returns 3.5
    add(-1, 1)            # returns 0
    
  1. Define a function add() that receives two numbers and returns the value that is 100 more than the sum of the two numbers.

    The function prints nothing. It returns the sum of the two values passed in.

    The test cases are:

    add(1, 2)             # returns 103
    add(1.5, 2.0)         # returns 103.5
    add(-1, 1)            # returns 100
    
  1. Define a function makeUserId() that receives two parameters – a string name and a number num, and returns a string that is the concatenation of the user name and the number.

    Remember that you can only concatenate two strings – not a string and an integer.

    The test cases are:

    makeUserId('susan', 2)             # returns "susan2"
    makeUserId('erica', 0)             # returns "erica0"
    makeUserId('', -1)                 # returns "-1"
    
  1. Define a function max() that receives two numbers and returns the larger of the two. Use an if-else statement.

    You need an if-else statement in the function.

    The test cases are:

    max(0, 1)             # returns 1
    max(44, -4.0)         # returns 44
    max(7.2, 7.2)         # returns 7.2
    
  1. Define a function makeFilledList() that takes two parameters:

    • length: the number of elements in the list
    • value: the value that should be repeated length times in the list.

    E.g., if the inputs where 3 and 0, the result would be [0, 0, 0]

    The test cases are:

    makeFilledList(4, 1)             # returns [1, 1, 1, 1]
    makeFilledList(0, 4)             # returns [ ]
    makeFilledList(10, "a")          # returns [ "a", "a", "a", "a", "a", "a", "a", "a", "a", "a" ]
    
Next Section - Advanced Function Definitions