Monday 14 June 2021

Python crash course (part 1 - example)

Today - something different. You'll learn Python (3) in 5 minutes, no need to thank... Ok, not exactly. But... Sort of. You know, when you have a little bit of experience and not much time, there is better way of learning some things (like programming languages), instead of tutorials and books. It's to take a look at the thing in action: in case of a programming language, it would be a short program, using some basic features of the language. The additionary benefit is that you can make it solve some problem you have. 

Please mind this note should be quite helpful, if you already know some programming languages, but not Python in particular. If you are a beginner in programming, maybe you can use it as a simple "practical" reference, but you may have problems understanding what going on - I won't elaborate on all things (of course, if you have questions, please do comment).

Ok, so what was that problem in my case? 

Well, I had been testing some feature of my Android game - to be precise, the notifications' logic. Some time after event A the app was supposed to show a notification, but only a limited number of times and in specific conditions (details are not important here). So at first I've opened Notepad and started to write things like:

10:00:00: App starts 10:00:06: Module initialized 10:10:10: Backgrounding the app 10:15:10: Foregrounding the app, module does not work. Why, o why? 10:16:10: Removing app from the device

...based on my app's behaviour and logcat.

After working with that for a day or so, I've realized that:

1) I have notes in 3 different editors open at the same time

2) I've been taking a note with a timestamp about 2 times a minute for a day (I check time, I write it down, I write the note, lot of work).

3) I can make things a bit easier...

And by 3) I mean: 

I can write a simple script, which simply takes the input by user (followed with [ENTER]) and writes every line (with timestamp) to a file. And then if the user types r [enter] (r), it shows the notes so far. This way: everything is in one editor (which is my script), stored safely in one file (which fixes issue 1) ); and I don't have to manually check and write down the time (issue 2, and - inherently - issue 3).

And here is the script, which by the way is one of the programs I've mentioned in the beginning: it uses functions, flow control (loops, ifs), basic data structures, file I/O... Basically a first few lessons in every Python tutorial ;). Nothing advanced, nothing object-oriented for now. We don't need that for now... Maybe in the future.

# !/usr/bin/python3

from datetime import datetime

# a function appending the line to the 'data.txt' file 
# or create the file first it it doesn't exist
def create_or_append(line):
    # open a file to write:
    file_descriptor = open('data.txt','a'encoding='utf-8')
    file_descriptor.write(line+"\n") # write the line
    file_descriptor.close() # close
    
logs_list = [] # define a global list, empty.

# another function: read all the lines from 'data.txt', 
# print them to screen and add them to logs_list list.
def read_from_file():
    # "global": don't override the global logs_list: use it 
    global logs_list
    # make the logs_list empty list: 
    logs_list = []
    # open a file to read
    file_descriptor = open('data.txt','r'encoding='utf-8')
    # iterate over lines read from file
    for val in file_descriptor.readlines():
        # add each one to list
        logs_list.append(val)
        # print it to console ("strip" removes ending '\n')
        print(val.strip())
    # close the previoously open file
    file_descriptor.close()

# a function showing a prompt
# and doing something in input in a loop
def notes():
    res=""
    while (res!="q"):
        # input function shows the text in param
        # and returns user's input
       # (any text followed by [ENTER]
        res=input('add note => [ENTER], [q]uit, [s]how '
        'all notes so far, [r]ead saved data:\n')
        # if input is 's'
        if(res=="s"):
            #...show this text:
            print("Notes so far:")
            # and iterate over logs_list
            for it in logs_list:
                # strip() removes trailing spaces
                print(it.strip())
        #else if input is 'r'
        elif(res=="r"):
            # call read_from_file() function (see above)
            read_from_file()
        # if input is any other (a note)
        elif(res!="q"):
            # get current time, and...
            now = datetime.now()
            # ...format it
            dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
            # add tab and note to time
            string_with_date = dt_string+"\t"+res 
            # add all of it to logs+list
            logs_list.append(string_with_date+"\n")
            # call method above with param
            create_or_append(string_with_date)

# main, where our program begins execution
def main():
    notes() # call the function defined above

if __name__ == "__main__":
    main()

I won't elaborate on the code - I think the Python syntax is very clean and self-explanatory, and I've commented it quite extensively. I think the most cryptic fragment is the if __name__ == "__main__": statement: it's simply the way you should call the main method in Python. You could just write main() in the last line; but when such script is imported as a module, it would be executed automatically (which most probably is not the desired effect). In our case it doesn't really matter (I would't advice importing this as a module ;) ), but let's follow the tradition.

The code is on github here - the linked version may be a bit different, because using it day-to-day, I'll probably tweak something in the future. Maybe I'll update this post too.

Next time I'll elaborate more about functions (and lambda functions). The next lessons will also be more descriptive about basic things.


Meta-notes for today: if you want such nice, monospace, syntax-colored code in Blogger, you can simply copy the contents of a file opened in VS Code (which makes a very nice Python IDE, BTW, with some plugins applied). It works out-of-the-box only for the files with syntax highlighting, so if you just create a new file and type some text, it won't. But in that case, you can use Ctrl+Shift+P -> type Copy -> choose Copy with syntax highlighting.



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...