Skip to content

Commit d00265d

Browse files
committed
return vs print, little fixes
1 parent 92f403d commit d00265d

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

defining-functions.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,9 +371,37 @@ None
371371
>>>
372372
```
373373

374+
## Return or print?
375+
376+
There's two ways to output information from functions. They can print
377+
something or they can return something. So, should we print or return?
378+
379+
Most of the time returning makes functions much easier to use. Think
380+
about the `input()` function. It asks the user to enter something, and
381+
then the user enters something and that value is returned. If the input
382+
function would print the value instead of returning it, things like
383+
`name = input("Name: ")` wouldn't work and assigning the output to a
384+
variable would be much more difficult. Printing things is fine when you
385+
know that you'll only need to print the result and you'll never need to
386+
assign it to a variable.
387+
388+
## Summary
389+
390+
- Functions are a way to write code once, and then use that same
391+
code in multiple places.
392+
- Variables inside functions are **locals**, and variables outside
393+
functions are **globals**. Functions can access all variables, but
394+
by default, they can only create and change the value of local
395+
variables.
396+
- Functions can take **arguments** and they can behave differently
397+
depending on what arguments they get. Functions can also
398+
**return** one value. Returning also ends the function immediately.
399+
- Return a value instead of printing it if you need to do something with
400+
it after calling the function.
401+
374402
## Exercises
375403

376-
**There is a lot to learn with functions, and I don't expect you to
404+
**There is a lot to learn about functions, and I don't expect you to
377405
learn everything at once.** However, there's also lots of free Python
378406
exercises about defining functions you can do. Do many of them and
379407
spend a lot of time with them, so you'll get used to defining

0 commit comments

Comments
 (0)