|
| 1 | +names = ['mark', 'nia', 'kate', 'jenny', 'kate'] |
| 2 | +scores = [90, 80, 65, 87, 90, 60, 68, 78, 91, 90, 63, 64] |
| 3 | + |
| 4 | +index = 3 |
| 5 | + |
| 6 | +def nth_index(lst, occur, search_for): |
| 7 | + curr_i = 0 |
| 8 | + for x in range(occur): |
| 9 | + curr_i = lst.index(search_for, curr_i) |
| 10 | + index = curr_i |
| 11 | + curr_i += 1 |
| 12 | + return index |
| 13 | + |
| 14 | +# call my method and get the result |
| 15 | +found_i = nth_index(names, 2, 'kate') |
| 16 | + |
| 17 | +# you get to choose whether or not to override index |
| 18 | +index = found_i |
| 19 | + |
| 20 | +# use the information that my method returned |
| 21 | +names[index] = 'katy' |
| 22 | + |
| 23 | +# returning different values depending on the situation |
| 24 | +def birthday(age): |
| 25 | + if is_dead: |
| 26 | + return age |
| 27 | + return (age + 1) |
| 28 | + |
| 29 | +# test the function |
| 30 | +is_dead = False |
| 31 | +print( birthday(87) ) |
| 32 | + |
| 33 | +is_dead = True |
| 34 | +# test the alternative result |
| 35 | +print( birthday(87) ) |
| 36 | + |
| 37 | +# return None to stop a function |
| 38 | +def greet(name): |
| 39 | + if name not in names: |
| 40 | + return |
| 41 | + print('Welcome,', name) |
| 42 | + |
| 43 | + |
| 44 | +# this will not display anything |
| 45 | +greet('jeremy') |
| 46 | + |
| 47 | +# this will display the greeting |
| 48 | +greet('nia') |
| 49 | + |
| 50 | +# return multiple values |
| 51 | +def is_div(num, div1, div2): |
| 52 | + res1 = num % div1 == 0 |
| 53 | + res2 = num % div2 == 0 |
| 54 | + return res1, res2 |
| 55 | + |
| 56 | +# return them both into one variable |
| 57 | +result = is_div(80, 4, 3) |
| 58 | + |
| 59 | +is_div_by4 = result[0] |
| 60 | +is_div_by2 = result[1] |
| 61 | + |
| 62 | +# unpack tuple into variables |
| 63 | +is_div_by21, is_div_by5 = is_div(106510, 21, 5) |
| 64 | + |
| 65 | +# split before returning |
| 66 | +is_div_by9 = is_div(540, 3, 9)[-1] |
0 commit comments