Python for C# Developers (control flow 1)

There are some differences in control flow in C# and Python though the concept in both languages is pretty much the same. Let’s take a look at them.

  1. Entry point
    The entry point to Python program can be expressed like the following. class is NOT necessary in Python, so if you are working on a simple script, I would just start to write logic in the file without a class. That said, I still like to encapsulate everything classes.

    class Main:
        def __init__(self):
            pass
    
        def say_hello(self):
            print('hello Python!')
    
    
    if __name__ == '__main__':
        entry_class = Main()
        entry_class.say_hello()
    
  2. if elif else
    Let’s think about the function that returns month name in a string.

        def get_month_name(num):
            if num == 1:
                return "January"
            elif num == 2:
                return "February"
            elif num == 3:
                return "March"
            elif num == 4:
                return "April"
            elif num == 5:
                return "May"
            elif num == 6:
                return "June"
            elif num == 7:
                return "July"
            elif num == 8:
                return "August"
            elif num == 9:
                return "September"
            elif num == 10:
                return "October"
            elif num == 11:
                return "November"
            elif num == 12:
                return "December"
            else:
                return "Invalid number" # Could throw an error

    I know the sample is ugly, but you get the idea. switch statement is NOT available in Python unfortunately but there is a workaround. I will write about in a separate blog post.

  3. while
    i = 0
    while i < 100:
        print(i)
        i += 1

    Not so elegant but while is still a necessary control statement.

  4. for
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for n in nums:
        print(n)

    for in Python acts like foreach in C#. If you want to express something like for (int i = 0; i < nums.length; i++) {}, you can do something like the following.

    for n in range(1, 10):
        print(n)

    The sample shows that range function can be used to mimic “for (int i = 0; i < nums.length; i++) {}” in C#.

Python for C# Developers (try catch finally)

 

try, catch/except, finally is a necessary control flow in any modern programming language. Here is one in C#.

var obj = new MyObj();

try
{
    obj.func1("bad data"); // This line can cause an error.
    // Do some other work here if error didn't happen.
}
catch(SomeException exp)
{
   ExceptionHandler(exp);
}
finally
{
    obj.CleanUp();
}

Here is the sample in Python.

obj = MyObj()

try:
    obj.func1("bad data") # This line can cause an error.
except SomeError as exp:
    exception_handler(exp)
else:
    # Do some other work here if error didn't happen.
finally:
    obj.clean_up()

Notice that Python can have else clause but it’s not necessary to use it. I would use it if I want a very clear separation between “trying code” and the process after it.

There may be situations where you need to raise errors. You can simply use raise keyword like the example below.

raise ValueError("Entered value is not valid.")

There are quite a bit of builtin error types. They can be found in this document.

Lastly, if you need to create your own exception type, you can create a class that inherits from Exception class.

class MyError(Exception):
    pass

 

Microsoft Buys GitHub

I’m sure everyone knows the news by now. Microsoft is buying GitHub.

My reaction to it is “Oh, OK.”

I don’t like the people who blindly criticize the move. There are old people who still live in the 80s and 90s when Microsoft was regarded as an evil empire. Those people the ones who say “RIP GitHub”. I really don’t think so.

Microsoft is a very different company now that contributes so much to the open source space. I personally think it’s a good thing for GitHub. Microsoft also contributes the Linux Foundation as well. I’m sure they realize that for Microsoft to survive, it cannot exclude or ignore Linux and open source technologies.

I got to learn to love Linux and open source technology very much. I have had such a great experiences in the last few years. I will gradually share my experiences about them.

Python for C# Developers (function)

I think I wrote C# code the most in my career. C# is almost like a mother tongue to me just like Japanese language is though I’ve been speaking “foreign languages” like Groovy and Python quite a bit. When I have to think deep about something, I always go back to my mother tongue. I think I’m going to try it out with C#. In this series, I’m going to write some sample code in C# and then translate it into Python.

I won’t start like what variables are, strings are, integers are… those very basic concepts like in any other “tutorial” sites. I will go straight into what may be useful.

I’m going to talk about functions this time. Functions can be void or ones that return something. Let’s see them in C#.

using System.IO;

public class Functions
    {
        public void WriteString(string path, string text)
        {
            File.WriteAllText(path, text);
        }

        public int Add(int a, int b)
        {
            return a + b;
        }
    }

Now let’s see them in Python.

class Functions:
    def WriteString(self, path, text):
        with open(path, 'w') as f:
            f.write(text)

    def Add(self, a, b):
        return a + b

This is not really “Pythonic”. Let’s change the Python code into more Pythonic way.

class functions:
    def write_string(self, path, text):
        with open(path, 'w') as f:
            f.write(text)

    def add(self, a, b):
        return a + b

Python coding standard is, in short, lower case everything connecting words with underscore. The details can be found here.

It’s very easy to see what the differences are but I will try to explain in words.

return keyword returns a value to the caller of the function.

To create a class, Python uses the same “class” keyword. Whenever you use a keyword (such as if, while, for and etc…), it has to end with : (semi colon). When you define a function, it has to start with def. There is no distinction between function that returns value or not.

“with” keyword in Python is equivalent to using in C#. It makes sure that any resource (such as file, database or network connection) opened this way will be closed when the code gets out of the context. (context manager)

 

Python

I have been extremely interested in and also using Python as one of my favorite programming languages at work and privately. I’m not saying it’s the best language, but it gets job done quite elegantly.

As an experienced software engineer, whenever I want to learn a new language, it has always been a problem that almost all the tutorials go through “Hello World”. I guess “Hello World” is OK because I would definitely need to know how to print some text on a screen. The problem I have is that I don’t need to learn what variables are, what booleans are, what strings are and what-not. I found this guy Dan Bader on YouTube. His lessons tailor to somewhat experienced software engineers and I have been enjoying his contents.

No, I am not affiliated with him nor get paid to talk about it. In this blog, I will only talk about what really interests me and what I think is good for fellow software engineers, I promise.

Software Engineering Trend

I have been in this industry for the last 20 years. A lot has changed and I think I have adopted to the trend quite alright but then new technologies have emerged much more than I can easily absorb, which makes it interesting to be in this industry.

There were no “DevOps”, “Build Engineers” or “System Engineers”. Software Developers used to pretty much do anything that came their way and I was one of them.

In this blog, I intend to write about the trend of software development and pretty much everything related to software development that interests me. This blog will also play a role as my own notes. With so much information you have to digest as a software engineer, there is no way you can remember them all. My own seachable database is a pretty powerful thing to do. I also would like to share what I have learned with whoever is out there.

I hope this blog will help me and help anyone on the Internet. 🙂