PROGRAMMING

  minte9
MEMORYApp




S R Q
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Conditional

p327 We can write conditional statement more concisely using conditional expression.
 
# Conditional statement ...
#
# normal expression
# short expression

n = 0
y = 0

# Conditional expression - normal use

if n > 0:
    y = 100
else:
    y = -1

assert y == -1
assert y != 100


# Conditional expression - concise

n = 1
y = 100 if n > 0 else -1

assert y != -1
assert y == 100

Recursion

Conditional expression came in handy when using recursion.
 
# Conditional expression are very useful ...
# when using recursion.
#
# Factorial number:
#
# 0! is 1
# n! = n(n-1)!

def factorial(n):
    if (n == 0): 
        return 1
    else:
        return n * factorial(n-1)

assert factorial(3) == 6
assert factorial(0) == 1
assert factorial(4) == 24


def factorial(n):
    return 1 if n == 0 else (n * factorial(n-1))

assert factorial(3) == 6
assert factorial(0) == 1
assert factorial(4) == 24

Questions    
Last update: 7 days ago
List Comprehension