13
Day 2 homework
j edited this page 2023-06-07 03:10:42 +02:00
  1. Annotate the following python expressions with the specific types of each literal, as well as the overall return value:

    • i = 3
    • f = 3.0
    • c = 3+3i
    • b = b'abcdefg'
    • s = 'abcdefg'
    • s = "abcdefg"
  2. For each of the types string, bytestring, integer, floating point, and imaginary literals, construct a 5x5 table showing what happens when the character "0" or number 0 is compared to each other type.

  3. Now do the same thing for the + and == operators for each pair of types in two other 5x5 tables.

  4. Write a small program that uses the AST module to open the lexer/parser example, and dumps the resulting AST. See if there are any arguments to the parse method which make the output easier to read.

  5. What does this do? print("\007") Can you figure out why? [1]

  6. What does this do? print("abcdefg\rhijklmnop") Can you figure out why?

  7. This is an HTTP server. Run it and connect to http://localhost:8000 . Why doesn't this do the same thing as what you see above? (don't forget to shut down the HTTP server afterward.)

    import http.server
    import socketserver
    from urllib.parse import urlparse, parse_qs
    
    class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            output_string = "abcdefg\rhijklmnop"
            self.wfile.write(output_string.encode())
    
    PORT = 8000
    Handler = MyRequestHandler
    httpd = socketserver.TCPServer(("", PORT), Handler)
    print(f"Serving on port {PORT}")
    
    httpd.serve_forever()
    
    1. Think of a way someone might try to commit a crime or hide an embezzlement scheme using the answers to the above two questions. Hint: applications usually output on web pages, but developers and system administrators usually troubleshoot in the console.
  8. Think of how you would do input validation to prevent such a crime. Replace the code REPLACE ME here so the tests pass:

def validate(str):
    for char in str:
        if REPLACE ME:
            raise ValueError("Crime detected!")

try:
    validate("abcdefg")
    print("✅ test1 pass!")
except:
    print("❌ test1 pass!")

try:
    validate("abcdefg\rhijklmnop")
    print("❌ test2 fail!")
except ValueError as err:
    print("✅ test2 pass!")

Footnotes:

[1] You have to turn on the setting terminal.integrated.enableBell in Visual Studio Code for the bell to work.