PROGRAMMING

m9/ PYTHON
REMEMBERS




Conditional

p327 ! We can write conditional statement more concisely using conditional expression.
 
n = 0; y = 0

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

print(y) # -1
 
n = 0
y = 100 if n > 0 else -1

print(y) # -1
Conditional expression came in handy when using recursion.
 
def factorial(n):
    if n == 0: 
        return 1
    else:
        return n * factorial(n-1)

print(factorial(3)) # 6
 
def factorial(n):
    return 1 if n == 0 else (n * factorial(n-1))

print(factorial(3)) # 6

Questions    
List Comprehension

        A B C D E F
🔔
1/1