Avoid using global without confusing new programming students in Python?

后端 未结 2 1331
野趣味
野趣味 2020-12-17 17:09

I\'ve been teaching 8th-9th graders basic computer programming for two weeks, and yesterday I tried to show them how they could make real simple text-adventure games in Pyth

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 17:58

    Assuming you want to keep things as simple as possible (no OO) and want to avoid introducing the global keyword, you could instead use a state dictionary and assign variables in there.

    state['hasKey'] = True
    

    Since access to this dict is not a variable assignment you avoid introducing the global keyword and at the same time can teach how to use a dict (checking for keys etc.)

    Of course you still use a global variable and don't really address the issue of good coding style. But on the other hand, it could serve as an introduction to scopes and namespaces.

提交回复
热议问题