python tutorial for beginners
Programming language concept. System engineering. Software development.
  1. What is Python and how Python works?
  2. What is Python used for?
  3. How to download Python?
  4. Why Python?
  5. R vs. Python
  6. How fast can you learn Python?
  7. What are the top Python IDEs
  8. Which is the best IDE for Python?
  9. How to power Jupyter Notebook?
  10. Functionalities in a Python Notebook (Jupyter)
  11. Standard Data Types in Python
  12. Flow Control Statements
  13. Creating Functions in Python
  14. Learn Simple Commands by Using Python as a Calculator
  15. Data Manipulation with Pandas

What is Python and how Python Works?

Python is a high-level, object-oriented programming language. Most beginners in the development field prefer Python as one of the first languages to learn because of its simplicity and versatility. It is also well supported by the community and keeps up with its increasing popularity. In this Python Tutorial for beginners, we will learn the basics of Python as a programming language, and understand how to get started with it. We will see how to download and install Python and use the popular IDEs to begin coding. We will also discuss jupyter functionality in detail.

What is Python used for?

Next time you are browsing through Google, indulging in your daily dose of Instagram, spending hours watching videos on Youtube, or listening to your favourite music on Spotify, remember that all of them use Python for their programming needs. Python has various uses across applications, platforms, and services. Let us talk about a few here.

Web Development

top Python web frameworks - python tutorial for beginners

The large selection of pre-built Python libraries makes web development a much simpler task. Writing a Python code is less time-consuming due to its clean and simple syntax. This helps with quick prototyping accelerating the ROI of commercial products. The built-in testing frameworks help in shipping bug-free codes. A large selection of well-supported frameworks help in facilitating speedy implementation without compromising on the performance of the solution.

Internet of Things

For the sake of simplicity, let us consider the Internet of Things to be the ‘physical objects connecting an embedded system to the internet’. It plays a vital role in projects that involve big data, machine learning, data analytics, wireless data networks, and cyber-physical systems. IoT projects also deal with real-time analytics.


A programming language should be a bold choice keeping in mind the aforementioned fields of application. This is where Python ticks off all the check-boxes. Additionally, Python is also scalable, expandable, portable, and embeddable. This makes Python system-independent and allows it to accommodate multiple single board computers, irrespective of the operating system or architecture.

Python tools for IoT under python tutorial for beginners


Also, Python is excellent for managing and organising complex data. It is particularly useful for IoT systems that are data-heavy. Another reason for Python to be the ideal programming language for IoT applications is its close relation with scientific computing.

Machine Learning

Machine Learning has offered a whole new approach to problem-solving. Python is at the forefront of Machine Learning and Data Science due to the following reasons:

  • Extensive open-source library support
  • Efficient and precise syntax
  • Easy integration with other programming languages
  • Python has a low entry-point
  • Scalable to different operating systems and architectures

Here is a Python Tutorial video for you by Great Learning.

How to download Python?

If you are a Windows user and if you have installed Python using Anaconda distribution package which is available at Anaconda.org, you need to go to “Download Anaconda” and then download the latest version for Python 3.6.

Once you download this, it is a pretty simple and straightforward process to follow, and you will have Python installed for you. The next step is to power up an IDE to start coding in Python.
So once you install Python, you can have multiple IDEs or text editors on top of your Python installation.

For text editors, you can use something like Sublime or Notepad++. If you are comfortable using an Integrated Development Environment, then you can use Jupyter. Also, there are other options like Wingware, Komodo, Pycharm, and Spyder.

There are multiple packages available in Python. Some of the instrumental libraries are numpy, pandas, seaborn for visualisation and scipy for calculations and statistics. Others are xlrb, openpyxl, matplotlib, and io.

 

Why Python?

Python has become the most preferred programming language for enabling data science and machine learning applications. Of course, Python has its advantages; it is swift as compared to other programming languages, even R for that matter.

We can easily say that Python is a swift compiler. Since it is a Java-based programming language, you will be able to extend its applications beyond analytical research, analytical modelling, and statistical modelling. You will be able to create web applications using Python and integrate these web applications directly to your analytical models in the background.
Python is also very easy to integrate with other platforms and other programming languages. It has a common object-oriented programming architecture wherein existing IT developers, IT analysts, and IT programmers find it very easy to transition to the analytics domain.
Because the structure of coding in Python is object-oriented programing architecture, it has excellent documentation support.

