Switching languages: Funky PY

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 of Null or Undefined
  • 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 variable x
  • int(x) casts variable x to type int. 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 string
  • str.strip() removes whitespaces from the beginning and end of string
  • str.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 like this 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 string
  • arr[0:5] return a slice of array data from variable arr, 5 elements from index zero
  • if x not in arr: can be used to simplify checking if element is present in array
  • arr.append(item) adds new item to the end of array
  • arr.extend(other_arr) concats to arrays
  • arr.pop() returns the last element of the array and deletes it from array in the same time
  • arr.pop(index) returns the element of the array by index and deletes it from array in the same time
  • del arr[index] deletes element from the array by index
  • arr.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 element
  • arr = list(str) converts string into array of single symbol strings
  • arr.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() or d = {}
  • 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 has self 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. for s = {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. For Counter("mississippi") returns Counter({'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!