Recursive functions in Python

Source: Internet
Author: User

In Python, a function can call other functions, and if the function calls itself, the function is called a recursive function.

1. Using recursive function to calculate factorial

The simplest example of recursive functions is the calculation of factorial.

Factorial: The formula for the general term is n! = n * (n-1)!, for example: 4! = 4 * 3 * 2 * 1

def func (N):
if n = = 1:
return n
return n * func (n-1)

Print (func (4))

Results: 24

The Fibonacci sequence is implemented using recursive functions.

Fibonacci sequence: Refers to a sequence of 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987 ... This sequence starts with the 3rd item and each item is equal to the sum of the first two items.

The Fibonacci sequence of Nature

def Fibo (n):
if n = = 1:
return n
return Fibo (n-1) + Fibo (n-2)

For I in range (20):
Print (Fibo (i))

Results:
1
1
2
3
5
8
13
21st
34
55
89
144
233
377
610
987
1597
2584
4181

Recursive functions in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.