We studied a new concept called function. what is a function? answer: “A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result” . we can create function for various purposes: avoid the duplication of code, expose a certain ability , etc. we already used functions in python, such as: len, count etc – but now it’s time to create functions ourselves. to create a function in python we use the def key word and name the function regarding to its purpose (for example a function which adds two numbers should be named Add, etc). a function could accept parameters (for example a function which calculates the area of a circle should accept a parameter stating the radius). we could assign a default value to the function parameter which will be used whenever this parameter will not be sent by the caller. of course, default parameters should be aligned to the right. we saw that a function could return a value using the return key word. why should we need a return value? answer: for example if a function calculates the sum of two numbers- we would be interested to know what was the sum that our function has calculated. usually, we store the returned value of a function in a memory cell, or print it to the screen. we saw how to generate random numbers
More topics covered:
- Function syntax: def <function-name> ( parameters )
- Function name should be legal , i.e. not starting with a number
- Function return value could be ignored
- None in python means empty
- If a function does not have a return value, the return value is None
- You cannot define the same function name more than once with different set of parameters
- Calling function with parameter name, i.e. MySum (a = 5, b = 8)
- random.randint
- import key word
Links:
