Join Hackr.io to get personalized course recommendations for you.

Best way to learn Python

Posted in Python
Best way to learn Python

If you are a non-programmer, Python could be your starting point as it is on the top of the top programming languages of 2019 list and is also the easiest to learn. If you know any other programming languages, learning Python will be a breeze for you. Except for the syntax differences, the basic concepts of OOP remain the same. In addition, Python has extensive libraries that support almost everything that you want to do.

Python is

  • Readable and easily understandable supports modules and encourages code reuse.
  • Cross-platform language – code once, run anywhere (Windows, Linux, Unix, Mac, etc…)
  • Interpreted language – interpreter executes each line of code one by one, making it easy to debug.
  • Open-source, so you can easily practice anytime you want

Further, Python

  • has great set of standard libraries
  • can be integrated with other languages like Java, C, C++.
  • supports object-oriented programming

With these in mind, let us go through the topics that you need to learn to master Python starting from the basics to advanced topics. By the end of this article, you will know enough Python to start coding, answer interview questions and get a nice job for yourself.

You can install Python from their official page.

Best way to start Learn Python Journey

The best way to learn Python is to implement whatever you read. Just open your laptop, install Python and start coding. You can learn as you go!

But, before you do that, here are some tips to make it easy for you –

  • If you are a non-programmer, have a little extra patience. You will get there for sure. Python is the easiest way to get into programming.
  • Think of your own small application and make your learning around it. Preferably build a simple website using Django. For example, browsing through the list of phones and buying one, purchasing your weekly grocery online, managing employee details etc… If you just read and don’t try what you read, you will not be able to grasp or remember the concepts.
  • If you get an error, that means you are going in the right direction. If you get a lot of errors, that’s great. Every error should make you excited and eager to find the solution. The best learning is through errors and exceptions.
  • Take the help of online courses and books if available. This free course on YouTube is a good way to start.
  • Learn the syntax along the way. Don’t spend too much time on learning the syntax alone. Have a project set up with an IDE like PyCharm, just start coding. You will get to know the syntax as you write more code.
  • Start with a simple project and enhance the functionality as you code. Include more complex concepts as you are able to develop code.

Okay, without any more theories, let us get started.

You might want to skip the first few subtopics if you already know one or two other languages. These will welcome you into the programming world by familiarizing you with common jargons used in most of the languages.

Variables and Data-types

Suppose you want to purchase a phone. You browse through a lot of phones and add one into your shopping cart. How does the computer know where to store your data like handset model, the plan you have chosen and any accessories for example earphones that you have added?

Data is stored in the form of variables. This helps the application to retain and pass the data from the beginning till the end of the application (for example, place order page) where your order ends.

There are different types of data. For example, your phone number will be an integer, the service plan could be a String, a variable to determine if you have any coupons could be a Boolean and so on. Integer, Boolean, String (and some others) are called as data types.

Let us check a simple example –

handset_id = 90993
plan = “MYPLAN199”
print(handset_id, plan)

We can use these variables handset_id and plan throughout the application instead of using hard-coded values.

Operations

Anything we do on the data is called an operation. Addition, subtraction, comparison or logic operations. For example, to compare a user’s new mobile plan and existing plan, we can write something like –

print(new_plan == old_plan)

The double equals is a comparison operator that returns a true or false as output. There are many operators in Python.

Conditions

Let us say a discount is applied to your plan based on some conditions like your monthly usage, choice of handset and several other factors. How does the application automatically check if you are eligible for a discount? By checking if these conditions are met!

if(plan == ‘DISCOUNT30’ and customer_existing):
print(‘You are eligible for discount’)
else if(some_condition):
#some block of code
else
#some other block of code

There are many other conditions in Python like while and for loops. Read this detailed blog to know about conditional statements of Python.

Functions

Sometimes, there are certain functionalities that we may want to reuse, or a piece of code may be so big that it might be a good idea to move it into a separate block and call it whenever needed. Such blocks are called functions. For example, our above code can be moved to a utility file and anyone can use the function.

def check_for_discount(customer_existing):
#function code

def defines the function. When we call the function, we pass the value of customer_existing (in this case). This is called as a parameter. We can pass any parameters to a function.

Object-oriented programming

Most of the top programming languages today are based on OOPS (object-oriented programming concepts) and so is Python. It is a very simple concept and a powerful one. In OOP, everything is considered as an object. A class is an entity of which we create objects as needed.

Watch this cool video to learn about OOPS concepts.

In our handset example, the handset can be a class and all the handset details like model, make, type, features can be its attributes. Whenever a user selects a handset, an object of the Handset class will be created and the details will be filled into its attributes (member variables).

Object Oriented Programming

You can consider a human being as a class – Human. Your attributes can be the name, age, gender and so on. You can consider yourself as an object of the Human class with specific values like name = ‘Mac’, age = ‘22’, gender = ‘M’.

Each class has attributes and methods to get and set those attributes. A class will also have a constructor or init method that will create the object of the class whenever needed.

class Human:
def ___init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender

Try to apply this analogy to our handset class.

class Handset:
def ___init__(self, handset_id, model, manufacture_date, features):
self. handset_id = handset_id
self. model = model
self. manufacture_date = manufacture_date
self.features = features
def printhandsetdetails():
print(self.handset_id, self.model)

