Conditionals
# simple if statement
def abs(n):
if (n < 0):
n = -n
return n
# again, with same-line indenting
def abs(n):
if (n < 0): n = -n # only indent this way for very short lines (if at all)
return n
# again, with multiple return statements
def abs(n):
if (n < 0):
return -n
return n
# aside: you can do this with boolean arithmetic, but don't!
def abs(n):
return (n < 0)*(-n) + (n>=0)*(n) # this is awful!
# simple if-else statement
def abs(n):
if (n >= 0):
return n
else:
return -n
# or, if you prefer...
def abs(n):
if (n >= 0):
sign = +1
else:
sign = -1
return sign * n
# simple if-else expression (not a conditional statement!)
def abs(n):
return n if (n >= 0) else -n
# simple if-elif-else statement
def numberOfQuadraticRoots(a, b, c):
d = b**2 - 4*a*c
if (d > 0):
return 2
elif (d == 0):
return 1
else:
return 0
# another example
def getGrade(score):
if (score >= 90):
grade = "A"
elif (score >= 80):
grade = "B"
elif (score >= 70):
grade = "C"
elif (score >= 60):
grade = "D"
else:
grade = "F"
return grade
# another if-else example
def round(d):
sign = 1 if (d >= 0) else -1
d = abs(d)
if (d % 1 < 0.5):
return sign * int(d)
else:
return sign * (int(d) + 1)
# and another way to do the same thing
def round(d):
sign = 1 if (d >= 0) else -1
d = abs(d)
offset = 0 if (d % 1 < 0.5) else 1
return sign * (int(d) + offset)
# and a reasonably clear way, without any conditionals or boolean arithmetic!
import math
def round(d):
sign = int(math.copysign(1, d)) # +1 for positive, -1 for negative
d = abs(d)
offset = int(d%1 + 0.5)
return sign * (int(d) + offset)