Functions & Logic

← All samples

functions-logic.dply
1---
2version: 0.1.0
3precision: 4
4---
5# draftply Pro — Functions & Logic
6# (Open in draftply; Pro features are marked in the free version.)
7
8# One-line function definition
9f(x) = x^2 + 2*x + 1
10f(5)
11
12# Multi-line definition with an optional parameter
13def power(base, exp = 2):
14 return base ^ exp
15power(3)
16power(2, 10)
17
18# Recursion — factorial
19def fact(n):
20 if n <= 1:
21 return 1
22 return n * fact(n - 1)
23fact(6)
24
25# Loops — accumulate a sum
26total = 0
27for i in 1..100:
28 total = total + i
29total
30
31# Conditional logic in a function
32def sign_of(x):
33 if x > 0:
34 return 1
35 if x < 0:
36 return -1
37 return 0
38sign_of(-42)
39
40# Lists & ranges
41range(1, 11)
42sort([5, 2, 9, 1, 7])
43