REMEMBER PYTHON

MINTE9
2REMEMBER




Conditional

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

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

print(y) # -1
... 6 lines
˄˄˄
 RunCode
n = 0
y = 100 if n > 0 else -1

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

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

print(factorial(3)) # 6
... 3 lines
˄˄˄

Questions    
No. 30   List Comprehension
CARD
29
32

        A B C D E F
🔔
1/1