269 | | Run this one. What does it output? A lovely happy birthday song for two kids? Imagine if you had to write a program to sing happy birthday to all the people in your class without it. It'd get pretty ugly, fast. |
270 | | |
271 | | `def` is used to indicate a custom function, and you have to define (that's what def is short for) it in your program before you use it. It takes an argument of an age, and a list of names. The "singHappyBirthday" line actually ''calls'' the custom function, with arguments of an age of size and a list of two names. |
272 | | |
273 | | |
274 | | Now what happens if you try and run it with age equal to 1? That's not right. Modify the program so it behaves correctly if an age of 1 is used. |
275 | | |
276 | | |
277 | | Now your turn... In the 'That's-a big number exercise above" make a function called inputNumber, and modify it to use that instead of the while-not stuff. Much easier to read, no? |
278 | | |
| 269 | Run this one. What does it output? A lovely happy birthday song for two kids? Now imagine if you had to write a program to print out a happy birthday for every single person in your grade without it. It'd get pretty ugly, fast. |
| 270 | |
| 271 | `def` is used in Python to indicate a custom function, and you have to ''def''ine it in your program before you use it. It takes an argument of an age, and second argument of a list of names. The "singHappyBirthday" line actually ''calls'' the custom function, with the two arguments it needs. |
| 272 | |
| 273 | A function can return a value, by using the Python keyword `return` as in: |
| 274 | |
| 275 | {{{ |
| 276 | def isOver9000(power): |
| 277 | if power>9000: # you could also express this if-then-else statement as "return power>9000" |
| 278 | return True |
| 279 | else: |
| 280 | return False |
| 281 | |
| 282 | isGokuPowerfulEnough = isOver9000(9001) |
| 283 | print(isGokuPowerfulEnough) |
| 284 | }}} |
| 285 | |
| 286 | Now your turn... In the 'That's-a big number exercise above" make a function called inputNumber, and modify it to use a custom function rather than the while-not stuff. Much easier to read, no? |
| 287 | |
| 288 | Here's the [[ThatsaBigNumberSolution|solution]] |