- Published on
Learning Python Basics as a JavaScript Developer
- Authors
- Name
- Sujan Tamang
- @SujanTa88350485
Table of Contents
Overview
This article is for people who has worked with JavaScript before and also for those people who wants to learn basic Python. In this article, I'll be covering fundamental data types, built-in functions and methods, variables, type conversion and much more.
But before we start, Let's refresh our knowledge of programming language and why to learn Python.
What is a Programming language?
According to Wikipedia, a programming language is a formal language comprising a set of strings that produce various kinds of machine code output.
If you got that, then it's awesome. But if you are still confused with the definition, then let me explain to you in simple terms.
A prgramming language is like a translator which converts your programs that you understand to something that machine understands.
I hope you got that one. It's just a refresh before learning a new programming language. Let's not waste any more time and learn what is Python & why to learn it.
What is Python programming?
Python is an interpreted high-level programming language used for general-purpose software engineering. Initially developed in the late 1980’s by Guido Van Rossum, Python has been around for decades alongside other languages like Java and C. Van Rossum modeled Python after the English language, eliminating unnecessary syntax to make it easier to read and write than other programming languages.
It is also open source, and in recent years has increased in popularity due to its use in data science. Python also has a strong community around machine learning, data modeling, data analysis and artificial intelligence (AI), with extensive resources and libraries built for these purposes.
And yes, the rumors are true. Python is named after the British comedy group Monty Python which makes it more awesome.
So why learn Python?
- Python is extremely versatile, with multiple uses.
- Python is easy to read, write, and learn.
- Python is the fastest growing programming language.
- Python is in high demand for jobs.
- Python has an incredibly supportive community.
Basically, I wanted to learn Python to be a part of its community and use it for machine learning and building backend servers. But you shall have your own reasons. There are much more to why learn Python. You can learn more by researching on your own.
A Quick Note before learning Python
If you want to code along and already have your development environment setup for Python then it's good. Otherwise, We need to install Python on our machine and setup our development environment which is out of scope of this article.
By the way, I'll be using an online IDE so that I can easily write code without any setup. You can also do the same. But If you want to write code on your local environment, it's not too difficult to install and there are many articles and videos out there which might help you.
Three things you need to know is that:
- By installing Python you're installing that translator I talked about.
- After installing Python, I also recommend to install a Code Editor or IDE to write Python code.
- If you install Python from the official Python website, you're going to install CPython.
Now, what the heck is CPython?
CPython is the reference implementation of the Python programming language written in C and Python which is the default and most widely used implementation of the Python language.
If you are confused by this, don't worry. You can skip this and still write code.
I introduced this earlier for you to know what you installed or going to install. And if you have guessed something, then YES you're right. There are other implementation of Python like Jython, IronPython etc.
Finally, from the next topic we are going to learn some Python and do some coding. I hope you're still here so, Let's get started.
Some Common Data Types
Every programming languages have some common data types like numbers, strings & booleans etc. It allows us to design a data structure for our needs. Let's learn about them.
Number
Actually, Python don't have a data type called number like in JavaScript. Instead, there are three distinct type of numbers: integers (int), floating point numbers (float) and complex numbers (complex). Integers are whole numbers and Floats are numbers containing decimals.
We won't be covering about complex numbers in this article. Now, let's look at some examples.
# Intprint(3 + 4)print(2 -1)print(5 * 5)print(2 ** 3)print(7 // 4)print(7 % 4)
# Floatprint(3.5 + 4)print(2 / 4) # produces a float
If you've done some basic maths in school. You could know what we're doing. But I would cover the three operators that are used above.
**
is used to calculate power of the number.//
is used to get the quotient of the division.%
is used to get the remainder of the division.
The
print()
used in above code is a built-in function in Python which just prints the output. There are a lot more built-in functions in Python. We can't cover everything Python provides but you could look at this when you need the full details of the functions and this if you just want to see the summary of functions.
String
Strings are immutable in Python and are almost similar to JavaScript. Let's look at some examples.
# String can use single or double quotesprint('Hello World')print("Good Morning")
# For multi-line stringprint('''Thisis amulti-linestring.''')
You can also add strings in Python. This is called string concatenation.
print('Hello' + ' ' + 'Sir')
String Concatenation is great but can be tedious to work with. If you're a JavaScipt developer then you should have used Template literals and there is something similar to Python called Formatted string literals. This helps us to easily work with dynamic values in strings.
user_name = 'John'user_age = 32
print(f'Hello {user_name}, You are {user_age} years old.')
In the above code, I have used something called variables to store the values 'John'
and 32
.
I'll be covering about it so, don't worry.
If you want to use single or double quotes mutiple times in a sentence, then you need to escape it using escape character \
.
\t
and \n
are also used in below examples which are tab space and new line respectively.
print("It's a \"kind of\" sunny day!")print('\tIt\'s a "kind of" rainy day! \nHope you had a great day.')
There are much more to string manipulation in Python. But I think this much enough for beginners.
Boolean
If you're a JavaScipt developer then you must know that, boolean's are capitalized in Python.
print(True)print(False)
print(2 > 4) # Falseprint(7 <= 10) # Trueprint(20 == 20) # True
Variables
Variable is a concept that exists on all programming languages. so what does it mean?
Variable is a mermory location in a computer program where you can store your data.
user_iq = 190user_age = 190 / 4
Let's see some Best Practices while creating a variable.
- Use snake_case for variables name.
- Start with lowercase/underscore while naming variable.
- Variable name can contain letters, numbers and underscores.
- Python is case-sensitive, so diffenrent variables are created if casing is different.
- Don't overwrite Python keywords like print, int etc. which you'll learn later.
You can also rapidly assign values to the variables.
# 3 new variables are createda,b,c = 1,2,3
Expressions vs Statements
A piece of code that produces some value is an expression.
# Eg.print(100 / 5)
An entire line of code that perfroms some action is a statement.
# Eg.user_age = 20
Type Conversion
Previously, I talked about built-in functions. Some of them are used to convert the types.
print(type(100))print(type(str(100)))print(type(int(str(100))))
type()
is another built-in function which is used to know the type of a value.
str()
, int()
, bool()
, set()
, list()
etc. built-in functions are used to convert one type to another.
Other Remaining Data Types
None
The None keyword is used to define a null value, or no value at all. In JavaScipt, it is similar to null keyword which simply means empty.
List
It is the first data structure out of fourth that we're going to learn.
Data structures are containers that organize and group data according to type.
If you've used array in JavaScript then, it is similar and would be easy to learn.
list1 = [1,2,3]list2 = ['a', 'b', 'c']list3 = [1, 2.5, 'a', True] # mixed
You can access the element you want by using the index it corresponds to.
ecommerce_cart = ['Item 1', 'Item 2']print(ecommerce_cart[0]) # Item 1print(ecommerce_cart[2]) # IndexError: list index out of range
Remember that, index start from 0 and not 1.
You can slice the list to get your desired output using the pattern [start:stop:step]
. This pattern can also be used with strings.
ecommerce_cart = ['laptops', 'desktops', 'mobiles', 'tablets']print(ecommerce_cart[1:4:2]) # ['desktops', 'tablets']
You can also place the list within another list to create an multi-dimensional list or also known as matrix. It is used in machine learning, image processing etc.
matrix = [ [0,1,2], [4,5,6], [8,9,[0]]]
print(matrix[1][2]) # 6print(matrix[2][2][0]) # 0
You can assign list values to the variables easily by unpacking list.
a,b,c,*others,d = [1,2,3,4,5,6,7,8,9]print(a,b,c, others,d) # 1 2 3 [4, 5, 6, 7, 8] 9
There are also something called built-in methods which are similar to built-in functions but they can't be accessed globally.
so, we need to call it using .
on something. Let's see an example.
my_list = ['a','b']
my_list.append('z')print(my_list) # ['a', 'b', 'z']
my_list.pop()print(my_list) # ['a', 'b']
I won't be covering methods as it'll make this article too long. But it is important to know. So, I'll be providing link for you to learn on your own.
Dictionary
It is the second data structure out of fourth in Python.
If you've used object in JavaScript then, it is similar and would be easy to learn.
simple_dictionary = { 'a': 1, 'b': 2}
print(simple_dictionary['a']) # 1
complex_dictionary = { 'a': [1,2,3], 'b': 'Hello', 'c': True, 'd': 7, 'e': 0.5}
print(complex_dictionary['a'][2]) # 3
Here's a link for dictionary methods.
Tuple
It is the third data structure out of fourth in Python. Tuples are immutable lists (i.e. write permission is forbidden and only read access is given). They are performant but not flexible than list. So, think before choosing between tuple or list.
my_tuple = (1,2,3,4,5)
my_tuple[3] = 'a' # TypeError: 'tuple' object does not support item assignmentprint(my_tuple[3]) # 4print(1 in my_tuple) # True
in
keyword is used to know if the element exists in the data type or not.
Here's a link for tuple methods and actually there are only two.
Set
It is the last data structure in Python that we're going to learn. Sets only hold unique values.
my_set = {1,2,3,4,5,5}my_set.add(100)my_set.add(2)
print(my_set) # {1, 2, 3, 4, 5, 100}print(len(my_set)) # 6
len()
is a built-in function that is used to calculate length of a data structure and also strings. As you know by now, index starts from 0 but you must also know that length starts from 1.
Here's a link for set methods.
If you've read Set Chapter in Math class while studying in school then it would be a lot easier to learn this data structure.
An Advice for Beginners
Every beginners tries to read everything they can before moving on to next things. So, they memorize as much as they can. I also did the same. But I realize after a while that this is really a bad habit. I just want to say that you don't need all the information at once. You can move on to new things by just having some basic idea. And never hesitate to say I don't know, if you really don't. Don't lie to others and yourself. Nobody knows everthing and that's why we use google and other websites to help us. Thank you for your time.
Summary
I think this much is enough for the article. I still haven't covered basic topics like conditional logics, loops, functions, scopes and much more. I hope you could learn those basic topics on your own. See you soon and have a good day.