W tym programie nauczysz się znajdować sumę liczb naturalnych za pomocą funkcji rekurencyjnej.
Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania w Pythonie:
- Python if… else Instrukcja
- Funkcje Pythona
- Rekursja w Pythonie
W poniższym programie użyliśmy funkcji rekurencyjnej recur_sum()
do obliczenia sumy podanej liczby.
Kod źródłowy
# Python program to find the sum of natural using recursive function def recur_sum(n): if n <= 1: return n else: return n + recur_sum(n-1) # change this value for a different result num = 16 if num < 0: print("Enter a positive number") else: print("The sum is",recur_sum(num))
Wynik
Suma wynosi 136
Uwaga: Aby przetestować program pod kątem innego numeru, zmień wartość num
.