From Javascript to Python

I’m currently learning javascript full stack development at Full Stack Academy, and while I’m not an expert yet, I wanted to see if it was easier to learn other programming languages after you’ve dived into one. Since I’ve wanted to learn python as well, I’d thought I’d start there.

Quick Setup: My mac already came with python 3.7, but you can get the latest versions here: https://www.python.org/downloads/ and you can check your version by typing in “python — -version” in your terminal. Also if you install a newer version, you might want to setup an alias so that a “python” command will also refer to the updated version instead of an old version. To do that, in your terminal you can type in “nano ~/.bash_profile” and add in “alias python=python3”. Just control+X to save, “y” to confirm and enter to exit, and close your terminal window and open again. Otherwise, to execute your commands, just use “python3” instead of “python”.

One of the basic differences is how to print to your console, in Javascript, you use “console.log” but in python, you just use “print.” In my terminal window, after typing “python” an interactive prompt will show up, allowing us to write and evaluate one line of python at a time. Easy-peasy.

The interactive prompt is great, but we will eventually want to be able to execute multiple commands so let’s make a file instead. I used the instructions here: https://code.visualstudio.com/docs/python/python-tutorial to use python in VSCode and saved a file with .py extension. Once saved I can run my file with “python path/to/file.py”

At any time, you can always use the dir function to showcase a list of methods available to a variable, like print(dir(‘Hello World’)) or get more info with help and the type, as in print(help(str)) or narrow down your search with the method name, as in print(help(str.methodname)).

Working with Strings:

Here, I’ll showcase the main differences with string between JS and Python. One of the main differences you’ll see below is variable declaration. With python, you don’t need to declare a type (like JS “let”, “const”, or “var”), all you need is the assignment operator (‘=’) and the name. Whereas JS uses camelcase naming conventions, python generally uses lowercase words separated with underscores.

FYI, you can use single quotes or double quotes, just remember that a single quote will be closed automatically with another single quote, the same goes for double quotes.

Javascript:
let/const/var newStr = 'Hello World'
applying console.log() to each of the below:
1. newStr.length prints '11'
2. newStr.slice(0,3) prints 'Hel'
3. newStr.slice(1) prints 'ello World'
4. newStr.toLowerCase() prints 'hello world'
5. newStr.toUpperCase() prints 'HELLO WORLD'
6. newStr.indexOf('e') or newStr.search('e') both print 1, the index of the first 'e', -1 is default
7. String(number) or (number).toString() will convert a number to a string
Python:
new_string = 'Hello World'
applying print() to each of the below:
1. len(new_string) prints '11'
2. new_string[0:3] returns 'Hel'
3. new_string[1:] return 'ello World'
4. new_string.lower() returns 'hello world'
5. new_string.upper() returns 'HELLO WORLD'
6. new_string.find('e') returns 1, the index of the first 'e', with -1 as a default
7. python also has a count: new_string.count('l') prints 3
8. str(number) will convert a number to a string

String methods, cont:

Concatenation:
Javascript:
1. using "+" or "+="
2. using the concat() method
3. using console.log() and separating strings with ","
4. using repeat() method if you needed multiples of the same string
Python:
1. using "+" or "+="
2. using print() and separating strings with ","
3. using * as in "hi "*3 will print "hi hi hi "
Replace:
Javascript:

1. using replace() method
2. using ES6 template literals:
let a = 'apples'
let b = 'pears'
console.log(`I like ${a} and ${b}.`) prints "I like apples and pears."
Python:
1. using replace() method
2. using format()
a = 'apples'
b = 'pears'
print('I like {} and {}.'.format(a,b)) prints "I like apples and pears."
3. using an f' string
print(f'I like {a} and {b}.') also prints "I like apples and pears."
with f' string you can actually write code in the placeholder like you can with JS ES6 template literals

Working with Numbers:

Next up, we’ll work with numbers. Python primarily deals with integers and floats, where an whole number is type: integer and a decimal is type: float.

The following arithmetic operators are shared between the two languages :+, -, *, /, **, %. Python also has floor division: //, which drops the decimal (rounds down to nearest integer), but it does NOT have the increment (++) and decrement(- -) operators. Likewise, both have assignment operators (=, +=, -=, *=, /=, **=. %=), with Python also have the //= option.

