deff(x):
print("A", end="")
if x == 0:
print("B", end="")
print("C", end="")
print("D")
f(0)
f(1)
A more interesting example:
# These examples define abs(n), which is a nice example here, but it is# also a builtin function, so you do not need to define it to use it.defabs1(n):if n < 0:
n = -n
return n
# again, with same-line indentingdefabs2(n):if n < 0: n = -n # don't indent this way unless there is a specific reasonreturn n
# again, with multiple return statementsdefabs3(n):if n < 0:
return -n
return n
# aside: you can do this with boolean arithmetic, but don't!defabs4(n):return (n < 0)*(-n) + (n>=0)*(n) # this is awful!# now show that they all work properly:
print("abs1(5) =", abs1(5), "and abs1(-5) =", abs1(-5))
print("abs2(5) =", abs2(5), "and abs2(-5) =", abs2(-5))
print("abs3(5) =", abs3(5), "and abs3(-5) =", abs3(-5))
print("abs4(5) =", abs4(5), "and abs4(-5) =", abs4(-5))
if-else statement
deff(x):
print("A", end="")
if x == 0:
print("B", end="")
print("C", end="")
else:
print("D", end="")
if x == 1:
print("E", end="")
else:
print("F", end="")
print("G")
f(0)
f(1)
f(2)
Revisiting abs(n):
defabs5(n):if n >= 0:
return n
else:
return -n
# or, if you prefer...defabs6(n):if n >= 0:
sign = +1else:
sign = -1return sign * n
print("abs5(5) =", abs5(5), "and abs5(-5) =", abs5(-5))
print("abs6(5) =", abs6(5), "and abs6(-5) =", abs6(-5))
if-elif-else statement
deff(x):
print("A", end="")
if x == 0:
print("B", end="")
print("C", end="")
elif x == 1:
print("D", end="")
else:
print("E", end="")
if x == 2:
print("F", end="")
else:
print("G", end="")
print("H")
f(0)
f(1)
f(2)
f(3)
A more interesting example:
defnumberOfRoots(a, b, c):# Returns number of roots (zeros) of y = a*x**2 + b*x + c
d = b**2 - 4*a*c
if d > 0:
return2elif d == 0:
return1else:
return0
print("y = 4*x**2 + 5*x + 1 has", numberOfRoots(4,5,1), "root(s).")
print("y = 4*x**2 + 4*x + 1 has", numberOfRoots(4,4,1), "root(s).")
print("y = 4*x**2 + 3*x + 1 has", numberOfRoots(4,3,1), "root(s).")
# Can lead to bugs:
b = Trueif b:
print('yes')
ifnot b:
print('no')
# Better:
b = Trueif b:
print('yes')
else:
print('no')
Another example:
# Messy and can lead to bugs:
x = 10if x < 5:
print('small')
if (x >= 5) and (x < 10):
print('medium')
if (x >= 10) and (x < 15):
print('large')
if x >= 15:
print('extra large')
# Better:
x = 10if x < 5:
print('small')
elif x < 10:
print('medium')
elif x < 15:
print('large')
else:
print('extra large')
Yet Another Example
# Messy and can lead to bugs:
c = 'a'if (c >= 'A') and (c <= 'Z'):
print('Uppercase!')
if (c >= 'a') and (c <= 'z'):
print('lowercase!')
if (c < 'A') or
((c > 'Z') and (c < 'a')) or
(c > 'z'):
print ('not a letter!')
# Better:
c = 'a'if (c >= 'A') and (c <= 'Z'):
print('Uppercase!')
elif (c >= 'a') and (c <= 'z'):
print('lowercase!')
else:
print('not a letter!')
Using "arithmetic logic" instead of "boolean logic"