Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Welcome 🤗! In the next ~4h we will cover:

A safety net - a metaphor for exception handling. Marek Slusarczyk, CC BY 3.0, via Wikimedia Commons

A safety net - a metaphor for exception handling. Marek Slusarczyk, CC BY 3.0, via Wikimedia Commons

Test

(20 min)

Accept the assignment

Learning goals

Preparation review

Question pool

  1. We used input() and print() to input and and output before. What is the motivation for using files in a program?

  2. You are working in a fashion company and would like to replace the telephone- and paper-based ordering pipeline with a digital one and start writing a simple prototype. Which Python file-related functions could be useful?

  3. What are the three main modes used to open a file? What are their differences?

  4. Your colleague writes f = open("orders.txt", "w") every time a new order arrives, then f.write(order). Why do the earlier orders disappear, and which mode should they use instead?

  5. If a file is opened in append mode, what happens to the file’s existing concents?

  6. What does the following code display:

    try:
         x = float('abc123')
         print('Conversion is complete.')
    except OSError: 
        print('Code caused an IOError.') 
    except ValueError:
        print('Code caused a ValueError.')
    
    print('End.')
  7. What is the difference between the two approaches? Which one is preferred in Python?

    import re
    
    def is_integer(s: str) -> bool:
        """Return True if s is a string representing an integer, e.g. "42" or "-7"."""
        return re.fullmatch(r"[+-]?[0-9]+", s) is not None
        
    while not is_integer(order_count_str := input("Enter order count: ")):
        print("You did not enter a number. Try again.")
    
    order_count = int(order_count_str)
    # process order
    ...
    def input_order_count() -> int:
        while True:
            order_count_str =  input("Enter order count: ")
            try: 
                order_count = int(order_count_str)
            except ValueError:
                print("You did not enter a number. Try again.")
            else:
                return order_count
    
     order_count = input_order_count()
     # process order
  8. Why should you prefer with open(...) as f: over calling f.close() yourself? What happens if an exception occurs between open and close?

Coding

E: Reading the first 5 lines

E: Sum of lines