7 Reasons Why You Should Use Python

  1. Readable and Maintainable Code
  2. Multiple Programming Paradigms
  3. Compatible with Major Platforms and Systems
  4. Robust Standard Library
  5. Open Source Frameworks and Tools
  6. Simplified Software Development
  7. Test-Driven Development
7 reasons why you should use Python - python tutorial for beginners

R vs Python?

R was developed for statistical analysis applications; on the other hand; Python was developed as a general-purpose programming language. Both of these are essential for those who work with large data-sets, solve machine learning problems, and create complex data visualizations.
Let us have a look at the differences between R and Python

Read more about the difference between R and Python, and which is a better alternative.

How fast can you learn python?

The ease of learning is the main attribute behind Python’s popularity. It is a simple and type free programming language and hence easy to learn. The time taken to learn the language depends on the level you want to achieve with Python. Also, the learning curve could be shorter or longer depending on individual ability.

One would require 6-8 weeks to learn the basics of Python. This will include learning the syntax, key-words, functions and classes, data types, basic coding, and exception handling.
Advanced Python skills are not necessary for all Python professionals. Depending on the nature of your work, you can learn skills such as database programming, socket programming, multithreading, synchronisation techniques etc.

The highly sophisticated Python skills include concepts of Data Analytics, hands-on experience of the required libraries, image processing etc. Each of the specialised skill would need around one week to master.

Read our blog on top 50 interview questions for Python to test your knowledge. It will give you an idea about how much you know about Python and what else is there to learn.

What are the top Python IDEs?

There are 7 top IDE’s for Python

  1. Spyder
  2. PyCharm
  3. Thonny
  4. Atom
  5. Jupyter
  6. Komodo
  7. Wingware


Top 7 Python IDEs - python tutorial for beginners

Which is the best IDE for Python?

Jupyter is the best IDE for Python and one of the most widely used IDE for Python. Let us have a look at how to set-up the Jupyter Notebook. Also, let us see what the functionalities of a Jupyter Notebook.

How to Power Jupyter Notebook

Below are the guided steps to power up a Jupyter notebook:

  1. Open the Anaconda prompt. This is available to you if you have done the installation through the Anaconda installer. 
  2. Once you open the Anaconda Command Prompt, you will see a default path assigned to you. This is the username for the computer that you are using.
  3. Add the folder paths to this default path (e.g., cd Desktop → cd Python), where you want to open the notebook
  4. Once you set the path, add the Jupyter notebook using the command jupyter notebook
    setting up a jupyter notebook - python tutorial for beginners
  5. Hit enter. This will open the notebook in your local host, i.e., your system
  6. The path described in the Anaconda prompt will now come on your jupyter notebook home page
  7. Next step is to open a new Python Notebook. This is your environment to carry out all the coding. You can rename the new notebook (untitled) to what you want and hit ‘rename’.
creating new python notebook - python tutorial for beginners


Keep the anaconda prompt active, the one which you used to power up your Jupyter notebook, while you are working with your Jupyter in your local. If the anaconda prompt is closed, the python is no longer running on your system, and the kernel gets disconnected.

Functionalities in a Python Notebook (Jupyter)

File options in Jupyter notebook - python tutorial for beginners
downloading a Jupyter notebook - python tutorial for beginners

There are multiple options on the toolbar, i.e., File, Edit, View, Insert, Cell, Kernel, Widgets and Help. Let us have a look at some of the features and functionalities one by one.

File Options

Save and Checkpoint – Setting a Checkpoint is a fascinating concept. The file is Autosaved at regular intervals, and by setting a check-point, you can skip back a few auto-saves to the set checkpoint. This helps in case you made a mistake in the past couple of minutes or hours. You can always revert to a more stable checkpoint and proceed with your code from there, rather than starting from scratch. 

Download as – There are different ways in which you can download a Jupyter Notebook. First is the Classic Notebook, which is the ipynb extension. Before being called a jupyter notebook, it was an Ipython notebook. That is why this extension.
Then you have your .py extension. Save the file with .py extension, and you can import the same to a different IDE for easier use. 

Close and Halt – This command closes whatever kernel is running at this particular point in time and halts all the processes.

run cells in Jupyter notebook - python tutorial for beginners
keyboard shortcuts in Jupyter - python tutorial for beginners

