Before you run it, say out loud what it will print. Then open the answer.
What it prints
a.txt
2
Names kept.
names = ["a.txt", "b.bin"]
keep = [x for x in names if x.endswith(".txt")]
print(len(keep))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
1
3
No matches.
import glob
print(len(glob.glob("none-*.txt")))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
0
4
Files counted.
n = 0
for root, dirs, files in os.walk("."):
n += len(files)
print(n > 0)
Before you run it, say out loud what it will print. Then open the answer.
What it prints
True
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
A folder is listed at run time. Patterns match names, walk visits every level, and an empty result is a valid answer.
1list the folder
↓
2filter the names
↓
3walk deeper
↓
4sort when needed
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
names = ["b.txt", "a.txt"]sets nothing on screen
print(sorted(names)[0])a.txt
Why this worksOrder is not free
A listing comes in whatever order the folder gives. Sort when output feeds a diff or a person, and do not rely on it otherwise.
Empty is a result
A pattern with no matches is a valid answer. Treat zero files as a case, not as a crash.