If you learn one programming language, it should be C/C++. But if you learn two, here's an argument that the other should be Python.

 

As an engineer, the last thing you probably need right now is to learn yet another programming language. There are many out there: Ruby, PHP, Java, C#, Javascript, Dart, Go, Rust, etc. Not for you, nope. You’re already fluent in C/C++, which takes you from embedded firmware all the way to GUI applications.

Why would you want to spend the time to learn another programming language that will be obsolete before the next president rolls around?

Well, my friend, I’ll let you in on a little secret. If you’re willing to learn one more language, it can potentially open up a whole new world for you.

As electrical engineers, if you learn one programming language, it should be C/C++. You need it to program the microcontrollers, configure the registers, and you’ll be designing and writing test firmware to exercise various parts of the circuit. It allows you to dig into the nuts and bolts of the hardware, writing values into different registers, accessing memory buses, and controlling hardware peripherals.

But if you learn two languages, I would argue that the other one should be Python. 

 

Image used courtesy of Christina Morillo

 

Power and Control vs. Simplicity and Flexibility

The reason C++ is so useful for hardware designers is the exact reason why it’s not so great for writing applications. You get all kinds of control over the bare metal—but, since you control it, it’s all your responsibility. You have to make sure that you de-allocate any memory you allocate, that your pointers actually point to valid locations in memory, and that your data types are assigned properly and don’t overflow.

What you get from all that awareness is raw power and speed but heaven forbid you to make a mistake since it could send the whole application or even the complete system crashing down.

This is where Python is a joy to work with. Sometimes you don’t need all that speed or to control things in memory so tightly. Instead, you just need something to work. 

 

Python is one of the fastest growing programming languages. Image used courtesy of David Robinson via StackOverflow.

 

Python abstracts away a lot of the details we need to deal with in C++ such as memory management and variable data types. There’s no more worrying if a variable will overflow or if the correct amount of memory was allocated or de-allocated. That all happens magically in the background. You just need to focus on putting code on (virtual) paper.

What really makes Python stand out as a good second language is its large and growing community, huge support of open source libraries, and that it supports a diverse set of applications like web application programming, data science, data visualization, and general purpose automation. Those are all hugely powerful domains that are horribly complicated if you tried to use C++.

Even something as simple as opening a file and parsing its contents, something that EEs have to do regularly for all sorts of things, is painfully easy in Python. Here’s an example where we open a file and print its contents to the screen:

 

C++

 

Python

 

The Case for Python

Now I’m not here to preach which language is better. I use both languages regularly as well as others like Java, C#, and Javascript on an as needed basis. But in my opinion, if I had to give advice on what languages an up and coming EE should learn, my advice would be first C++, then Python. (Hmmm…and perhaps Verilog, depending on whether or not you do programmable logic, but that’s a different article series.)

This article is a starting point for a larger series on Python as it relates to electrical engineers. As we get deeper into this series, I’m hoping it will become more and more apparent why an understanding of Python will open up new worlds to an electrical engineer.

Even though I just used a very trivial example of file parsing above, that’s the very foundation of tons of design automation as well as data science. Beyond that, we will be exploring the various libraries to learn how to set up databases, web servers, creating a REST API, mine large datasets, create slick data visualizations, detect objects with a webcam, and we’ll throw in a bit of machine learning. I threw that last one in since it’s all the rage in the techie (and non-techie) circles. You can impress the tech hipsters you talk to at Starbucks with that one.

 

Data visualization in Python using Seaborn. Image used courtesy of Insight Data

 

So put on your programming hats and stay tuned as we embark on a journey to explore new frontiers of technology from the eyes of an electrical engineer. I’m hoping that this series can not only allow you to automate things more efficiently but expand your world beyond designing hardware and circuits and into designing complex systems, systems that not only involve electronics but leverage the mountains of technology that an understanding of Python allows you to access.

 


 