Edit Options

It includes Cut Cells, Copy Cells, Paste, Delete, Splitting a Cell, Moving up, down, so on and so forth.

So, What is a cell?
Cells are nothing but the code that you type in the dialogue box present on the window. This is a cell, where you type in your code — each cell when run will give you an output.

To run this particular piece of code, you can either click the specific option which says, Run cell or the shortcut key for the same is Shift + Enter

If you want to explore the other available shortcut options, you can get under Help in Keyboard Shortcuts. 

You can cut these cells, paste them later on. You can merge, split, so on and so forth. These are simple items.

View Options

You can Toggle your Headers, Toolbars, and Line numbers as well. 

Insert Options

These are basic insert operations. You can insert a cell above or below as per the requirement of your code. 

cell types in Jupyter - Python tutorial for beginners
what is markdown - python tutorial for beginners

Cell Options

If you hit Run All, it runs all the cells that are present in this entire workbook. When you click ‘Run All Above’, it runs all the cells above the selected cell. Similarly, if you click ‘Run All Below’, it runs all the cells that are below the selected cell.

The different types of cells, i.e., Code, Markdown and Raw Convert Files.
One exciting feature that we will be using much in our code files is something called Markdown file. A markdown is nothing but converting whatever you have typed in a cell into a text message.

The cells that you have converted as a Markdown will not be run or considered as a line of code. When you run this cell, it is taken as a text field, and the output is text too. No computation is carried out on this cell.

help options in Jupyter - python tutorial for beginners

Help Options

Here you can see the usual libraries and packages that are available.

You can click on these options, and it will open a guidebook or the reference book, where you can have a look at the various methods that are available within the selected package.
There are various other options you can experiment with when you are working with Jupyter.

Standard Data Types in Python

Python supports five standard data types which further might have sub-types. The data types that are used to define the operations possible on them and the storage method for each of them. These five data types are:

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary

Let us have a look at all these data structures and understand how to use them with examples:

Numbers

This data type stores numeric values where Python creates a number object and a number is assigned to a variable.

Example:

a=4
b=6

Here, a and b are number objects.

Python supports four types of numeric data; they are-

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers with imaginary number represented with ‘j’)

Lower case L can be used in case of long integers, however, upper-case L should always be used to avoid confusion.

String

A sequence of characters which are represented in quotation marks are known as a string. A single, double or triple quotes can be used to define a string in Python. If string handling needs to take place, there are inbuilt operators provided. This makes it straightforward and easy to use.

Example: “hello” +” python” will return “hello python”

The operator * is called a repetition operator. The operation “Python ” *2 will return “Python Python “

Let us take a look at another example-

str1 = 'hello javatpoint' #string str1   
str2 = 'how are you' #string str2   
print (str1) #printing first two character using slice operator    
print (str1) #printing 4th character of the string  
print (str1*2) #printing the string twice 
print (str1 + str2) #printing the concatenation of str1 and str2    

Output:

he  
o 
hello javatpoint hello javatpoint
hello javatpoint how are you

List

A list can contain data of different types, it is similar to arrays in C. Items which are stored in the list are separated with a comma and should be enclosed within square brackets [].

To access data from a list, slice operators should be used. Repetition operator (*) and concatenation operator (+) work the same way in strings as well as list.

Take a look at the following example-

l  = 
print (l)
print (l) 
print (l)
print (l + l)  
print (l * 3)      

Output:

  
 


Tuple

There are many similarities between tuple and list. Tuple contains the collection of items of different data types, these items are separated with a comma (,) and need to be enclosed within parentheses ().

The size and value of items in a tuple cannot be modified since it is a read-only data structure.

Let us take a look at one example-

t  = ("hi", "python", 2)  
print (t)  
print (t)  
print (t)  
print (t + t)  
print (t * 3)   
print (type(t))  
t = "hi"  

Output:

('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t = "hi";
TypeError: 'tuple' object does not support item assignment 

Dictionary

A dictionary is like an associative array where each key stores a specific value. It is an ordered set of key-value pair items. A key is capable of holding any primitive data type. Value is an arbitrary Python object. Each item in a dictionary is separated using a comma and is enclosed within curly brackets {}

Let us take a look at the following example-

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
print("1st name is "+d)
print("2nd name is "+ d)  
print (d)  
print (d.keys())  
print (d.values())  

Output:

1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}


