================================ Python: Input-Output (Solutions) ================================ Raw input ------------------ #. Solution:: food = raw_input("What is your favourite food? ") print "I also like", food #. Solution:: a_and_b = raw_input("Write two integers: ") words = a_and_b.split() a = int(words[0]) b = int(words[1]) answer = raw_input("how much is " + str(a) + " " + str(b) " ? ") result = int(answer) print a + b == answer #. Solution:: key = raw_input("give me a key: ") value = raw_input("give me a value: ") dictionary = {key: value} # or dictionary = {} dictionary[key] = value print "dictionary =", dictionary #. Solution:: name = raw_input("Give me your full name: ") fixed_words = [word[0].upper() + word[1:].lower() for word in name.split()] print "Your name is:", " ".join(fixed_words) Filesystem ---------------------- #. Solution:: f = open("data/aatable", "r") # or f = open("data/aatable") rows = f.readlines() print type(rows) # list print type(rows[0]) # str print len(rows) f.close() #. Solution:: f = open("data/aatable") first_row = f.readline() print "The first row is: ", first_row remaining_rows = f.readlines() print "another", len(remaining_rows), " rows are left" remaining_rows_bis = f.readlines() print "then, another", len(remaining_rows_bis), "rows are left" # In the last case, 0 rows should be left: the first # readlines() already read all the lines of f f.close() #. Solution:: f = open("output.txt", "w") f.write("check one two three check") f.close() g = open("output.txt", "r") print g.readlines() g.close() #. Solution:: verses = [ "S'i fosse fuoco, arderei 'l mondo" "s'i fosse vento, lo tempestarei" ] f = open("poetry.txt", "w") f.write("\n".join(verses)) f.close() Now let's try with ``"a"``:: f2 = open("poetry2.txt", "a") f2.write(verses[0] + "\n") f2.close() f2 = open("poetry2.txt", "a") f2.write(verses[1] + "\n") f2.close() And if we use ``"w"`` on ``"poetry2.txtx"``:: f = open("poetry2.txt", "w") # Here we do absolutely nothing to f, we just close it f.close() we can see that now ``"poetry2.txt"`` is empty! This happens as a consequence of using ``"w"`` instead of ``"a"``. #. Let's write in the file ``trick.py``:: myself = open("trick.py") print myself.read() myself.close() Let's execute the file to verify that it's working as we want: from a shell, let's write:: python trick.py