Defining and calling
def greet(name): print("Namaskar,", name) greet("Riya") greet("Arjun")
Write Python. Understand every error.
Python basics · topic 14 of 25
A function is a named block of code that you can run whenever you need it. You define it with def, give it parameters in brackets, and send a result back with return.
def square(n): return n * n print(square(7)) # 49
Defining a function does not run it. The code inside runs only when you call it, as in square(7).
return and print are different. print shows a value on the screen; return hands the value back to the caller, who can store it or use it in a calculation. A function without return gives back None.
Parameters can have default values, used when the caller leaves them out: def greet(name, greeting="Hello"):.
def name(parameters): then an indented bodyreturn value sends a result backdef name(parameters): starts a function, and the indented lines below are what it runs.return sends a result back. A function without return gives back None.print where return is needed, so the result cannot be used again.
def greet(name): print("Namaskar,", name) greet("Riya") greet("Arjun")
def area(length, width): return length * width room = area(4, 5) print(room) print(area(2, 3) + area(1, 1))
def add_print(a, b): print(a + b) def add_return(a, b): return a + b x = add_print(2, 3) y = add_return(2, 3) print("x is", x) print("y is", y)
def power(base, exp=2): return base ** exp print(power(5)) print(power(2, 10))
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
def add(a, b): return a + b print(add(2, 3) * 2)
add(2, 3) returns 5, which is then multiplied by 2.
def greet(name="friend"): return "Hi " + name print(greet())
With no argument, the default value "friend" is used.
def f(x): print(x * 2) result = f(4) print(result)
f prints 8 but has no return, so it returns None.
x = 5 def change(): x = 10 change() print(x)
The x inside the function is a separate local variable. The global x stays 5.
return statement?Every function returns something. Without return, it is None.