Procedures: Parameters and Return

Part of: Programming Lab: Python for CSP

Naming a Chunk of Work. A procedure , which Python calls a function , is a named block of code you can run whenever you need it. You define it with def, and you run it by calling its name with parentheses. Defining greet does not run it. The two calls below do, so this prints hello twice. Writing the steps once and calling them many times keeps code short and clear. Parameters Pass Data In. A parameter is a variable listed in the definition that receives a value when you call the function. The value you pass in is an argument . When you call square(5), the argument 5 lands in the parameter n. The return statement sends a value back to whoever called the function, so square(5) becomes 25, which is stored in result. Return Versus Print. These are different. print shows a value on screen. return hands a value back to the caller so the program can use it further. A function that returns a value lets you combine results, like square(3) + square(4). A function that only prints cannot be reused that way. What usually goes wrong. What you see What caused it How to fix it --- --- --- The output is None The function reached its end without an explicit return, so the caller got nothing back R

Challenge: Square Function