Python Values Return and Recursion :

Function Return Values :

To let a function return a value, use the return statement :

Example :

  1. def my_function(x):
  2. return 5 * x
  3. print(my_function(2))
  4. print(my_function(4))
  5. print(my_function(6))
  6. print(my_function(8))
  7. print("\n python function return example :) ")
  8. input()

Output :

python function values return example

Recursion :

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

Example :

  1. #find factorial number using recursion function
  2. def my_function(n):
  3. if n == 1:
  4. return n
  5. else:
  6. return n*my_function(n-1)
  7. num = int(input("Enter a number: ")) # take input(int type) from the user
  8. if num < 0: # check is the number is negative
  9. print("Sorry, Factorial does not exist for negative numbers.")
  10. elif num == 0:
  11. print("The factorial of 0 is 1")
  12. else:
  13. print("The factorial of",num,"is",my_function(num))
  14. input()

Output :

python recursion function to find a factorial number

Next Update

Loading...

Currently we improved our website User Interface and other contents. Our next update is adding video tutorials on this site so, We create a new YouTube channel, our YouTube channel name is CodeX.

We need some time for make video tutorials (CodeX) so, stay with us and keep supporting and you know already we make a Collaboration with HackIsOn YouTube channel long time ago So, please Subscribe Our Channels