PYW.png 8a: Recap

Table of Contents

1. Exam 1

2. Recap

2.1. Some general things you should be able to do

What happens if you convert:

  • set("hello")
print(set("hello"))
  • str({3,4,5})
print(str({3,4,5}))

print(type(str({3,4,5})))
  • int("345")
print(int("345"))

print(type(int("345")))
  • str(345)
print(str(345))
print(type(str(345)))
  • list(range(10))
print(list("hello"))

  • set(range(10))
print(set(range(10)))
set1 = set("hello")

set1.add(100)

print(set1)

2.2. Recap homework

2.2.1. Question 6: counting characters

Write a Python program that open and reads the songlyrics.txt file, and counts how often a certain character (except whitespaces, tabs and line-breaks) appears. This means that besides vowels and consonants, you should also take into account numeric characters and punctuation signs. Print to the console each of the characters followed by its final counting, each in a different line.

with open("/home/misha/git/programming-your-world/files/7b/song_lyrics.txt") as file:
    words = file.read()

dict_new = {}

for i in words:
    if i in dict_new:
        dict_new[i] += 1
    elif i not in ("\n", " ", "\t"):
        dict_new[i] = 1

print(dict_new)


with open("/home/misha/git/programming-your-world/files/7b/song_lyrics.txt") as file:
    lyrics = file.read()

dict1 = {}
for i in lyrics:
    if i != " " and i != "\t" and i != "\n":
        if i in dict1:
            dict1[i] += 1
        else:
            dict1[i] = 1
print(dict1)        

3. Writing files

Last Friday we saw that we can read files like this:

with open("example.txt","r") as file:
    lines = file.readlines()

for i in lines:
    print(lines)

Let us now look at how we can write to text files as well:

3.1. Write and append to text file

Writing to a file:

with open("example.txt","w") as file:
    file.write("this is the output of a python script")

N.B.: The file is only open (and therefore open to edits) within the "with"-block. So this does not work:

with open("example.txt","w") as file:
    file.write("this is the output of a python script")

file.write("\nthis is yet another new line")

If you open a file in the "writing" mode ("w") and then use .write you will overwrite whatever was inside the file.

with open("example.txt","w") as file:
    file.write("this is replacing the output of the previous python script")

Within the "with"-block you can use the .write method multiple time without replacing what you have already written…

with open("example.txt","w") as file:
    file.write("---------\n")
    for i in range(5):
      file.write("Number %s\n" % i)

… but if you leave the "with"-block and open the file again, any usage of .write will replace whatever was inside the file.

with open("example.txt","w") as file:
    file.write("test1")

with open("example3.txt","w") as file:
    file.write("test2")

If you want to add to the content of an existing file (rather than overwrite/replace it), you can use .append

with open("example.txt","a") as file:
    for i in range(5):
        file.write("\nthis is additional output of a python script")

4. Formatting text output

Remember from last Friday that this is a way to add a value to a print statement:

for i in range(4):
    print(f"This round of the for loop, the variable i has the value {i}.")

Using this way of printing text, there are a few extra tricks. For instance:

f"{value:{width}.{precision}}"

In the example below "width" stands for the minimal width that will be occupied by the value that you want to print. If the value itself does not require that full width, the rest will be filled up with whitespace:

value1 = 10
value2 = 20
print(f"Value 1 is {value1:5} and value 2 is {value2:5}")

You can also change the alignment of the text within that minimal width:

value1 = 10
value2 = 20
print(f"Value 1 is {value1:5} and value 2 is {value2:5}") # By default integers are outlined to the right
print(f"Value 1 is {value1:<5} and value 2 is {value2:<5}") # With the < and > we can change the alignment.

# In both cases, the integer + whitepsace takes up the same width.

When printing floats, there is also this trick:

pi = 3.14159

print(f"{pi:.2f} is an approximation of pi.")
print(f"{pi:10.2f} is an approximation of pi.")
print(f"{pi:<10.2f} is an approximation of pi.")

We can use these tricks to format the text we write to files:

with open("christmastree.txt", "w") as file:
  for i in range(10):
      output1 = i * "a"
      output2 = i * "b"
      file.write(f"{output1:>12}{output2:<12}\n")

Created: 2025-04-03 do 15:55