Creating Functions: def and Parameters
A function is a named piece of code that can be called many times. We create our own functions with def and pass data to them through parameters.
All topics (8 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
We have already used ready-made functions such as print(), len() and input(). A function is a named piece of code that is called when needed. Instead of repeating the same code in several places, we move it into a function and call it by name, which makes the program shorter and errors easier to find.
A function is declared with the keyword def: after the line def hello(): the body is written indented by 4 spaces, for example print("Salom!"). Declaring a function does not run it; it executes only when we call it: hello(). The call must come after the declaration.
Data is passed to a function through parameters: def greet(name): and print("Salom,", name). The value given in the call is called an argument: greet("Dilnoza"). Several parameters are separated by commas: def area(a, b):. A parameter may have a default value: with def greet(name="do‘st"): the call greet() prints “Salom, do‘st”.
Variables created inside a function are local: they are visible only within that function and disappear when it ends. Global variables created outside a function can be read inside. Give functions meaningful names (print_table, area) and let each one do one clear job.
Key takeaways
- A function is declared with
defand called by its name. - A parameter is the name in the declaration; an argument is the value in the call.
- A parameter can have a default value.
- Variables inside a function are local.
Practice tasks
- Write a function
star_line(n)that printsnasterisks ("*" * n); call it with three different arguments. - Let
def rectangle(a, b):print the area of a rectangle; call it twice with different numbers. - Create a function
greet(name, city="Toshkent")and call it once with one argument and once with two.
Review questions
Test yourself: think first, then reveal the answer.
1What is the difference between declaring and calling a function?Show answerHide answer
A declaration (`def`) creates the function but does not run it; the code runs only when the function is called by name with parentheses.2What is a local variable?Show answerHide answer
A variable created inside a function that is visible only in that function.
0 of 11 topics completed
Sign in to mark