Skip to content

Commit c60fa6f

Browse files
committed
removing useless stuff and adding useful stuff
1 parent b810450 commit c60fa6f

2 files changed

Lines changed: 134 additions & 33 deletions

File tree

files.md

Lines changed: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ Let's create a file and write a hello world to it.
6969
Doesn't seem like it did anything. But actually it created a `hello.txt`
7070
somewhere on our system. On Windows it's probably in `C:\Users\YourName`,
7171
and on most other systems it should be in `/home/yourname`. You can open
72-
it with notepad or any other plain text editor your system comes with.
72+
it with notepad or any other plain text editor your system comes with by
73+
opening the folder that contains the file and then double-clicking the
74+
file.
7375

7476
So how does that code work?
7577

@@ -82,23 +84,22 @@ object that is assigned to the variable `f`.
8284
>>>
8385
```
8486

85-
So the first argument we passed to `open` was the path we wanted to write.
87+
File objects are not the same thing as paths and filenames, so if we try
88+
to use `'hello.txt'` like we used `f` it doesn't work.
89+
90+
The first argument we passed to `open` was the path we wanted to write.
8691
Our path was more like a filename than a path, so the file ended up in
8792
the current working directory.
8893

89-
The second argument was `w`... but where the heck does that come from?
90-
`w` is short for write, and that just means that we'll create a new file.
91-
There's some other modes we can use also:
94+
The second argument was `w`. It's short for write, and that just means
95+
that we'll create a new file. There's some other modes we can use also:
9296

9397
| Mode | Short for | Meaning |
9498
|-------|-----------|-----------------------------------------------------------------------|
9599
| `r` | read | Read from an existing file. |
96100
| `w` | write | Write to a file. **If the file exists, its old content is removed.** |
97101
| `a` | append | Write to the end of a file, and keep the old content. |
98102

99-
The `w` and `a` modes create a new file if it exists already, but trying
100-
to read from a non-existent file is an error.
101-
102103
But what is that `with ourfile as f` crap? That's just a fancy way to make
103104
sure that the file gets closed, no matter what happens. As we can see,
104105
the file was indeed closed.
@@ -130,9 +131,9 @@ we created to a list of lines.
130131
>>>
131132
```
132133

133-
Trying to open a non-existent file with `w` created the file for us, but
134-
doing that with `r` gives us an error instead. We'll learn more about
135-
errors [later](exceptions.md).
134+
Trying to open a non-existent file with `w` or `a` creates the file for
135+
us, but doing that with `r` gives us an error instead. We'll learn more
136+
about errors [later](exceptions.md).
136137

137138
```py
138139
>>> with open('this-doesnt-exist.txt', 'r') as f:
@@ -150,11 +151,11 @@ that `\n` doing there?
150151

151152
`\n` means newline. Note that it needs to be a backslash, so `/n`
152153
doesn't have any special meaning like `\n` has. When we wrote the file
153-
with print it actually added a `\n` to the end of it. It's good practise
154+
with print it actually added a `\n` to the end of it. It's recommended
154155
to end the content of files with a newline character, but it's not
155156
necessary.
156157

157-
So how does that work if we have more than one line in the file?
158+
Let's see how that works if we have more than one line in the file.
158159

159160
```py
160161
>>> with open('hello.txt', 'w') as f:
@@ -206,7 +207,8 @@ that reads the next line, and returns `''` if we're at the end of the file.
206207
```
207208

208209
There's only one confusing thing about reading files. If we try
209-
to read it twice we'll find out that it only gets read once:
210+
to read the same file object twice we'll find out that it only gets read
211+
once:
210212

211213
```py
212214
>>> first = []
@@ -226,8 +228,8 @@ to read it twice we'll find out that it only gets read once:
226228

227229
File objects remember their position. When we tried to read the
228230
file again it was already at the end, and there was nothing left
229-
to read. But if we open the file again, it's in the beginning
230-
again and everything works.
231+
to read. But if we open the file again, we get a new file object that
232+
is in the beginning and everything works.
231233

