Skip to content

Commit 774c608

Browse files
committed
add examples and clean up
1 parent 3969559 commit 774c608

File tree

1 file changed

+61
-21
lines changed

1 file changed

+61
-21
lines changed

defining-functions.md

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ Let's use it to define a function that does nothing.
6262
>>>
6363
```
6464

65-
Seems to be working so far, we have a function. Let's see what happens
66-
if we call it.
65+
Seems to be working so far, we have a function. Actually it's just
66+
a value that is assigned to a variable called `do_nothing`. Let's see
67+
what happens if we call it.
6768

6869
```py
6970
>>> do_nothing()
@@ -130,7 +131,7 @@ program, even in functions.
130131
>>>
131132
```
132133

133-
But there are also **local variables**. They exist only inside
134+
But there are also **local variables**. They exist only **inside**
134135
functions, and they are deleted when the function exits.
135136

136137
```py
@@ -150,18 +151,19 @@ NameError: name 'd' is not defined
150151
However, modifying a global variable in-place from a function is easy.
151152

152153
```py
153-
>>> foo = ['global foo']
154-
>>> def bar():
155-
... foo.append('local foo')
154+
>>> stuff = ['global stuff']
155+
>>> def add_stuff():
156+
... stuff.append('local stuff')
156157
...
157-
>>> bar()
158-
>>> foo
159-
['global foo', 'local foo']
158+
>>> add_stuff()
159+
>>> stuff
160+
['global stuff', 'local stuff']
160161
>>>
161162
```
162163

163164
This doesn't work if the value is of an immutable type, like string or
164-
integer. Fortunately, Python will tell you if something's wrong.
165+
integer because immutable values cannot be modified in-place.
166+
Fortunately, Python will tell you if something's wrong.
165167

166168
```py
167169
>>> foo = 1
@@ -376,15 +378,54 @@ None
376378
There's two ways to output information from functions. They can print
377379
something or they can return something. So, should we print or return?
378380

379-
Most of the time returning makes functions much easier to use. Think
381+
Most of the time **returning makes functions much easier to use**. Think
380382
about the `input()` function. It asks the user to enter something, and
381383
then the user enters something and that value is returned. If the input
382384
function would print the value instead of returning it, things like
383-
`name = input("Name: ")` wouldn't work and assigning the output to a
385+
`name = input("Name: ")` wouldn't work and assigning the result to a
384386
variable would be much more difficult. Printing things is fine when you
385387
know that you'll only need to print the result and you'll never need to
386388
assign it to a variable.
387389

390+
## Examples
391+
392+
Ask yes/no questions.
393+
394+
```py
395+
def ask_yes_no(prompt):
396+
while True:
397+
answer = input(prompt + ' (y or n) ')
398+
if answer == 'y' or answer == 'Y':
399+
return True # returning ends the function
400+
if answer == 'n' or answer == 'N':
401+
return False
402+
print("Answer 'y' or 'n'.")
403+
404+
if ask_yes_no("Do you like ice cream?"):
405+
print("You like ice cream!")
406+
else:
407+
print("You don't like ice cream.")
408+
```
409+
410+
Ask questions with multiple answers.
411+
412+
```py
413+
def ask_until_correct(prompt, correct_options,
414+
error_message="I don't know what you meant."):
415+
while True:
416+
answer = input(prompt + ' ')
417+
if answer in correct_options:
418+
return answer # returning ends the function
419+
print(error_message)
420+
421+
422+
colors = ['red', 'yellow', 'blue', 'green', 'orange', 'pink', 'black',
423+
'gray', 'white', 'brown']
424+
choice = ask_until_correct("What's your favorite color?", colors,
425+
error_message="I don't know that color.")
426+
print("Your favorite color is %s!" % choice)
427+
```
428+
388429
## Summary
389430

390431
- Functions are a way to write code once, and then use that same
@@ -394,9 +435,10 @@ assign it to a variable.
394435
by default, they can only create and change the value of local
395436
variables.
396437
- Functions can take **arguments** and they can behave differently
397-
depending on what arguments they get. Functions can also
398-
**return** one value, like the built-in input function does.
399-
Returning also ends the function immediately.
438+
depending on what arguments they get. Arguments are just local
439+
variables.
440+
- Functions can also **return** one value, like the built-in input
441+
function does. Returning also ends the function immediately.
400442
- Return a value instead of printing it if you need to do something with
401443
it after calling the function.
402444

@@ -405,8 +447,7 @@ assign it to a variable.
405447
**There is a lot to learn about functions, and I don't expect you to
406448
learn everything at once.** However, there's also lots of free Python
407449
exercises about defining functions you can do. Do many of them and
408-
spend a lot of time with them, so you'll get used to defining
409-
functions.
450+
spend time with them until you're familiar with defining functions.
410451

411452
1. Python comes with many built-in functions. Some of the simplest ones
412453
are abs, all and any. They can be used like this:
@@ -421,8 +462,8 @@ functions.
421462
>>>
422463
```
423464

424-
- any returns True if any of the elements of a list is true, and
425-
False otherwise.
465+
- any returns True if one or more of the elements of a list is true,
466+
and False otherwise.
426467

427468
```py
428469
>>> any([True, False, True])
@@ -466,8 +507,7 @@ functions.
466507
and all the exercises because you didn't know how to define
467508
functions. Read those parts now, and do the exercises.
468509

469-
4. Use a search engine (e.g. Google) to find more exercises about
470-
defining functions.
510+
4. Find more exercises about defining functions online.
471511

472512
Answers for the first and second exercise are [here](answers.md).
473513

0 commit comments

Comments
 (0)