Hacking Secret Ciphers with Python

(Ann) #1
Chapter 4 – Strings and Writing Programs 51

Functions....................................................................................................................................................................


A function is kind of like a mini-program inside your program. It contains lines of code that are
executed from top to bottom. Python provides some built-in functions that we can use (you’ve
already used the print() function). The great thing about functions is that we only need to
know what the function does, but not how it does it. (You need to know that the print()
function displays text on the screen, but you don’t need to know how it does this.)


A function call is a piece of code that tells our program to run the code inside a function. For
example, your program can call the print() function whenever you want to display a string on
the screen. The print() function takes the value you type in between the parentheses as input
and displays the text on the screen. Because we want to display Hello world! on the screen,
we type the print function name, followed by an opening parenthesis, followed by the 'Hello
world!' string and a closing parenthesis.


The print() function


hello.py


  1. print('Hello world!')

  2. print('What is your name?')


This line is a call to the print() function (with the string to be printed going inside the
parentheses). We add parentheses to the end of function names to make it clear that we’re
referring to a function named print(), not a variable named print. The parentheses at the
end of the function let us know we are talking about a function, much like the quotes around the
number '42' tell us that we are talking about the string '42' and not the integer 42.


Line 3 is another print() function call. This time, the program displays “What is your name?”


The input() function


hello.py


  1. myName = input()


Line 4 has an assignment statement with a variable (myName) and a function call (input()).
When input() is called, the program waits for the user to type in some text and press Enter.
The text string that the user types in (their name) becomes the string value that is stored in
myName.


Like expressions, function calls evaluate to a single value. The value that the function call
evaluates to is called the return value. (In fact, we can also use the word “returns” to mean the

Free download pdf