Comparator operators are fairly similar as well. Python doesn’t have the strictly equal/not equal and ternary operators that JS has (===, !==, ?) but otherwise both have (==, !=, >, <, >=, <=).

Logical operators are not symbol based in Python. Instead of using &&, ||, and ! for and, or, and not, Python literally uses the words “and”, “or”, and “not”.

Bitwise operators are the same for both languages.

Python has identity operators “is” and “is not” to be used in cases when checking if two variables are located in the same part of memory. Another option to check memory location is to use the id() method, which takes a variable and will return the actual memory address used to store the value of that variable.

Javascript:
Number(), + before string, or *1 converts a string to number
parseInt() converts a string to an integer
parseFloat() converts a string to a decimal
Math.abs() return absolute value of a number
Math.round() return number rounded
Math.floor() returns number rounded down
Math.ceil() return number rounded up
Python:
int() converts a string to an integer
float() converts a string to a decimal
abs() return absolute value of a number
round() return number rounded

Lists, Tuples, Sets, and Dictionaries:

If we wanted to store multiple values in a variable in JS, we would use objects, which can be broken down into arrays (list-like objects) and objects (key-value pairs). (Functions are also an object, but thats another topic). There’s also a concept of mutability, or whether values in the variable can be changed. We can affect this by deciding how to declare our variables (let, const, or var) or by which methods we use on our variables. Another consideration is that arrays and objects can have duplicate values, but objects cannot have duplicate keys.

In Python, the following are used to collect values:

List: collection that is ordered and changeable, allows for duplicates.
Tuple: collection that is ordered and unchangeable, allows for duplicates.
Set: collection that is unordered and unindexed, no duplicates allowed.
Dictionary: collection that is unordered, changeable, and index

Lists:

In the below, I’ll declare a list with brackets [] and apply some methods to showcase use. You can also declare using the list keyword: vegetables = list([‘carrot’, ‘cauliflower’, ‘brussels sprouts’]). Notice the brackets within parans here.

vegetables = ['carrot', 'cauliflower', 'brussels sprouts']
vegetables2 = ['cucumber']
Retrieval:
1. len(vegetables) returns 3
2. vegetables[0] returns 'carrot'
3. vegetables[-1] returns 'brussels sprouts'
vegetables[0:2] returns ['carrot', 'cauliflower'] like JS array slice method
4. vegetables[1:] returns ['cauliflower', 'brussels sprouts']
5. vegetables.index('cauliflower') returns 2
6. print('carrot' in vegetables) return a boolean True
7. for numeric lists, there are also min(), max(), and sum() methods
Mutation:
1. vegetables[0]='carrot2' will change the 0 index to 'carrot2'
1. vegetables.append('broccoli') will add to the end of the list like JS array push method ie vegetables is now ['carrot2', 'cauliflower', 'brussels sprouts' 'broccoli']
2. vegetables.insert(0,'onion') will insert broccoli at the start of the list. Now, vegetables is ['onion', 'carrot2', 'cauliflower', 'brussels sprouts', 'broccoli']
3. vegetables.extend(vegetables2) will add the values in vegetables2 into vegetables. Now, vegetables is ['onion', 'carrot2', 'cauliflower', 'brussels sprouts', 'broccoli', 'cucumber']. (insert here would insert the entire vegetables2 list into vegetables, not just the value(s))
4. vegetables.remove('brussels sprouts') will remove 'brussels sprouts' from vegetables
5. vegetables.pop() will remove and return the last item of the list like the JS array pop method
6. vegetables.reverse() will reverse the items in vegetables
7. vegetables.sort() will sort the items in vegetables in alphabetical or numerical ascending order vegetables.sort(reverse=True) will sort in the opposite order

Looping over a List:

Looping over a List in python resembles looping over an object keys in JS. As a side note, to designate a block of code in Python, you must indent each line of the block by the same amount — the typical amount is four spaces.

for item in vegetables:
print(item)

The above will print each item in vegetables. Just like in JS, you don’t need to use the word “item”, you can choose any word to represent each item in the List. The enumerate option below can be used to access, or in our case, print, both the item and the index. You can also pass in a second argument to start the index at a certain number like ‘start=1’.

for index, item in enumerate(vegetables):
print(index, item)

List methods, cont:

