Wednesday, January 14, 2015

Hail to the Exec

Today a student in my Python programming class was working on printing out letters on a set of 4 blinkytapes. He'd already spent a lot of time defining functions for how to print out each letter of the alphabet. He called the functions "letterA()" and "letterB()" and so on. Now he wanted to print out whatever the user types in. It's easy to get input from the user:



Then you can loop through the "word" letter by letter:




But the question is how to execute the "letterA()" function when the user types in "a." He was going to use a long list of if statements (he figured copying and pasting would save him a lot of typing) but as usual Python has an easier way.

exec()


There's a function called "exec" which will execute the code inside the parentheses. So my student could put some strings in the argument:





This means he should have just called his functions "a()" and "b()" and so on. But instead of having him change every function name, I suggested he put in this code:



This changes the letter to uppercase (just like it is in his function names), puts the string "letter" on the front of it and adds the parentheses on the end. Executing this is just like executing the code "letterA()".

If the user enters more than one letter, the code just replaces the "a" with a "b" or "c" as needed:


But on the blinkytapes (a string of 60 LEDs) the letters are a function of their starting LED, like letterA(20).

We decided to write a letter for every 6 LEDs so we changed the code to

Python didn't like concatenating the strings to the integer x, so we changed x to a string:




This worked perfectly. Here's a picture of his blinkies. His classmate typed in "yolomcswag."


No comments:

Post a Comment