232234
```py
233235
>>> first = []
@@ -250,21 +252,7 @@ again and everything works.
250252
Usually it's best to just read the file once, and use the
251253
content we have read from it multiple times.
252254

253-
As we can see, files behave a lot like lists. [The join string
254-
method](https://docs.python.org/3/library/stdtypes.html#str.join) joins
255-
together strings from a list, but we can also use it to join together
256-
lines of a file:
257-
258-
```py
259-
>>> with open('hello.txt', 'r') as f:
260-
... full_content = ''.join(f)
261-
...
262-
>>> full_content
263-
'Hello one!\nHello two!\nHello three!\n'
264-
>>>
265-
```
266-
267-
But if we need all of the content as a string, we can just use [the read
255+
If we need all of the content as a string, we can use [the read
268256
method](https://docs.python.org/3/library/io.html#io.TextIOBase.read).
269257

270258
```py
@@ -297,8 +285,8 @@ adding an `r` to the beginning of the string. In this case the `r`
297285
is short for "raw", not "read".
298286

299287
```py
300-
>>> r'C:\some\name' == 'C:\\some\\name'
301-
True
288+
>>> r'C:\some\name'
289+
'C:\\some\\name'
302290
>>>
303291
```
304292

@@ -312,6 +300,11 @@ don't contain backslashes we don't need to double anything or use
312300
>>>
313301
```
314302

303+
Doing things like `open('C:\\Users\\me\\myfile.txt', 'r')` is not
304+
recommended because the code needs to be modified if someone wants to
305+
run the program on a different computer that doesn't have a
306+
`C:\Users\me` folder.
307+
315308
## Examples
316309

317310
This program prints the contents of files:

loops.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,114 @@ of `stuff.copy()` and `stuff[:] = []` instead of `stuff.clear()`.
297297
- The `break` keyword can be used to interrupt the innermost loop at
298298
any time.
299299

300+
## Examples
301+
302+
Repeat something an endless amount of times.
303+
304+
```py
305+
message = input("What do you want me to say? ")
306+
while True:
307+
print(message, "!!!")
308+
```
309+
310+
Ask the user to enter five things and print them.
311+
312+
```py
313+
things = []
314+
315+
print("Enter 5 things: ")
316+
while len(things) < 5:
317+
thing = input("> ")
318+
things.append(thing)
319+
320+
print("You entered these things:")
321+
for thing in things:
322+
print(thing)
323+
```
324+
325+
Ask the user a bunch of questions.
326+
327+
```py
328+
questions_and_answers = [
329+
# [question, answer], ...
330+
["What is 2+4? ", "6"],
331+
["What is 2-4? ", "-2"],
332+
["What is 2*4? ", "8"],
333+
["What is 2/4? ", "0.5"],
334+
# You could add more questions, but the code that asks them
335+
# wouldn't need to be changed in any way.
336+
]
337+
338+
for qa in questions_and_answers:
339+
while True:
340+
if input(qa[0]) == qa[1]:
341+
print("Correct!")
342+
break
343+
else:
344+
print("That's not what I was thinking of... Try again.")
345+
```
346+
347+
Store a list of names and let the user check if the program knows
348+
the user.
349+
350+
```py
351+
# You can add names here so the program will know them automatically
352+
# when it starts.
353+
namelist = []
354+
355+
print("Options:")
356+
print(" 0 Quit")
357+
print(" 1 Check if I know you")
358+
print(" 2 Introduce yourself to me")
359+
print(" 3 Make me forget you")
360+
print(" 4 Print a list of people I know")
361+
print() # print an empty line
362+
363+
while True:
364+
option = input("Choose an option: ")
365+
366+
# Things like option == 0 don't work because option is a string
367+
# and it needs to be compared with a string.
368+
if option == '0':
369+
print("Bye!")
370+
break
371+
372+
elif option == '1':
373+
name = input("Enter your name: ")
374+
if name in namelist:
375+
print("I know you! :D")
376+
else:
377+
print("I don't know you :/")
378+
379+
elif option == '2':
380+
name = input("Enter your name: ")
381+
if name in namelist:
382+
print("I knew you already.")
383+
else:
384+
namelist.append(name)
385+
print("Now I know you!")
386+
387+
elif option == '3':
388+
name = input("Enter your name: ")
389+
if name in namelist:
390+
namelist.remove(name)
391+
print("Now I don't know you.")
392+
else:
393+
print("I didn't know you to begin with.")
394+
395+
elif option == '4':
396+
if len(namelist) == 0: # len is short for length
397+
print("I don't know anybody yet.")
398+
else:
399+
for name in namelist:
400+
print("I know %s!" % name)
401+
402+
else:
403+
print("I don't understand :(")
404+
405+
print()
406+
```
407+
300408
## Exercises
301409

302410
1. Back in "Using if, else and elif" we created a program that asked

0 commit comments

Comments
 (0)