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. Key takeaways: - def defines a function; parentheses call it. - A parameter receives the argument you pass in. - return sends a value back to the caller. - Returning is not the same as print
Challenge: Square Function