Switching languages: Funky PY
One person said to me once during my first job interview: "I don't look for C++ programmer or Javascript programmer, I'm looking for programmer. Every language has loop and such constructions. If you know how this function in general, you can get by"
This thesis was a quite insightful for me and guided me through all my jobs and projects. Whenever I needed to start doing something new, I just started working with it, trying to learn new syntax and language details on the way. Sometimes that was harder than I expected (switching from C# to Javascript for instance), but always worked.
Recently I did that for Python. I've heard a lot about this language, but never actually used it. These days I'm starting to write small cloud functions in Python. After initial steps, I decided to read a book about Python to simplify my process of getting into the language. Usually, reading such book would take weeks of time for my. But this one took only 2-3 days! I think the main reason for this is the thesis I started from - the core idea of Python as language is not so different. But there are some interesting differences, which makes language nice and unique.
Here I would like to list the differences between Python and Javascript from the syntax perspective. Such exercise can help Javascript developers (like me) who need to write small things in Python. But I won't touch core language structure and anything about functionality. Just pure syntax.
Common
- Comments in Python are either single line started by # or multi line with 3 double quotes in the beginning and end. Also, multiline comment, placed right after function of class definition, would be used in docstring - automated documentation
# single line comment
"""
Multi
line
comment
"""
- No need to use semicolon in the end of lines
None
instead ofNull
orUndefined
- Tabs are crucial! Python doesn't use parentheses
{}
, instead it strongly relies on indentation (tabs) usage. Every logical block should be indented! - Global variables. Similar to Javascript, there are global variables in Python. Basically, every variable defined outside of function scope is considered as global. But there is a trick, if you use a value type variable with the same name of existing global variable, interpreter considers it as local scope variable and define it separately from global one. If you do want to use global value type variable inside some function, you need to declare it again. For reference type variables - no need to add this step
myGlobalVar = 'test'
def myFunc():
global myGlobalVar
# now I can use global variable inside function
Types
type(x)
returns type of variablex
int(x)
casts variablex
to typeint
. In case if there is number with decimal part, only integer part would be taken.int(3.9
returns 3- Type checking
if not isinstance(x, int):
...
Strings
- Strings are considered as arrays (obviously), but they are immutable in Python. You cannot reassign single element in the string, just access it or iterate over the whole string
str.upper()
returns upper case stringstr.strip()
removes whitespaces from the beginning and end of stringstr.find('...')
returns index of the first occurrence of the substring- String format:
this is arg 1 - %d and arg 2 - %d' % (arg1, arg2)
returns something likethis is arg 1 - 17 and arg 2 - 18'
.%d
is used for integers, other types can be googled
Math operations and overrides
a, b = b, a
short snippet to make variables exchange values without the third temporary variable defined!- Exponentiation:
x = a ** 2
- You can also use + for strings concatenation (obvious, ha?), but also you can multiple strings with *
str = 'Ho!'
tripleStr = str * 3
# now tripleStr = 'Ho!Ho!Ho!'
Function declaration
def myOwnSum(arg1, arg2):
return arg1 + arg2
Ifs
if x == 1:
...
elif x == 2:
...
else:
...
Arrays and Loops
- Standard loop
sum = 0
array = [1, 2, 3]
for x in array:
sum += x
range(5)
returns new array[1, 2, 3, 4, 5]
len(x)
returns length of array or stringarr[0:5]
return a slice of array data from variablearr
, 5 elements from index zeroif x not in arr:
can be used to simplify checking if element is present in arrayarr.append(item)
adds new item to the end of arrayarr.extend(other_arr)
concats to arraysarr.pop()
returns the last element of the array and deletes it from array in the same timearr.pop(index)
returns the element of the array by index and deletes it from array in the same timedel arr[index]
deletes element from the array by indexarr.remove(item)
deletes element from the array. In this case we need to provide actual element. The executing instruction will iterate over array and removes the first one, which is equal to provided elementarr = list(str)
converts string into array of single symbol stringsarr.sort()
sorts the array. Note, that this call changes the array, not returning new one
Dictionaries
I got an impression that dictionaries in Python have a special place. They are not just dictionaries or maps as in Javascript for instance. Dicts are also used as objects to carry data with key access. Something like JSON, actually.
- Create a dictionary:
d = dict()
ord = {}
- Access value from dict:
x = d['key']
Tuples
Tuple is something hard to understand in the beginning. By definition this is something as immutable array (not necessary with length of 2, can be more).
t = ('a', 'b', 'c')
Why they added it? This is example, when a book can help. According to information I have found, tuples are used in scenarios like:
- return values for functions. When We need to return several items, but language allows to return only one and we don't want to introduce a class for this case
- function input arguments when we don't know amount of the arguments beforehand.
def funcAll(*args):
args here is tuple! - key for a dictionary, when we need to use several different values as key without additional code
- for strange way of reducing code amount:
def accessFunc(id, env, user):
... # check access
def main:
tpl = (15, 'prd', 'user name') # imagine we get it from some func
hasAccess = accessFunc(*tpl) # scatter tuple into regular args for function
Exceptions
- To raise exception:
raise 'error...'
... literally like english sentence - To catch:
try:
... # code block
except:
... # catch block
Classes
Finally we get to the most interesting part => classes! This part brings some little surprises, but after initial disbelief, I found it as quite simplistic and smart:
- class body is indented as everything in Python
- no constructor,
__init__
function instead - no
this
, instead every function hasself
variable as the first argument. If function will be called for some instance - self will receive reference to that instance. Otherwise - if function was called statically, self will be None - No actual class members definition, only initial assignment in
__init__
function
import math
class Point:
"""
Geometrical point representation
"""
def __init__(self, x, y):
self.x = x
self.y = y
def getDist(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
"""here we overide toString function"""
return 'Point (%d, %d)' % (self.x, self.y)
def __add__(self, other):
"""here we overide + operation"""
return Point(self.x + other.x, self.y + other.y)
- inheritance is also present in Python
class Child(Parent):
Other interesting built-in types
Python is beloved but lots of developers because it's code is usually readable and it has lot of handy stuff by design. I will list couple of them without digging into details:
Set
- Python version of hash map. The main thing of this data structure - no duplicates allowed. fors = {1, 2, 2, 3}
result will be{1, 2, 3}
Counter
- data structure to count amount of provided distinct elements. Can be used for strings or arrays. ForCounter("mississippi")
returnsCounter({'i': 4, 's': 4, 'p': 2, 'm': 1})
. Basically, it iterates over input elements one by one and collects counts for each.
Conclusion
After I completed reading the book, I still had impression that Python is pretty similar to other languages like Javascript. Python is interpreted language, dynamically typed, easy to read and kind of simplistic. It is not necessary to study for years to start doing something with Python.
But in the same time, I have got much better impression why Python become such popular language. There are plenty of out of the box things, smart way of class definitions and usage of self
variable and other small things, which makes work with quite nice! Would be better if there was a language like TypedPython... but maybe I want too much!
Happy coding!