Exercises (raw input)

  1. Using raw_input(), ask the user for his/her favourite food, store the result in a variable food, then print to screen: I also like and the favourite food.

  2. Ask the user for two integers, let’s say a and b, then a third integer, let’s say result.

    Check whether the sum of a and b is equal to result: if so, print to screen True, otherwise False.

  3. Ask the user for a key and a value, and build a dictionary including (only) that key-value pair. Print to screen the result.

  4. Ask the user for his/her name, store it in the variable name, then print to screen the name, making sure that all the words contained in name are in lower case, except for the first characters, that must be in upper case.

Exercises (Filesystem)

Warning

If open() raises an error, maybe you are in the wrong directory: fix the path in order to be in the right directory.

  1. Use open() to open the file "data/aatable" in read-only mode, storing the result of open() in the variable f.

    Next, use readlines() to read the content of the file, storing the result in rows.

    What is the type of rows? What is the type of the first element of rows? How many rows are there in the file?

  2. Use open() to open the file "data/aatable" in read-only mode, storing the result of open() in the variable f.

    Next, use readline() (not readlines()!) to read the first row of the file, storing the result in first_row.

    How many rows are left to read? Check using readlines().

    At this point, how many other rows are left to read?

  3. Use open() to read the file "output.txt" in write-only mode "w", storing the result of open() in the variable f.

    Next, write the string "check one two three check" in the file.

    Close the file using the method close().

    Now open the file "output.txtx" in read-only mode and print to screen its content.

  4. use open() to open the file "poetry.txt" in write-only memory. Next, write in the file the strings of the following list, one per line:

    verses = [
        "S'i fosse fuoco, arderei 'l mondo"
        "s'i fosse vento, lo tempestarei"
    ]
    

    Next, do the same opening twice the file "poetry2.txt" in write-only mode (appending), and each time write one of the two verses.

    What does it happen when we re-open "poetry2.txt" in mode "w" and we close it immediately?

  5. Write a module trick.py that prints to screen its code.

    Curiosity: we just wrote (cheating!) a Quine program.