Top 10 Programming Languages to Learn in 2019

ProgrammingPython

Introduction to Python Programming

python-programming-670x335

What is Python?

Python was released in 1991 by Guido van Rossum. It is an interpreted high level language for general purpose programming. 
Python features a dynamic type system and automatic memory management. It supports also supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.

Unlike other programming languages like C, Java, C++ it is easy to learn and use. It is more expressive and understandable and readable, object-oriented, Extensible, and most importantly it open source.

How to install Python?

Before we get started please ensure that you have Python installed in your PC or Mac. To install python follow this official website link. 

Choosing Python Version

Currently, there are two main versions of python, 2.7.x and 3.6.x

In general, Python 2.7.x has more supported libraries than Python 3.x.x. But if you are starting to learn python you may go for version 3.6.x. You may download any of them according to your need. This tutorial uses Python 3.6.2. 

Make sure you select the Add Python 3.6 to PATH option

Make sure you add python to path while installation. This will enable you to call python commands from the Command Prompt.

Which IDE to select?

Now that you have installed Python on your PC next step will be to select a code editor or IDE. There are various code editors out there, but I will suggest you download Visual Studio Code as it is open source and one of the most customizable and smart code editors in the market. The installation process will be different for different OS. You can download and install it according to your OS.

Python Shell

Python is known for its crisp language structure and elegant codes. Let’s see this by writing our first code. Let’s start the python IDLE.

  • Windows Users– If you have only one version of python run python. 
    If you have both Python 2.7 and Python 3 installed, run python for Python 2.7 and/ or py -3 for Python 3.
  • MAC Users- Open your terminal and run python or python3 depending on your installation.
  • Linux Users- Open the terminal and run python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 

Your version may be different depending on which version you installed 

Now that you are here we may run some code

>>> print("Hello World")

This should be your output after you execute the code

Hello World

Python Overview

Variables

In general, variables are the container for data. They are declared in python as VariableName = data. A variable name can be anything except reserved words. 

There are few rules that can be followed while deciding a variable name

  1. It should start with an alphabet or underscore like abc, _foo.
  2. It should not start with a number like 2d, 3mer etc are invalid.
  3. It should not be a reserved word

These are the mandatory rules to declare a variable. There are also some conventions to decide a variable name like CamelCases. One thing that should be kept in mind while deciding a variable name is that the variable name is easily readable for example x=2,y=3 are not a good choice as variable name as num1=2 and num2 = 3 are.

Built-in Datatypes

Python has many built-in data types like integers,string, float,list,dictionary,tuples, and set.

We can use them in our context by declaring them using a variable name. For. e.g..list1 = [] They can be manipulated by using:

  • Operators
  • Data types and functions
  • Functions

Let’s see this by referring some examples.

Numbers

Numbers in python can be integer, float, Boolean or complex numbers. Some examples are:

  • Integers – 2, 5, 0, -3 etc
  • Boolean –  0 or 1
  • Float – 1.2, 4.5, 6.0 all are floats
  • Complex Numbers – 5 + 6j, 4 – 9j etc
Basic operations

Some basics operations which you have already gone through in elementary school

>>> 5 + 8  #Addition
13
>>> 9 - 6  #Subtraction
3
>>> 8 * 9  #Multiplication
72
>>> 8 / 9  #Division
0.8888888888888888
>>> 8 % 2  #Modulus(returns the remainder)
0
>>> 5**2  #raise to the power 
25
>>> num1 = 9
>>> num2 = 4
>>> sum = num1 + num2
>>> sum
13

Basics operations that can be done in python are

  • Addition – 5+8
  • Subtraction – 9-6
  • Multiplication – 8*9
  • Remainder – 8%2
  • Power – 5**2
  • Division – 5/2

Please note that unlike C/C++, python uses **, double asterisk operator for power 

Now let’s recall our high school memories by using some basic algebra. They returns Boolean values. i.e (True or False)

