I719 Fundamentals of Python/lecture7

Make a function that returns the sum of all elements in an iterable

>>> my_sum_function([2,3,5])
# 2 + 3 + 5
10

all, sum, any

all, true if all elements are true
any, true if any elements are true

Find if all elements are false

opposite_all([False, False])
>>> True

Implement all function with a for loop

my_all([True, True])
>>> True

Break loops

Implement any with a for loop, use a break statement

Error Handling

• When to raise an exception
• handling user input

this calculator is error prone. Users can put in a value that cannot be cast to an integer, which will cause this programs to raise an error.

return int(a) + int(b)

def main():
a = input('Write a number: ')
b = input('Write a number: ')
print(result)

if __name__ == "__main__":
main

giving an error like this on bad user input

Write a number: a
Write a number: 1
Traceback (most recent call last):
File "calc.py", line 12, in <module>
main()
File "calc.py", line 7, in main
File "calc.py", line 2, in add_two_numbers
return int(a) + int(b)
ValueError: invalid literal for int() with base 10: 'a'

With error handled

return int(a) + int(b)

def main():
a = input('Write a number: ')
b = input('Write a number: ')
try:
except ValueError:
print('you must type a valid integer!')
else:
print(result)

if __name__ == "__main__":
main()

With checking before

return int(a) + int(b)

def main():
a = input('Write a number: ')
b = input('Write a number: ')
if a.isdigit() and b.isdigit():
print(result)
else:
print('you must type a valid integer!')

if __name__ == "__main__":
main()

Splats

• dict as kwargs
• list as args

Solution

def sum_args(*args):
return sum(args)

if __name__ == "__main__":
print(sum_args(1, 3, 5))  # 9

Pass a list into the function

def sum_args(*args):
return sum(args)

if __name__ == "__main__":
print(sum_args(*[1, 3, 5]))  # 9