I719 Fundamentals of Python/lecture7

From ICO wiki
Revision as of 14:24, 19 March 2017 by Eroman (talk | contribs) (Created page with "= Advanced control flow = == Task 1 == Make a function that returns the sum of all elements in an iterable <source lang="python">>>> my_sum_function([2,3,5]) # 2 + 3 + 5 10...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Advanced control flow

Task 1

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

Task 2

Find if all elements are false

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

Task 3

Implement all function with a for loop

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

Break loops

Task 4

Implement any with a for loop, use a break statement

Error Handling

  • When to raise an exception
  • handling user input

Example: Addition calculator

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.

def add_two_numbers(a, b):
    return int(a) + int(b)

def main():
    a = input('Write a number: ')
    b = input('Write a number: ')
    result = add_two_numbers(a, b)
    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
    result = add_two_numbers(a, b)
  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

def add_two_numbers(a, b):
    return int(a) + int(b)

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


if __name__ == "__main__":
    main()

With checking before

def add_two_numbers(a, b):
    return int(a) + int(b)


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


if __name__ == "__main__":
    main()

Splats

  • dict as kwargs
  • list as args

Task: Sum of all arguments

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