>>> 2 == 3  # Equality check
False
>>> 2 >= 3
False
>>> 3 <= 2
False
>>> 1 == 1
True
>>> 2 != 3
True
>>> 45 > 1
True
>>> 1 < 3
True

Please note that to check equality we use ‘==’ double equal sign and to assign we use ‘=’ single equal to.

Functions

There are many inbuilt functions provided by python to manipulate the numbers. Let’s see them one by one.

>>> float(2) #changes an integer into float
2.0
>>> int(3.44) #truncates the part after the period and returns integer
3
>>> (2.3).is_integer() #Checks is a float is finite
False
>>> (2.0).is_integer() 
True

Strings

Strings are used in python for recording text information such as an address. Python Strings are basically a sequence, i.e. python keeps track of each and every element of the string as a sequence.  

Know more about strings

Basic Operations
>>> "hello" + " world"
'hello world'
>>> "ab" * 5
'ababababab'
>>> a = "hello"  #String Slicing
>>> a[1]
'e'
>>> a[0]
'h'
>>> multiline_string = """ Lorem ipsum """
>>> multiline_string
' Lorem ipsum '
>>> not_escaped_string = "didn't"
>>> not_escaped_string
"didn't"
String Methods
>>> escaped_string = 'didn\'t'
>>> escaped_string
"didn't"
>>> escaped_string.capitalize()
"Didn't"
>>> escaped_string.center(12)
"   didn't   "
>>> escaped_string.count('d')
2
>>> escaped_string.find('d')
0
>>> escaped_string.find('did')
0
>>> escaped_string.format("%12s")
"didn't"
>>> escaped_string.index('d')
0
>>> escaped_string.find('id')
1
>>> escaped_string.isalpha()  #because it also contains "'"
False
>>> escaped_string.replace('d','a')
"aian't"

Lists

Lists are the builtin python sequence. Consider it just like in array of other languages like C,C++ or Java. Now lets dive into some examples to get to know more about lists.

Basic Operations

Python lists can be created in two ways:

  • Use ‘[]’ to declare an empty list
  • Use ‘list()’ to declare an empty list
>>> a = []
>>> b = list()
>>> print(type(a), type(b))
<class 'list'> <class 'list'>
>>> a
[]
>>> b
[]
List methods
>>> list1 = [1,2,3]
>>> list1.reverse()
>>> list1
[3, 2, 1]
>>> list1.sort()  # sorts the list in ascending order
>>> list1
[1, 2, 3]
>>> list1.append(4) # appends an object at last of the list
>>> list1
[1, 2, 3, 4]
>>> list1.clear() # clears the objects in list
>>> list1
[]
>>> list1.append(1)
>>> list1.append(2)
>>> list1.insert(3,0)  # inserts an element at a particular index
>>> list1
[1, 2, 0]

Dictionary

Dictionary is the types of an associative array in python. They are similar to hash-map in Java. Let’s see few examples to understand it better.

Like python lists they can also be declared in two ways.

  • Use ‘{}’ to declare an empty dictionary
  • Use ‘dict()’ to declare an empty dictionary
>>> dict1 = {'key': 'value'}
>>> dict1
{'key': 'value'}
>>> dict1['key']
'value'
>>> dict1.keys()  # returns the keys in the dictionary object
dict_keys(['key'])

Tuples

Tuples are just like python lists unlike lists they have less inbuilt functions and are immutable. Let’s see a few examples:

Like python lists they can also be declared in two ways:

  • Use ‘()’ to declare an empty tuple
  • Use ‘tuple()’ to declare an empty tuple
>>> tuples = ()
>>> tuples.count(2)
0
>>> tuples = (1,2,3)
>>> tuples
(1, 2, 3)
>>> tuples = (1,'a',2)
>>> tuples
(1, 'a', 2)

Loops in python

Python has two loops

  • For loop
  • While Loop

For loop