1. ', '.join(List) will return a new string equal to the List joined by the prefix, in our case ', '
2. .split(' ,') will return a new List equal to a string split by the parameter

Tuples:

Tuples are pretty much the same as Lists, but they are immutable. You designate a Tuple by using parans () or using the tuple keyword ie tuple_example = tuple((itemA, itemB,…)). Notice the double parans here.

tuple_example = ('Apple', 'Orange')

We can use any of the List methods that access values in the tuple as well as looping over a Tuple, just nothing that mutates the values.

Sets:

Sets are defined with the set keyword ie new_set = set([itemA, itemB, …]) but will show up in curly braces {} in prints . To review, they are unordered, so printing out a set will usually return the items in a different order. The main use for Sets are to test whether a value is part of a Set or to get rid of duplicate values. Sets are optimized to confirm if items exist in a collection.

Set Methods:

letters_set = set(['a', 'b', 'c'])
more_letters_set = set(['b', 'c', 'd'])
1. print(letters_set.intersection(more_letters_set)) will print {'b','c'} in any order
2. print(letters_set.difference(more_letters_set)) will print {'a'}
3. print(letters_set.union(more_letters_set)) will print {'a', 'b', 'c', 'd'} in any order

Dictionaries:

Dictionaries in Python are very similar to objects in JS, except keys can be any immutable type whereas object keys in JS are converted to strings. Dictionaries are declared with curly braces {}.

animal = {'species': 'Tiger', 'name': 'Tony', 'age': 3, 'color': ['orange', 'black'], 1: 'mammal'}
Retrieval:
1. print(len(animal)) prints 5
2. print(animal['species']) prints 'Tiger'
3. print(animal[1]) prints 'mammal'
4. print(animal[2]) prints a keyerror
5. print(animal.get('type')) prints 'Tiger'
6. print(animal.get(2)) prints 'None' instead of a keyerrorprint(animal.get(2, 'No Key')) prints 'No Key'
7. print(animal.keys()) prints dict_keys(['species','name','age','color',1])
8. print(animal.values()) prints dict_keys(['Tiger','Tony',3,['orange','black'],'mammal'])
9. print(animal.items()) prints dict_items([('species': 'Tiger'), ('name': 'Tony'), ('age': 3), ('color': ['orange', 'black']), (1: 'mammal')])
Mutation:
1. animal['genus'] = 'panthera' will add a new key-value pair or update value of an existing key
2. animal.update({'name': 'Aslan', 'age': 2}) will change the name to 'Aslan' and age to 2 and keep all other key-value pairs the same
3. del animal[1] will delete the 1:'mammal' pair from animal
4. animal.pop('age') will remove the 'age': 25 pair from animal and return 25 as a value

Looping:

animal = {'species': 'Tiger', 'name': 'Tony', 'age': 3, 'color': ['orange', 'black'], 1: 'mammal'}
for key in animal:
print(key)
will print:
species
name
age
color
1
for key, value in animal.items():
print(key, value)
will print:
species Tiger
name Tony
age 3
color ['orange', 'black']
1 mammal

If, Else, Elif Statements:

If, else, and elif statements are fairly similar between JS and Python after accounting for syntax. Below I am showing a JS if, else, elif statement and then translating into Python for comparison. The comparator and logical operators mentioned above can be used test further statements.

Javascript:
let studentA = 'John'
let studentAEnrolled = false
let studentAPlans = 'student next semester'
if(studentA==='John' && studentAEnrolled){
console.log('is student')
} else if (studentAPlans === 'student next semester'){
console.log('enrolling')
} else {
console.log('not a student')
}
will print 'enrolling'
Python:
student_a = 'John'
student_a_enrolled = False
student_a_plans = 'student next semester'
if student_a=='John' and student_a_enrolled:
print('is student')
elif student_a_plans == 'student next semester':
print('enrolling')
else:
print('not a student')
will print 'enrolling'

Loops and Iterations:

In addition to loops mentioned above, like JS, Python also has while loops, with break and continue keywords.


Its exciting to see how much easier it is to understand the basics of new programming languages after you’ve learned your first one. The real skill is not necessarily the syntax and keywords, but the ability to analyze and solve problems and being familiar with the flow of information from the computer’s point of view.

My next plan is to review functions in Python and do a similar comparison.