Skip to content

Introduction to Python — Session 7

In this session we cover:

  • What are functions and why we use them
  • Creating your own functions
  • DRY Principle
  • Calling functions
  • Parameters
  • Returning values from Functions
  • Recursion

Write your code

Questions

Section A

  1. Write a function that prints your name
  2. Write a function that accepts a name as a parameter and prints "Hello, name"
  3. Loop through the list ["Alice", "Bob", "Charlie"] and call the function you just wrote
  4. Write a function that prints the area of two passed in parameters
  5. Write a function called 'print_list' that accepts a list as a parameter and then prints out each item of the list
  6. Put the following into a function that accepts age as a parameter:
    1. If they are younger than 11, print "You're too young to go to this school"
    2. If they are between 11 and 16, print "You can can come to this school"
    3. If they are over 16, print 'You're too old for school"
    4. If they are 0, print "You're not born yet!"

Section B

  1. Write a function called is_odd that will return True or False if the integer passed as a parameter is odd (hint: x % 2 will return true for all odd numbers)
  2. Write a function that accepts a word and returns it backwards, e.g. 'hello' to 'olleh'
  3. Write a recursive function that accepts a number and prints that number of stars, followed by ever decreasing stars on each line, E.g:
*****
****
***
**
*
  1. Create a padlock function. You need to be able to pass in a passcode and if its correct it should return "Unlock", else "Locked"
  2. Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20
  3. Write a function called is_prime() that accepts a number and return True or False if the number of prime or not
  4. Write a function that checks to see if a string is a palindrome, if it is, it will return True and False if it is not.
  5. Write a function that checks to see if a sentence is a palindrome, if it is, it will return True and False if it is not. Tip - you may want to format your sentence so it is all lower case, and .replace() to get rid of white spaces.

Answers

See the code for each answer on our GitHub!