Good day!
May I have somebody’s help on a sample in a book that I am reading and trying to learn Python?
For the codes shown below. I’ve never define “each_score” so why this “each_score” is recognized by Python and running fine?
scores={}
result_f=open("py score.txt")
for line in result_f:
(name,score)=line.split()
scores[score]=name
result_f.close()
print("The top scores were:")
for each_score in scores.keys():
print('surfer '+scores[each_score]+' scored '+each_score)
by the way, the text file content is simple as below:
Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31
Note – not an answer, but just a large comment that won’t format in a comment field… Just some tips on learning (which I’ve had to write quickly as my battery is about to die…)
You should be looking to using the
withwhere ever you need automatic resource closing (have a look at the fine manual)… Comprehensions can be useful (see thedictbit below)… ‘Proper’ naming of variables is also good – in this casesurfer_scores… Unpacking tuples such asfor surfer, scorealso adds readability, and using string formatting instead of concat’ing is also useful.So after you’ve done the necessary learning bits, your above code could become something like: