Can someone please explain me about 'def' and 'return' command in details with an example. Thanks in advance.
def is used to define a function with parameters. At the end of the calculations, return will select a value to return as the value of the function, i.e. result of the calculations. Example below to calculate the square of a number: def square(x): x2=x*x; return(x2); # main program k=eval(input("type in x : ")); print("The square of ",k," is ", square(k)); If you have Python (Version 3), you can try it out. If not, you may need to make some modifications to make it work. The definition of a function is useful if you want to calculate results for many different input values.
Thank you @mathmate
You're welcome! :)
Function can return no value (or be "void") or got zero parameters. ---------------------------------- # Python 3 # don't return anything def greet(name): print('Hello', name) # no parameters, no return value def greet_all(): print('Hello, World!') ---------------------------------- Keyword "return" can be also used to control code flow - you can just type "return" and function ends. ---------------------------------- def give_me_positive(value): if value > 0: print('Thanks for', value) else: return
Just be careful. Commands and keywords have two different meanings. When you want to excute a program, you use a command in the command line interface (shell). Ex : >>>python myprogram.py This executes myprogram.py in the shell. Keywords are reserved words in the python syntax. def and return are two examples of it, explained by mathmate and tezaurismosis. def is a keyword which defines a function block in the script. When you want to code a function, then it is mandatory to start with the def keyword. return generally concludes the function code and returns the output of the function to the rest of the program.
Join our real-time social learning platform and learn together with your friends!