Flow control statements

Conditional statements (if-else statements)

These commands help you make decisions based on conditions such as ‘if’ a specific condition occurs then you have to perform a set of operations, ‘else’ you have to perform another set of operations.

Let us see how it works:

First, we will define some variables and assign values to them. Next, we will perform some basic ‘if’ ‘else’ operations on these variables.

a=10
b=20
if (b>a):
    print (b is greater than a) 

Output

b is greater than a

In the above computation, the if condition is true hence we get the output. Now, let us try ‘if’ function with a false statement.

if (a>b):
    print (“a is greater than b”)

For this statement, we will not get an output because the if condition stands false.

Now, let’s include the else statement.

if (a>b):
    print (“a is greater than b”)
else:
    print (“b is greater than a”)

Output:

b is greater than a

Next, let us explore the ‘elif’ function for multiple conditions:

a=10
b=20
c=30
if (a>b) & (a>c):
    print (“a is the greatest”)
elif (b>a) & (b>c):
    print (“b is the greatest”)
else: 
    print (“c is the greatest”)

Output:

c is the greatest

You can also implement if and else functions on the different data structures such as tuple, list, string, etc. Let us look at an example with a list.

l1 = 
if l1==10:
    l1=100
l1

Output:

Looping (while and for statements)

Looping statements are used to repeat a task multiple times. Let us look at how it works.

First, we will define a variable and assign a value to it. Next, we will implement ‘while’ function to it.

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

Output:

1
2
3
4
5

So, what is happening here? Since, i=1, which is less than or equal to 5, the while loop stands and the value of ‘i’, i.e., ‘1’ is printed. As per the next command, the value of ‘i’ will be updated to ‘2’.

Again, as ‘2’ is less than or equal to ‘5’, we will again enter the while loop and print the value of ‘i’, which is now ‘2’. This goes on until the value of ‘i’ becomes ‘5’. After that, when the value of ‘i=6’, i.e., it is not less than or equal to ‘5’, the while statement stands false and hence the computation stops there. 

Let us take another example where we have to print the table of ‘2’ to ten values. Let us have a look at how to use while loop for the same.

i=1
n=2
while(i<=10):
    print (n, “ * ”, i, “ = ”, n*i)
    i=i+1

Output:

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Just like conditional statements, you can also implement while functions on the different data structures such as tuple, list, string, etc. Let us look at an example with a list.

li=
i=0
while i<len(l1);
    l1=l1+100
    i=i+1
l1

Output:

Next, let us take a look at where and how to use a for loop. For loop is used to iterate over a sequence, let us head to the code to understand the functionality of the for loop.

l1 = 
for i in l1
    print(i)

Output:

blue 
green 
red

Now, let us see how to create nested for loops, i.e., a for loop inside a for loop.

color = 
item = 
for i in color:
    for j in item:
        print(i,j) 

Output:

green chair
green book
green phone
yellow chair
yellow  book
yellow  phone
pink chair
pink book
pink phone

So this is all about the flow control statements. You can apply these functions and loops in many ways as required for the type of data you are working with and the type of problem you are trying to solve. 

Creating Functions in Python 

A function is a block of code that is reusable. It is used to perform a single, related action and one can directly call the function when they need to perform that action, often as a part of a bigger code. Just call the function and input required values to the variables and hence eliminate the need for writing lengthy codes every time you need to perform the same action.

To create functions in Python, we will use the ‘def’ method. Any input parameter or arguments need to be placed inside the parenthesis with the functions name while defining it. The code block within every function starts with a colon (:) and is indented. Finally, return exits a function. Look at the example below.

 def add_10(x):
     return (10+x)

Let us see what output we get when we invoke this function.

add_10(5)

Output:

15

Let us have a look at another example of defining a function using if and else.

Learn Simple Commands by Using Python as a Calculator

To insert a comment in Python, start the sentence with the hash character, i.e., #. A comment may appear at the start of a line. It might also follow a code or a white space. Comments are explained below with the help of some examples.

 # This is a comment
counter = 100     # This is a comment which follows a code
                  # This is a comment which follows a white space
text = "# This is not a comment as the hash character is inside the quotes."

Let us run some simple commands. Start the interpreter and wait for the primary prompt, i.e., >>>. Let us now see some simple commands and their results. Here are the basic mathematical operations such as sum, difference, multiplication, and division.

