Saturday, 10 July 2021

Python crash course part 5 (control flow)

Until the last post, I guess I've kind of skipped over some very basic thing: control flow.

So here is a script with simple class, defining some lists as its fields, a method for checking if a string is in one of this lists (using if - elif - else), then for in ("foreach") and for .. in range(...) ("classic for") as well as a while loop example.

Listing 1

# !/usr/bin/python3


class Fellowship:
    # method declaration, self - instance (the method is called      # with only 1 arg) in parentheses
    def check(selfname):
        # these are instance fields:
        self.hobbits = ["Frodo""Bilbo""Sam""Merry""Pippin"]
        self.people = ["Aragorn""Boromir"]
        self.dwarves = ["Gimli"]
        self.elves = ["Legolas"]
        self.istari = ["Gandalf""Saruman""Radagast"]

        # if, elif, else
        if name in self.hobbits:
            print(name + " is a hobbit")
        elif name in self.istari:
            print(name + " is a wizard")
        elif name in self.people:
            print(name + " is a human")
        else:
            print(name + "? - I don't know what he is")

def main():
    # object creation
    fellowship = Fellowship()
    # calling a method
    fellowship.check("Gandalf")

    print("HOBBITS:")
    # for ("foreach") loop
    for name in fellowship.hobbits:
        print(name)
    
    print("ISTARI:")
    # for ("classic", with number)
    for i in range(0len(fellowship.istari)): # 0..len(...)-1
        print(fellowship.istari[i])

    # while loop
    
    number = 0
    print("PEOPLE:")
    while(number<len(fellowship.people)):
        print(fellowship.people[number])
        number = number+1


if __name__ == "__main__":
    main()

The result of calling this code is as follows:

Gandalf is a wizard
HOBBITS:
Frodo
Bilbo
Sam
Merry
Pippin
ISTARI:
Gandalf
Saruman
Radagast
PEOPLE:
Aragorn

First, the call to check() method, then for in loop to enumerate the hobbits, then for .. in range(...) one to list the Istari, and last but not least: classic while to list people.

No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...