Wednesday, November 17, 2021

10 reasons why Python is better than C# (or almost any other programming language)

Nearly 10 years ago, I wrote an article on this website comparing C# unfavourably with Visual Basic, which prompted many comments, roughly equally divided between praise and censure. My favourite two (now sadly removed) were “Your website looks like Teletubbieland” (which had some truth at the time, but wasn’t strictly relevant) and “You know f*** all about C#”, which had relevance but – I believe – less truth (and in its original form didn’t have any asterisks either!). To celebrate this anniversary, I’ve decided to reawaken all of you slumbering C# trolls with 10 reasons why Python is better than C# (and better than most other programming languages, too, it has to be said).

1 – Indented code blocks

These are just beautiful! Here’s how you can write a loop and condition in Python to play Fizz-Buzz in Python:

for integer in range(1,11):
    # for first 10 numbers
    if integer % 3 == 0:
        print(integer, "Fizz")
    elif integer % 5 == 0:
        print(integer,"Buzz")

Notice anything? There are no silly { } brackets to denote when a condition or loop block starts and ends because Python can infer this from the indentation. Why type characters when you don’t have to?

2 – Self-declaring Variables

Here’s how you can declare variables in four programming languages:

An image showing how to declare variables in several languages

In Python, you don’t – and can’t – declare variables. Instead, you just assign values to them:

# create a variable to hold the meaning of life
meaning_of_life = 42

Python then creates a variable of the appropriate type (you can prove this by printing out its value):

# show the type of this, and its value
print(type(meaning_of_life),meaning_of_life)

This code would show <class ‘int’> 42. Another nice thing about Python variables is how simple the data types are: there are only integers, floating point numbers, strings, and Boolean values, which is pretty much all a programming language needs, dates being just formatted numbers when all’s said and done).

Now C# programmers will – like I did – initially throw their arms up in horror at this, but haven’t we all been writing lines of code like this for years?

// store life's meaning
var meaningOfLife = 42;

This statement does exactly the same thing: it sets the type of the variable from the context.

I’ve found not having to declare the type of variables strangely liberating, to the extent that I now resent having to declare variables when I go back to writing code in C# or SQL.

3 – Those modules …

Python is Python because of its modules: literally thousands of add-ins, covering everything from scraping websites to advanced AI tasks.

But wait a bit, you may say – C# (at least as it’s written in .NET, which is surely the most common implementation) has “modules” too. Here are just a few of the ones in the System namespace:

An image showing a Using statement in C# and all the options

The answer to which is: yes, it does, but … Python modules are so much easier to use. To illustrate this, let’s take an example: looping over the subfolders in a folder. Here’s how you could do this in Python:

import os
# get a list of all the files in a folder
files = os.listdir(r"C:\__work\\")
# loop over these files
for file in files:
    # show its name
    print(file)

Here’s the approximate equivalent C# code:

