Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added Python factorial calculating snippet #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
SamratBarai wants to merge 9 commits into quicksnip-dev:main from SamratBarai:main
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added error handling for invalid inputs
  • Loading branch information
SamratBarai committed Jan 8, 2025
commit 75ecb1b8a6081ea97255ffdc49378fa6a5a06a11
8 changes: 5 additions & 3 deletions snippets/python/math-and-numbers/calculate-factiorial.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ tags: python,math,factorial,recursive-function

```py
def factorial(n):
if n == 0 or n == 1: return 1
if type(n) != int or n < 0: raise TypeError("Invalid type of input: '" + str(n) + "'") # Raises an error for invalid input
if n == 0 or n == 1: return 1 # Returns 1 if n is 0 or 1
else: return n * factorial(n-1) # Recall the factorial function

# Usage:
print(factorial(5)) # Returns 24
print(factorial(10)) # Returns 3628800
print(factorial(4)) # Returns 24
print(factorial(-4)) # Returns type error for invalid inputs
Copy link
Collaborator

@Mathys-Gasnier Mathys-Gasnier Jan 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO I don't think it's needed to showcase the errors

print(factorial("q")) # Returns type error for invalid inputs
```
10 changes: 10 additions & 0 deletions snippets/python/math-and-numbers/test.py
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import math

def factorial(n):
if type(n) != int or n < 0: raise TypeError("Invalid type of input: '" + str(n) + "'") # Raises an error for invalid input
if n == 0 or n == 1: return 1 # Returns 1 if n is 0 or 1
else: return n * factorial(n-1) # Recall the factorial function

# Usage:
print(factorial(4)) # Returns 24
print(factorial(-4)) # Returns a type error

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /