Avoid using global without confusing new programming students in Python?

后端 未结 2 1328
野趣味
野趣味 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:36

    I would encourage them to start learning OO

    class Location:
         name="a place"
         description = "A dark place.  there are exits to the North and East"
         exits = "North","East"
         def __str__(self):
             return "%s\n%s"%(self.name,self.description)
    
    
    class Player:
         current_location = "Home"
         inventory = ["Blue Key","Magic Thumbtacks"]
         health = 100
         name = "Unknown"
         def __init__(self,name):
             self.name = name
    
    player = Player("Player 1")
    loc = Location()
    print loc
    x = input("Input:")
    

    To be honest a game is a difficult concept (even a text adventure). But I would start them directly on OO concepts, they will benefit more from that in the long term.

    Granted this example is very small and leaves a lot of implementation details out.

    An unrelated but better OO example would be:

    class Animal:
         voice = '...'
         def speak(self):
             return "A %s Says '%s'"%(self.__class__.__name__, self.voice)
    
    class Dog(Animal):
         voice = "Bark, Bark"
    
    class Duck(Animal):
         voice = "Quack, Quack"
    
    print Dog().speak()
    print Duck().speak()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题