Rekursive Fakultätsberechnung in Python

PythonPythonBeginner
Jetzt üben

This tutorial is from open-source community. Access the source code

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Einführung

In der Mathematik ist das Fakultät einer nicht-negativen ganzen Zahl n, bezeichnet mit n!, das Produkt aller positiven ganzen Zahlen kleiner oder gleich n. Beispielsweise ist 5! = 5 x 4 x 3 x 2 x 1 = 120. In dieser Herausforderung werden Sie eine Python-Funktion schreiben, um das Fakultät einer gegebenen Zahl mithilfe der Rekursion zu berechnen.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") subgraph Lab Skills python/comments -.-> lab-13628{{"Rekursive Fakultätsberechnung in Python"}} python/conditional_statements -.-> lab-13628{{"Rekursive Fakultätsberechnung in Python"}} python/function_definition -.-> lab-13628{{"Rekursive Fakultätsberechnung in Python"}} python/raising_exceptions -.-> lab-13628{{"Rekursive Fakultätsberechnung in Python"}} end

Fakultät

Schreiben Sie eine Funktion factorial(num), die eine nicht-negative ganze Zahl num als Argument nimmt und deren Fakultät zurückgibt. Die Funktion sollte die Fakultät mithilfe der Rekursion berechnen. Wenn num kleiner oder gleich 1 ist, geben Sie 1 zurück. Andernfalls geben Sie das Produkt von num und der Fakultät von num - 1 zurück. Die Funktion sollte eine Ausnahme werfen, wenn num eine negative oder eine Gleitkommazahl ist.

def factorial(num):
  if not ((num >= 0) and (num % 1 == 0)):
    raise Exception("Number can't be floating point or negative.")
  return 1 if num == 0 else num * factorial(num - 1)
factorial(6) ## 720

Zusammenfassung

In dieser Herausforderung haben Sie gelernt, wie man die Fakultät einer Zahl mithilfe der Rekursion berechnet. Sie haben auch gelernt, wie man in Python Ausnahmen behandelt.