From C# To Python – Conditionals

I created a course called Python for the .NET Developer and wanted to blog some portions of it.

Throughout the course I compare how things are done in CSharp and then demonstrate them in Python to see the difference. I understand why so many boast Python as an easy language to code in but it did feel weird at first given how long I’ve code in C#.

Any who – One of the early topics I hit on is conditionals. Specifically, the IF statement.

A condition is a statement that compares things and tells us whether the criteria set by the comparison are either True or False & use operators to create our conditions, such as equal to, greater than, and less than.
If statements are one of the most common type of statement used when implementing conditions. If, else & else if.

static void DemoIf() {
    int testGrade = 95;

    // Ex: if
    if (testGrade>85)
    {
        WriteLine("You did good!"); 
    }else{
        WriteLine("You did not work hard!");
    }

    // Ex: else if
    if (testGrade > 94)
    {
        WriteLine("You did awesome!");
    }
    else if (testGrade > 85)
    {
        WriteLine("You did good!");
    }
    else
    {
        WriteLine("You did not work hard!");
    }
    // Ex: multiple operators
    if ((testGrade >= 90) && (testGrade <= 95))
    {
        WriteLine("You almost reached excellence!");
    }
}

To replicate the same code in Python, you’d enter the following…

def demo_if():
    testGrade = 95

    # Ex: if
    if testGrade>85:
        print("You did good!") 
    else:
        print("You did not work hard!")
    
    # Ex: elif
    if testGrade > 94:
        print("You did awesome!")
    elif testGrade > 85:
        print("You did good!")
    else:
        print("You did not work hard!")

    # Ex: multiple operators
    if ((testGrade >= 90) and (testGrade <= 95)):
        print("You almost reached excellence!")

What are the difference that you like, and don’t like in both languages? What seems more easy on the eyes?

Python for the .NET Developer is available on at reynald.teachable.com