Challenge: create your own function defined by inputs and outputs
Functions are going to be really important throughout this course, so I would like to challenge you to create some more as practice. Below are three descriptions of functions, stating what parameters should be accepted and what information should be returned.
Some useful syntax
Throughout the course and other programming you may have done, you will find there is often a need to combine strings together. This is particularly important when it comes to creating output messages using variables. The process of assembling strings is called concatenation and there are a few ways to do it.
Adding strings together
One way to combine strings is to use the + operator to “add” them together, for example:
name = "Ajay"
occupation = "Paleontologist"
print(name + " is a trained " + occupation)
In the code above the variables and string are added together before they are output in the console. The results would look like this:
Ajay is a trained Paleontologist
.format
Another way of combining strings is to use the .format() method to place variables into a string. You have to include placeholders in the string to show where you want the new data to go, this is done with curly brackets ({}). You then add the list of data to be inserted inside of the brackets on the format method. You can see an example below:
name = "Siobhan"
occupation = "Therapist"
print("{} is a trained {}".format(name, occupation))
The curly brackets inside the string will be replaced in the same order that the data is supplied, the first pair will be replaced with the first variable and so on. This code produces the following output:
Siobhan is a trained Therapist
Back to the challenges
Pick at least one of these challenges and create a function with the desired behaviour. Try to use one of the methods of concatenating strings in your solution. Share your code in the discussion and give feedback on each other’s solutions.
Challenge 1
Can you create a function that, when called, displays a nursery rhyme? Give it a sensible name.
Challenge 2
Create a function with one parameter, name, which will be the name of a person. The function should then “sing” Happy Birthday to that person, inserting their name at the correct point. Give your function a sensible name.
Challenge 3
Can you make a function that generates a random password of any length? The function should accept one parameter, the desired password length, and return a password. You may find it useful to import the choice function from the random module.
from random import choice