What's your take on Python? What would you like to learn about it? Share your views in the comments below.

 

Comments

26 Comments


  • tim.savage 2019-04-10

    I often use python scripts for generating data tables for use in embedded C.

    • akiba 2019-04-11

      Yes! I do that too!
      Thanks for the comment smile

  • nandohurtado 2019-04-10

    I would like to learn the application areas of Python in microwave and RF engineering, including Digital Signal Processing.

    • akiba 2019-04-11

      We won’t necessarily get into how python can be applied to RF (I’m an RF engineer myself), but will get into how we can automate test equipment and data collection. This is one of the things I find myself spending a lot of time on.

  • PeiKay 2019-04-10

    The paragraph below has an error….something as simple as opening a file and parsing its contents, something that EEs have to do regularly for all sorts of things, is painfully easy in Python. ........
    It should be painlessly easy in python

    • akiba 2019-04-11

      Thanks for the comment. Actually I meant “painfully easy” as a way to emphasize that many things in python feel like they’re not supposed to be that easy. Coming from a C++ background, I’m using to more verbosity and setup before getting to the actual meat of an operation.

      • MurrG 2019-04-11

        Seems you’re in violent agreement :D ATM I’m having to convert from VB6 to C#. For embedded I only use 8 bit processors; assembler works a treat. But rest assured, I’m not trying to strangle the Python

  • Passer By 2019-04-11

    Your example on C++ file parsing is both buggy and unnecessarily verbose. Here’s a one-liner in C++: copy(istream_iterator<char>{ifstream{"test.txt"}}, {}, ostream_iterator<char>{cout}).

    • akiba 2019-04-11

      Thanks. You’re correct in that it’s possible to throw everything into a typecast iterator so that the portion of code inside the main() function is a one-liner. My point is that python handles these types of operations in a simpler way than C++. As we go through the series, I think this will become more clear.

  • John Blake Arnold 2019-04-11

    I love Python, but given that any executable or library can be called from the C preprocessor (cpp), my second language system would have been MATLAB/Octave

    • Zorglub 2019-04-12

      Actually for anything Matlab I’d use Python libraries such as NumPy, SciPy and Matplotlib for numeric computation, then SymPy for symbolic computation.
      Best of all, it’s free.

  • Raymond Genovese 2019-04-12

    “You can impress the tech hipsters you talk to at Starbucks…” Wouldn’t that be a reason NOT to learn Python?

  • lisandropm 2019-04-12

    Python is a great language for prototyping (I do it a lot with modems) and even “gluing together” many things, specially libraries written in another languages: chemical reactions in Fortran, managing IEEE 488/HPIB devices, Octave, Matlab…
    But at the end of the day I use C/C++, specially if I can use Qt.

  • vanderghast 2019-04-12

    One of the MAIN criteria about which programming language to use could be how easy it would be to maintain it. APL is very fast to use, from making movie (TRON, from Disney, was developed in APL)  to develop logic for new intercepting missile (Patriot missiles), but try to maintain it… So, if I consider Python, with its unfortunate choice of using indentation as scope delimiter, that is prone to bug and errors, to other “choices”, keeping maintenance in perspective… While there are out there some GUI developed in Python (such as Alice, for the ADALM1000, … the end result is a little bit like something of one of two generations… from the past. So, to me, Python stands between Excel Spreadsheet (for dirty mathematical prototyping that you will run just once) and a more decent long life application with a user interface ( XAML + C#, or something similar). Sure, someone using Excel, or SQL, doesn’t generally try to use I/O directly and to react asap to new inputs, but if “asap” responsiveness is also part of the criteria, standard Python does not score very high. So, for SOME electrical prototyping, it has advantages, but are they that different than those presented by C/C++ (which is ALSO poor in User Interface, but “better” in maintenance for application with a “long” life expectancy, imho). So, as a second language, I would suggest … SQL … for something really different, while having some usefulness, such as:  make a combination of 2 10%-resistances in parallel to get 250 Ohm as close as possible. It is a single line, in SQL (assuming that you already have a table with the commercial values for 10% resistances, at your disposal). I suspect that you can even come with the solution faster using Excel (with a couple of manipulations, though).

    • Zorglub 2019-04-12

      Originally I reacted as you do about the indentation, but in my experience it ends up clarifying a lot the intent and is a net positive for maintainability, as paragraphs and indentation help readability of text. smile

      Python is a general purpose language with more and more libraries that allow any kind of interpreted processing. No-one is going to suggest it replace C/C++ or even does the same things - and driving an electrical device is only a tiny part of what I am using it for.
      For instance I came up with a test framework over USB for a medical device, including real-time (you read it right) graphing of data coming from it. The framework also slurps the C sources and map file and allows the user to peek at structures content in the live code, accessed directly by their structure names.

      You may want to consider other applications than scrubbing spreadsheets.
      How about building Nyquist or Bode plots and determining the poles and zeros of a system from the raw data in real time?
      (Real time here means “as fast as necessary”, not necessarily “in a split femtosecond”.)

  • Curt Carpenter 2019-04-12

    For hardware guys, rather than moving horizontally or upwards to Python for a second language, I’d recommend moving downward toward the foundation and getting deeply familiar with assembler, debugger and tool chain for a modern MCU.

    Or just accepting the discipline required to truly master and contribute to the one HLL you chose.   

    In my view, vanderghast’s comment below is on target:  looking ahead toward software maintenance is really important, even for the casual programmer.  Assembly is perhaps the hardest of all languages to maintain—but at least offers the possibility of achieving the absolute maximum performance as compensation for that defect.

    • Zorglub 2019-04-12

      I agree, however
      - Knowing your way around a debugger with ICE is a must, however this is a tool, not a language.
      - Verilog or VHDL are not for SW development
      - A C/C++ programmer will need Assembly to get started on bare silicon

      In my experience Assembly accounts for a small fraction of the embedded code of any modern system.
      More to the point the use of Python is to quickly and reliably get stuff done on a PC to ease your design.

      Admittedly I am more a SW guy now, but only after years of control and power electronics including VHDL on Xilinx and Altera as well as analog control for a 2000MW (not a typo) DC link between France and England. I still bring up boards, I still write Assembly when needed but I find that in my day-to-day work I write mostly C and Python - not even C++.

      If you ever have to write control code for an environment such as VDSP++ and you only know C, you end up learning TCL on the fly and it is not pretty. (Or JavaScript as I did and it is not that pretty either.)

      Note that the article does not suggest you use Python to program the chips on your designs, but to perform all these painful tasks we know a computer can help with in the process of coming up with a functional design.

      The advantages of Python:
      - Shallow learning curve (no need to know a lot to start doing useful stuff)
      - Expressive (do a lot with little typing)
      - Extensive libraries (no need to reinvent the wheel)
      - Supports many paradigms: procedural, structured, object, even functional programming and does not force one down your throat: use the one that’s natural to you

      Its drawbacks:
      - Not typed (unless you use Numpy) can be confusing for C practitioners
      - Variables scope can be confusing for C practitioners

  • kjmclark 2019-04-12

    This is exactly right, and it’s kind of depressing.  It’s depressing because python is a big deal because C/C++ hasn’t evolved well, and python, which really isn’t that great of a language for much beyond web development, is a bit of a pain.  But it’s clearly winning, and that’s probably enough said. 

    Python is slow, it’s very set based, and you’re going to spend half your time keeping up with the version updates and package after package after package to get things done.  It has a very flavor-of-the-week aspect to those packages too.  No one is really in charge, so it’s constantly in flux.  You know, like the internet and web development.  You can pull out old C++ code from 20 years ago, and there’s a decent chance it will compile and run.  You can pull out Python code from a year ago and find out it’s one major and 15 minor versions old, and all of the packages are now obsolete.  But that’s how development is being done these days, so get used to it.

    But the reasons for that are good - the machines get faster more quickly than we can write code anyway, the constant hacking attacks mean that development has to change constantly as new threats happen, almost all of those changes are because of significant improvements, etc.  And what good would most 20-year old C++ code be anyway?

    Of course, maybe you should skip python and learn go instead…

    • Zorglub 2019-04-12

      With all due respect I believe there is a confusion here: C/C++ and Python have very different purposes.
      Python being interpreted is necessarily slower than native compiled code (one could argue it’s not true with Cython but that would be missing the point).
      Its being interpreted is a feature: it makes it very easy and fast to slap together a tool for the need of the moment, and no, that does not mean just for web development. I use it for processing device logs from raw binary to detailed graphs. I use it for data analysis of clinical studies. I use it for signal processing.

      Now you do have a point with the libraries question. Yes indeed the look-and-feel is not very coherent, and yes there are compatibility issues between libraries, especially when mixing very different domains.
      However the backward compatibility issue you refer to is mostly only between Python 2.7 and Python 3 - They decided to continue supporting Python 2.7 precisely because of backward compatibility issues introduced with Python 3 so that people would not have everything broken. Still it was very clear from the get go that any new development should be done on Python 3 except when the needed libraries had not been ported yet.
      Please note that the same problem would have happened if C/C++ had been evolving as fast as Python does.

      Also note that there are configuration management systems such as Conda (and Anaconda) specifically to tackle the question by allowing you to define combinations of versions of Python and libraries and determining what program would be run with what configuration. I agree it is sub-optimal but I have had good success with these so far.

      Personnaly I try to rely as little as possible on external packages and the ones I do rely on are the most widely used and stable ones (the ones I listed in an earlier answer above.)

  • trnscndr 2019-04-13

    Python is an invaluable resource for high performance computing, if you’re an engineer inclined to that direction. You will shoot yourself in the foot trying to use C++ for it.

  • Shyam D 2019-04-14

    One similar thing i recently came across is micropython which is even implemented for controller
    one other in ZYNQ based board using python to convert python code to HDL logic
    read more at : http://tinyurl.com/y3plzdkd

  • Jake1 2019-04-14

    Please comment on close loop control and uPython.

  • daviviotto 2019-04-14

    RAM is more if the same programs stay running for days or weeks, if I restart and restart the same programs from memory, why should I? The exchange is the correction is bad too, show a same of memory control are loosing step by step? I hork whith Linux, Ubuntu. Hardware are good work in ASM or C.

  • tradition 2019-04-15

    I use python to create virtual world with Arduino… although I am still a newbie

  • MIS42N 2019-04-15

    Interesting thread. I have learned many programming languages, ultimately the choice is a compromise between the tools you know how to use and the task at hand. Python is a snowball, people write snippets of code in Python that other people want, so they learn Python then produce more snippets of code and so on. In many ways the language is irrelevant. My preference is to write in assembler. The C language for low level programming is nearly as obscure as assembler, good documentation is key to maintainability (in any language). If I need to prototype, I’ve been known to hack up some .vbs and run it in the script engine in a DOS box. It’s clunky, but it’s convenient and it works. No way would I recommend either option (write assembler or write .vbs scripts) to someone else. If I were to give advice, it would be to use the tools with the best community support in the area you are interested in. The community didn’t get there by accident, they have done the evaluations, they made the choices. Today it’s Python - well documented.

  • Peterg17 2019-04-20

    I have two observations on this subject.

    1) In terms of programming speed, writing a project and getting it going in python takes about one third the time doing it in C/C++ does, for me.

    2) Every large complex software system inevitably depends on some scripted or data-file driven heart to define its various incantations. It is much better to invert the process, start with a python core, and detach the bits that run slowly in a faster language such as C, if numpy won’t do it for you.