简体   繁体   中英

Why does python recognise my object even when I haven't defined it?

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

No, you have defined it in your for loop .

In your example your variable should get the first value from your keys, on the second iteration the second value and so on.

You are defining it in the loop. Every iteration each_score will get the current value of score.keys() .

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 with where ever you need automatic resource closing (have a look at the fine manual)... Comprehensions can be useful (see the dict bit below)... 'Proper' naming of variables is also good - in this case surfer_scores ... Unpacking tuples such as for surfer, score also 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:

with open('py score.txt') as fin:
    surfer_scores = dict(line.split() for line in fin)

for surfer, score in surfer_scores.iteritems():
    print('Surfer {} scored {} points'.format(surfer, score))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM