Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write a function read_number(name) that reads a file with one whole number in it, and gives the number. If the file is missing, it gives 0. If the file does not hold a whole number, it gives -1. Test it with a missing file, a file with 42, and a file with abc.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Two different errors, two different answers. A missing file is a FileNotFoundError. A text that is not a number is a ValueError from int().
Check. The missing file gives 0. a.txt holds 42 with a new line, and strip() removes it, so 42. b.txt holds abc, so int raises a ValueError and the answer is -1.
Answer: 0 42 -1.
Log in to join the discussion.
Loading…