Python 5
Python 5
5.1 Function
A function is a group of statements that are used for later execution on a specific task.
The name of a function tells us what the group of statements is going to accomplish.
Thus, users only need to memorize the name of the function, but not the whole group of
statements.
The main reason for using functions is that it saves the programmer’s time in repeatedly
writing the same group of statements.
Programmers can then concentrate on constructing high-level building blocks.
Another reason is that it is easier to check the error in a program if the whole program is
divided into different sub-parts.
5.6 Exercises
1. You receive a secret code “.gnitseretni si esruoc ehT” from Edwin. Design a function to decrypt
this message and name the function as decrypt.
2. Design a function to encrypt a message based on the logic of the above secret code. If you want
to send “Yes, it is interesting.”, what would be the encrypted message that you send back to
Edwin? Hints: would your answer the same as the previous one?
3. Without defining x outside the body of a function, design a function that assigns a value of 5 to x,
using the global keyword.
4. Design a program to ask users to input their gender (M for male and F for female). Design a
function to raise RuntimeError if their input is not valid.
End of Module 5