using System.IO;
var folder = new DirectoryInfo(@"C:\__work\");
foreach (DirectoryInfo dir in folder.GetDirectories())
{
Debug.WriteLine(dir.Name);
}

I’m aware that it’s subjective, but I find the Python modules to be almost without exception more logically constructed and easier to learn than the equivalent .NET ones, for example.

4 – Simplicity of Data Structures

C# has (deep breath now) the following data structures: Array, ArrayList, Collection, List, Hashtable, Dictionary, SortedDictionary, SortedList. These implement the IEnumerable or IDictionary interfaces. If you’re thinking of learning C#, I’ve probably just put you off for life!

Python has four structures: lists, tuples, dictionaries, and sets, although the first two are virtually identical from the programming point of view. Purists will say that you need all the different data types that C# provides, but trust me, you don’t.

It’s not just that Python only has a few data structures; the ones it does have are so easy to use. Here’s how you create a sorted list of fruit, for example:

# create an empty list
fruit = []
# add some fruit
fruit.append("Pears")
fruit.append("Apples")
fruit.append("Bananas")
# sort this
fruit.sort()
# print

print(fruit)

Programming doesn’t get any more straightforward than this!

5 – Slicing

I’m not generally a fan of languages that try to cram as much logic into as few characters as possible (that’s why I don’t like regular expressions and didn’t get on with Perl).

However, slicing sequences has the big advantage that it’s used everywhere in Python, so once you’ve learnt a few simple rules, you can pick out anything you want. And there’s a certain beauty in code like this:

# the seven deadly sins
sins = ["pride", "envy", "gluttony", "greed", "lust", "sloth", "wrath"]
# every other one, but missing the first and last
# ie ['envy', 'greed', 'sloth']
selected_sins = sins[1:-1:2]
print(selected_sins)

The great thing about slicing is that it carries through to everything. Once you’ve learnt how to slice a tuple, for example, you’ve also learnt how to slice a multi-dimensional array (in numpy) or an Excel-style dataframe (in pandas) or any other sequence of items.

6 – For loops

C# has two separate loop structures, depending on whether you’re looping over numbers or objects, as shown by these two examples:

// first 5 numbers
for (int i=0; i <= 5; i++) {
Debug.Print(i.ToString());
}
// words in a string
string[] words = {"Simple","Talk"};
foreach (string word in words)
{
Debug.Print(word);
}

Here is the same code in Python:

# first 5 numbers
for i in range(1,6):
    print(i)
# words in a string
words = {"Simple","Talk"}
for word in words:
    print(word)

Notice that not only is the Python for loop syntax simple and easier to understand, but there’s only one version of it (unlike in C#, where sometimes you use for and sometimes foreach).

7 – List comprehensions

A list comprehension is one of the most beautiful programming constructs I’ve seen. You can use it as a substitute for C# lambda or anonymous functions, and the result is transparent.

Here’s an example listing out the cubes of all the even numbers up to 10:

# cubes of even numbers up to and including 10
# (would give [8, 64, 216, 512, 1000] as output)
print([n ** 3 for n in range(1,11) if n % 2 == 0])

You could of course do this the long way round:

for n in range(1,11):
    if n % 2 == 0:
        print(n ** 3)

It’s hard to think how you could improve the syntax of the first method: show me this for these numbers where this condition is true.

8 – Sets

I said just now that list comprehensions are beautiful, but so too are sets.

For example, the way to remove duplicates from a list of items in Python is just to convert the list to a set (since sets can’t contain duplicate items, any duplicates will be removed), then convert the set back to a list. Like this, say:

# this contains some duplicates
languages = ["C#","Python","VB","Java","C#","Java","C#"]
# this set can't
language_set = set(languages)
# convert back to a list
languages = list(language_set)
# this will give: ['C#', 'Java', 'Python', 'VB']
print(languages)

However, sets don’t just provide an elegant way to remove duplicates from lists; they also allow you to find the intersection or union of two groups of items (those long-ago maths lessons learning Venn diagrams weren’t wasted after all!).

Pretty much everything you need to know about sets in Python is covered by these few lines of code:

# create two sets: Friends characters and large Antarctic ice shelves
friends = {"Rachel","Phoebe","Chandler", "Joey","Monica","Ross"}
ice_shelves = {"Ronnie-Filchner", "Ross", "McMurdo"}
# show the intersection (elements in both lists)
print(friends & ice_shelves)
# show the union (elements in either list)
print(friends | ice_shelves)
# show the friends who aren't ice shelves
print(friends - ice_shelves)
# elements in either set but not both
print(friends ^ ice_shelves)

This code would give this output ( “Ross” is the only item in both lists, for example):

An images showing the output of sets in Python

9 – Working with files and folders

Virtually everything to do with files and folders is easier than you think it’s going to be. Want to write out the contents of a list? No need to import modules – just do this :

# list of 3 people
people = ["Shadrach","Meshach","Abednego"]
# write them to a file
with open(r"c:\\wiseowl\people.txt","w") as people_file:
    people_file.writelines("\n".join(people))

Want to export this as a CSV file? Just use the built-in csv module:

import csv
# write student amesto a file
with open(r"c:\\wiseowl\students.csv","w",newline="") as people_file:
    potter_file = csv.writer(people_file)
    # use this to write out 3 rows
    potter_file.writerow(["Harry", "Gryffindor"])
    potter_file.writerow(["Draco", "Slytherin"])
    potter_file.writerow(["Hermione", "Gryffindor"])

I could go on to show reading from or writing to JSON files, Excel files, any files using pandas … Python modules make coding as easy as it can be!

10 – The quality of online help

Here are the results of a search using a well-known search engine (!) for the phrase C# tutorial:

An images showing the number of results when searching on C# tutorial

Here are the results for the same search using the phrase Python tutorial:

An image showing the results of searching on Python tutorial

But it’s not just that Python has nearly four times as many tutorial page results: the tutorials themselves are much better, IMHO.

Two reasons not to like Python

It would be disingenuous to end this article without giving two areas in which Python doesn’t compare well with other languages like C#.

The first way in which Python underperforms is that it’s so hard to get started. In C#, you’re probably going to choose Visual Studio as your development environment, and while you will have teething problems, at least everything is integrated. In Python, you have to choose whether to use Visual Studio Code, PyCharm, Jupyter Notebook, or any of a dozen other candidates for your IDE (Integrated Development Environment). Even when you’ve chosen your IDE, you’ll still have to learn how to set up “virtual environments” in which you can install modules for different applications that you’re creating so that they don’t interfere with each other. None of this is straightforward, and it’s a serious impediment to getting started with Python.

The second way in which Python underperforms is that it isn’t always strongly typed. This limitation is best illustrated by an example. Consider this segment of Python code:

def add_numbers(first:int,second:int) -> int:
    # add the two numbers together
    return first + second
# test this out
print(add_numbers(3,5))
# now test this with some text
print(add_numbers("Simple","Talk"))

It creates a function to add two numbers together, then calls it twice. The first call will give 8 (the sum of 3 and 5), while the second will give “SimpleTalk” (treating the “+” in the function as a concatenation symbol).

The problem is this line:

def add_numbers(first:int,second:int) -> int:

This is sometimes referred to as duck typing: if it looks like a duck and quacks like a duck, it’s probably a duck. Except that this looks like an integer and is passed as an integer – and yet is happily accepting a string into the function. The data types are just hints, it turns out: a serious limitation.

Interpreted not compiled

One other big difference between Python and other languages is that the former is interpreted rather than compiled. What this means is that when you run a Python program, the instructions are read as text in sequential order (no executable file is constructed first from the human-readable statements translated into machine-readable language). However, I still can’t decide if this is a good or bad thing, so I have left it off both lists above!

Why Python is better than C#

Python was created by Dutch programmer Guido van Rossum to be as easy to use as possible; he succeeded in his aim! Although the Monty Python references in documentation get a bit tedious (even for this diehard fan), if you’re an experienced C# programmer, you will enjoy the simplicity of programming in Python.

 

If you like this article, you might also like 10 Reasons Why Visual Basic is Better Than C#

 

The post 10 reasons why Python is better than C# (or almost any other programming language) appeared first on Simple Talk.



from Simple Talk https://ift.tt/3Fq3XpF
via

No comments:

Post a Comment