Now, let us say a user added a particular handset into their cart. The details can be stored as –

handsetDetails = Handset(“NOKN96”, “2009”, “23-05-2009”, “slim”)

Suppose we want to print these details, we can add a method inside the class to do this and call it as handsetDetails.printhandsetdetails()

Data structures

The term data structure is common to all programming languages. In Python, we call them as a collection. There are different types of collections in Python that make storing and retrieving data, a piece of cake. These also make the program fast and efficient. The 4 main types of collection are –

  • List – the simplest of all data structures, list is an ordered collection, which is also changeable. For example,
featurelist = ["frontcamera", "androidpie", "6GBRAM"]

To access list items, we refer them using the index, and index always starts with 0. featurelist[0] will give you frontcamera.

  • Tuple – is also ordered but not changeable. You cannot add or remove items in a tuple.
  • Set – unordered and unindexed collection. You cannot access set items using index, however can loop through the items or scan through them to check if an item is present.
  • Dictionaries – also called as maps, these are accessed through key-value pairs. They are unordered. For example,
handsetdetails = {
 "name": "Nokia6.1",
 "color": "Black",
 "RAM": "6GB"
}

To get the value, we should access using the key handsetdetails[“name”].

This free udacity course is a good one for you to have a detailed knowledge of data structures and algorithms of Python. If you take this, you will be able to use data structures in any programming language later on.

Learning data structures will help you play with data in Python and build a large-scale application with ease. It will also help you master writing efficient code and dynamic programming.

User inputs

Getting input from user is quite simple. Just using the input() method will get the input from the console.

name = input(‘Enter handset name - ’)

Based on the name received, you can fetch details of the handset and display to the user. Data can be fetched from a file or database using connection.

Connecting to Database

To connect to database, you should install MySQL connector Python (for MySQL) or MongoDB driver like PyMongo. If you are a beginner, go for MySQL as it is most common and good to learn.

This simple tutorial will walk you through steps to connect to the database and fetch necessary details.

File handling

File handling is an important part of any application. Your application might want to read from a file, write onto a file and so on. It is very easy to implement file handling in Python. There are 2 types of files in Python - binary, text. There are 4 types of file operations which we call as CRUD - Create, Read, Update, Delete. For example, we can open a file as -

file = open(“handsetlist.txt”, “w”); 

#this will open the file in ‘w’ i.e. write mode

If we give ‘r’, the file will open in read mode, to add a new row, we use ‘a’ (append). The ‘r+’ mode is a special mode which handles both read and write actions while working with a file.

To read a file, we use file.read() method and to write, yes you guessed it right! We use file.write(“data to write”).

Read about and play with more file handling functions from this crisp and simple link.

So now, you can create individual programs, stand-alone application that gives perfect results. But, how about a scenario where your application can be accessed by multiple people at the same time. For example, a printer that is accessible by various users, how does the printer handle multiple jobs without a deadlock?

Concurrency and Multithreading

There could be situations like the above. Two or more processes waiting for the same resource. Let us say a process A is trying to access a resource R. Now, process B also tries to access resource R. To avoid issues of B overriding the data of A, the processes will be synchronized where-in each process (B, C, D, etc…) is blocked until the previous thread/process A completes using the resource R. This is called mutual exclusion. This means process A locks the resource till the time it is using the resource, and releases it when it is done. The other processes have to wait for their turn of having the lock. But what if process A runs into an issue and is not able to complete its work? What if process A needs something from process B to be completed and B is waiting for A to complete. This is called a deadlock! Deadlock is deadly and you wouldn’t want it in your program.

In a practical environment, it is important to know about multithreading, multiprocessing, and locks. This detailed article will tell you about threads and multi-processing from scratch (with code).

Creating API Services

Let us now take a bigger picture – of the web world, where programs and applications interact with each other, share resources and most importantly, pass requests to each other using the HTTP protocol. Each application that can communicate with another is called a microservice. This means if you want your application to interact with the world, you should know how to expose your services – by creating API! You can easily create API services using Python library – Flask. Watch this series of videos to know-how.

Creating web application

You can now create your own web application using Python. This free tutorial gives you a good step by step way to build a project using Django and Python. Do enroll for this course and learn about Django. Django is a full-stack web framework with which you can create an end-to-end web application in Python. It uses the MVC (Model-View-Controller) architecture and ORM (Object-Relational-Mapping) for data access. There are libraries in Python that fully support ORM and building a web application in an easy manner.

Final word

That is all that takes to be a Python pro. We started from the basic variable and ended up creating a full-fledged web application. If you feel that you are ready to go out and appear for interviews, do read our Python interview questions. Also, This comprehensive blog will give you detailed idea about what books you need as a beginner or advanced Python programmer.

And, most importantly, check out some of these tutorials and go ahead, enroll for some. There are free and paid tutorials both, so you can choose the ones you wish to enroll with.

People are also reading:

Swapnil Banga

Swapnil Banga

Software engineer, hardware enthusiast, writer by avocation and a gamer. Swapnil has been working on Hackr for a large part of his career. Primarily working on Laravel, he is also the author of our React Native Android app. When not in front of a screen, you will find him devouring a novel or listening to heavy metal. View all posts by the Author

Leave a comment

Your email will not be published
Cancel