I’m trying to learn Python for my new Raspberry Pi — though with all the app development I do that is not so easy. I need to wrap my head around some very different concepts.
The first concept that is obvious is the dynamic typing of Python. If you’ve used Objective-C or C, those are static typed languages. At compile time We set the variable for life of the variable that type. I’m used to writing in Objective C:
float number = firstNumber + secondNumber; BOOL isThisTrue = 5 > 6; NSInteger count = 0;
In Python that same declaration would be:
number = first_number + 1.23 is_this_true = 5>6 count = 0
It doesn’t matter if you want a integer, float, boolean or even string, that works. Also notice the lack of semicolon. There are no termination characters in Python like C, C++, or Objective C. Finally, the variable convention is underscores instead of capitalization.
While just missing a declaration is no big deal, in Python this is acceptable code:
number = first_number + 1.23 number = 5>6 number = 0 number = 'My number is 0'
The variable number is successively a float, bool, integer and a string. For new programmers, this is probably is nothing to care about. For someone used to typing everything, it’s really annoying and took me a minute to get used to the difference.
In particular, while coding I have to be very careful with the type I assign a variable. Unlike Xcode giving us warnings about type there are no warning because everything is valid. This can lead to some unexpected bugs.
Fortunately, to prevent some of these there is casting. The functions int(x),float(x),bool(x) among others will cast to a type. There is also type checking. the type(x), and isInstance(object,classInfo) will also check classes and types.
Some people like dynamic typing, some don’t. When using Python, it is something that one will have to think about.
Leave a Reply