>>> 2 + 2
4
>>> 50 - 5*4
30
>>> (50 - 5*4) / 6
5
>>> 8 / 5
1.6

The division always provides a floating value as an output. If you want to display the integer result and remainder separately, the command would include “//” to display integer value after division, and % will display the remainder.

>>> 16 / 3
5.333333333333334
>>> 16 // 3
5
>>> 16 % 3
1

In Python, you can use ** to calculate powers.

>>> 5 ** 2
25
>>> 3 ** 4
81

Next, the symbol (=) is used to assign values to a variable.

>>> height = 20
>>> width = 9 * 5

When working in the interactive mode, the last printed value is assigned to the variable (_), i.e., underscore. Hence, one can recall the last printed value by calling the variable _. Let us have a look at the example below where we calculate tax levied on the price of a product.

>>> tax = 12.5 / 100
>>> price = 110.50
>>> price * tax
13.8125    # this is the last printed value, hence assigned to _
>>> price + _
124.3125   # now this becomes the last printed value, hence assigned to _
>>> round(_, 2)  # this is the command to round off the value to two decimal places
124.31 

Data Manipulation with Pandas

Pandas stands for Panel Data. It is the core library for data manipulation and data analysis. 

NumPy provides us with a multidimensional array, similarly, Pandas provides us with a multi-dimensional data structure to perform various data manipulation operations. 

Pandas provides us with both single-dimensional and multidimensional data structures. 

The single-dimensional data structure is called a series object; the multidimensional data structure is known as data-frame.

In Python, we’ll mainly be working with data-frames. This is because, Machine Learning algorithms such as linear regression, logistic regression and so on, are all applicable on data-frames. All the data sets available to us can be converted into a data-frame in Python and all manipulations can be done on this. 

In Pandas, the series object is a one-dimensional labelled array. When we consider NumPy array, it is not labelled. 

Pandas Series object

Let us take a look at how to create a series object using Pandas. Pandas are pre-installed in Anaconda, hence, we will not have to install it manually. 

First, we would have to invoke the Pandas library. To do this, type in-

import pandas as pd

Here, ‘pd’ is an alias for Pandas. 

Once Pandas has been imported, we can create the first series object. Let us name it as s1.

s1= pd.Series () 

We must keep in mind that S should always be a capital letter. A series object has now been created. 

Take a look at the image for reference. 

This is how a series object is created. As you can see, the values 10,20,30,40,50 are int64 type. And 0,1,2,3,4 are the labels associated with each of these values. These values can either be known as labels associated or index values. 

If you wish to change the index in a panda series, you can do it by adding an index attribute as shown in the following image. 

This allows us to choose the value associated or the index value corresponding to the series list.

Series object from Dictionary 

Now that we have seen how to create a series object with the help of lists, we can take a look at how it is done with the help of a dictionary. 

In case of a dictionary, the key automatically becomes the index and the values will stay as the actual values of the index. 

Here, the index is k1, k2 and k3 and the values are 10,20 and 30 respectively. 

Pandas Data-frames

A data-frame is a two dimensional labelled data structure and it comprises rows and columns. Normally, in a data-frame, all the elements in a particular column are of the same type. 

For example- If we consider a column which contains the names of people, all of them would be a string type value. If we consider a column containing the marks of these individuals, they would be of an integer type. 

Let us create a data-frame named ‘student’. We’ll list the names of the students inside the data-frame and also the marks which each student obtained, this creates a dictionary. 

To create the data-frame using the dictionary we created, we need to type pd.DataFrame(student) 

Refer the image below for reference and to see the output for the same.

The key becomes the column name and the list of values for a particular key becomes the row values for that column. In simpler words, the key here is student_name and the row values are Bob, Sam, Julia and Charles. 

This is basically how a data-frame is created in Pandas. 

There are a few inbuilt functions which can be performed on any data frame. They are – head(), shape(), tail() and describe(). If we want to separate individual rows and columns from a data frame, we can use any of these two methods. They are .iloc[] and .loc[] method. 

These are some of the data manipulation methods which can be done with Pandas. 

Learn python from expert faculty under Great Learning’s PG program in Artificial Intelligence and Machine Learning. You do not need any prior technical background to pursue this course and understand python functioning.

LEAVE A REPLY

Please enter your comment!
Please enter your name here