Python can also be used for functional programming as it can for structural programming. This can be done by defining the function which can be done with or without an argument.
The code inside the function won't be run unless called by the user.
An example of a basic code is this.
Functions can take in one or more arguments depending on the programmer's need. Functions are widely used in python because of their ability to be called upon anywhere in the program whenever a syntax is needed to be repeated twice or more times, which is generally better than typing the same line of code and pasting it when needed over and over which creates repetition and a rigid program.
In functional programming, there is also a return function that passes out the result of the operation performed without being printed or seen by the user, the output of the function can then be taken as the input of another function.
Here's a simple function that adds two numbers and doubles them:
Just like structural programming which uses iterations to run over a code multiple times, functional programming involves the use of iterations which involve calling the function inside the function and it will keep running until a base case is reached and the result is displayed.
There's a simple example of recursions.
The use of factorial (factorial is a product of a number by the number -1 until 1 is reached, I.e 3! = 3×2×1,5!=5×4×3×2×1)
Let me break down how I solved this
Step1:First we need an input function which will be the length of the array
Step2: I created a list comprehension to take in values entered by the user on a single line
list=[int(x) for x in input("Enter numbers:").split()]
To explain further the list comprehension as written takes in only integers, for x in the input of the user, the .split() function collects each input removes the spaces, and collects it as an integer
Here's how it works
Step3: I created negative positive and zero as integers which equal to zero, then created a loop to go over each of the numbers entered and group them whether they are greater than 1 equal to 0, or less than 1.
Finally; I created a function to make them all fractions by dividing the argument of the function by the length of the list and printing out the answer.
How did you solve yours, feel free to drop it in the comment below😇thanks for reading, share, and have a lovely day. We'll see more on recursions next lesson.