For loop is a finite loop in which you predetermine the number of times the loop will run. Let’s write a program to print the first 5 natural numbers to make you understand better.

>>> for i in range(1,6):
	print(i)
1
2
3
4
5
>>>

Well, now you may be wondering what is range() and why we gave arguments as 1,6. This is because the range() function returns value from the starting argument to the second last argument.

While loop

While loop is used when you don’t know the number of times the loop will be executed.

>>> i = 1
>>> while(i<=5):
	print(i)
	i += 1

1
2
3
4
5
>>> 

Loops in general have three parts:

  1. Initialization/ increment
  2. Condition Check
  3. Execute

Errors

Python is very helpful in pointing out the error. There are many types of errors in python. Let’s go through few of them.

Syntax Error

>>>  print(1)
    ^
SyntaxError: unexpected indent
>>> if i < 0
if i < 0
        ^
SyntaxError: invalid syntax

Value Error

>>> int('a')
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    int('a')
ValueError: invalid literal for int() with base 10: 'a'

Type Error

Passing an invalid object type in a function generally gives this error

>>> sum(1,2)
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    sum(1,2)
TypeError: 'int' object is not iterable

Error handling

Errors in python can be handled by putting the code inside a try/except block.

>>> try:
	int('a')
except ValueError:
	print('Program ran successfully')

Program ran successfully
>>>

You can see in the above example that we did get a ValueError but with the try/except block, we have successfully handled.

Python’s Power – Packages and Modules

Python has a great collection of packages and libraries. You can import many pre-built libraries to extend the language capabilities. Let’s see few libraries.

  • math: mathematical functions from the standard library of the C
  • datetime: used for manipulating dates and times
  • random: a pseudo-random number generator
>>> import math
>>> math.sqrt(4)
2.0
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 12, 3, 18, 31, 54, 54054)
>>> import random
>>> print(random.randint(3,10))
3
>>> print(random.randint(3,10))
4
>>> print(random.randint(3,10))
4
>>> print(random.randint(3,10))
8

Next Steps

You can plenty of tutorials and blog available online.

The place that truly helped me was MIT’s course, Introduction to Computer Science and Programming, which covers various computer science concepts along with Python. The course can be found at. The Harvard and MIT non-profit online initiative (Edx.org) offers the course in two parts. They are challenging and provide an excellent approach to problem-solving. Both parts are graded.

But the best part to learn python is – Project driven learning approach. You can find a project driven beginner course related to python here at PyBlog. These courses are updated monthly to keep up with changes in Python.

Another source of free learning materials comes from the Python Software Foundation:

Practice makes you Perfect!!

Practice Code

Now that you have learned the basics of Python. Let’s Practice. Open your code editor and copy paste the code and save the file as practice.py. 

###############################################################################
######## Change the variables till all the statements evaluate to True ########
###############################################################################


variable1 = 
variable2 = 
variable3 = 
variable4 = 
variable5 = 
variable6 = 

###############################################################################
##################### Don't Change anything Below this ########################
###############################################################################

# test1 Strings
print(type(variable1) == type(''))
print(len(variable1) < 9)
print(variable1[0] == "a")

# test2 Integers
print(type(variable2) is int)
print(type(variable3) is float)
print(variable2 < variable3)

# test3 Dictionary
print(type(variable6) is dict)

# test4 List
print(len(variable4) == 5)
print(type(variable4) is list)

# test5 tuple
print(type(variable5) is tuple)
print(len(variable5) == 2)
Related posts
Programming

Amazon Price Scraper and Auto Mailer Python App

ProgrammingPython

Top 10 Deep Learning frameworks in 2019 (with comparison)

ProgrammingPython

Python vs R - Data Visualization

Programming

Cython vs Python - Speed up your Python

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Improve Your Python

...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

PyBlog will use the information you provide on this form to be in touch with you and to provide updates and marketing.
%d bloggers like this: