Python Tutorial

python-tutorial

Introduction to Python

In this Python tutorial, we will comprehensively learn all the ideas of Python. How about we start off by understanding what precisely is Python.

Python is a free, open-source programming language. Therefore, you should simply introduce Python once, and you can start working with it. Also that you can contribute your own code to the community.

Python is likewise a cross-platform viable language. Anyway, I don’t get this’ meaning? Indeed, you can introduce and run Python on several operating frameworks. Whether you have a Windows, Mac or Linux, you can rest assure that Python will work on all these operating frameworks.

Python is likewise a great visualization device. It provides libraries, for example, Matplotlib, seaborn and bokeh to create dazzling visualizations.

In addition, Python is the most popular language for machine learning and profound learning. In actuality, today, all top organizations are putting resources into Python to execute machine learning in the back-end.

Python Tutorial: Why learn Python?

Simple and easy to learn:

Learning python programming language is enjoyable. In the event that you compare Python with some other language, for instance, Java or C++, at that point you will find that its punctuation is a way part easier. You additionally don’t need to worry about the missing semicolons (;) at long last!

Assume we need to print “Welcome to the world of programming” on our screen. How about we compare the linguistic structure for Python and Java:

Python Syntax:

print(“Welcome to the world of programming”)

Java Syntax:

class Simple{

public static void main(String args[]){

System.out.println("Welcome to the world of programming");

}

}

So here we see that Python code consists of only one line, but for Java, there are multiple lines of code just for printing a statement.

Career Opportunities:

Python has huge career opportunities in the IT industry. Almost every other IT company, be it a startup or a Multi-National Company uses python for varied applications. So, if you have good expertise in python, you will be in demand for a wide range of jobs in different domains such as machine learning, cloud infrastructure, web-site designing, testing and many more.

Large Open Source Community:
Let’s say you are working on a python project and you get stuck somewhere, you don’t have to worry at all because python has a huge community for help. So, if you have any queries, you can directly seek help from millions of python community members.

Now, in this python tutorial, we will look at the procedure to install python.

Python Installation

If you are new to programming, then installing a programming language itself could be a herculean task. So, now we are going to look at the step by step process to install python.

  1. Start off by going to this website -> https://www.python.org/downloads/

python installation

  1. Click on the downloads tab and choose the operating system and python version. So, here I am downloading python version 3.7.4 for  Windows operating system.

python downloads

Now that we have installed python, let’s go ahead in this python tutorial and start off with programming in Python

Variables in Python:

You can consider a variable to be a temporary storage space where you can keep changing values. Let’s take this example to understand variables:

So, let’s say, we have this cart and initially we store an apple in it.

So, here this cart acts like a variable, where the values stored in it keep on changing.

Now, that we have understood what a variable is, let’s go ahead and see how can we assign values to a variable in python.
Assigning values to a variable:

To assign values to a variable in Python, we will use the assignment (=) operator.

a=10a="sparta"a=True

Here, initially, we have stored a numeric value -> 10 in the variable ‘a’.  After a while, we have stored a string value -> “sparta” in the same variable. And then, we have stored the logical value True.

Now, let’s implement the same thing in Jupyter Notebook and look at the result:

Assigning a value 10 to a:

a=10

Allocating “sparta” to a:

a="sparta"

Assigning True to a:

a=True

Going ahead in this Python tutorial, we will learn about data types in Python.

Data Types in Python

Every variable is associated with a data type and these are the different types of   data types available in python:

Data Types in Python

Now, let’s understand these individual data types by their implementation in Jupyter notebook.

Numbers in Python

Numbers in python could be integers, floating point numbers or complex numbers.

Let’s start off with an example on integer:

num1=100

Here, we have assigned the value 100 to num1 and when we check the type of the variable, we see that it is an integer.

Next, we have an example on floating-point number:

num2=13, 4

This time, we have assigned the value 13.4 to num2 and checking the type of the variable, tells us that it is float.

Finally, let’s look at an example of a complex number:

num3=10-10j

Here, we have assigned the value 10-10j to num3. Now 10-10j comprises two parts->  the real part and the imaginary part and combining these two gives us the complex number.

Now, let’s start with Python Strings.

Python Strings

Anything written in single or double quotes is treated as a string in Python.

str1='Intellipaat'                    str2="Let there be peace!!"

Now, let’s see how can we extract individual characters from a string.

So, I’d want to extract the first two characters from ‘str1’ which I have created above:

str1[0:2]

Now, similarly, let’s extract the last two characters from str1:

str1[-2:]

Now, let’s head onto tuples in Python:

Python Tuples

A python tuple is a collection of immutable Python objects enclosed within parenthesis (). Elements in a tuple could be of the same data type or of the different data types.

Let’s create a tuple where elements are of the same data type:

tup1=('Intellipaat', 'Python', 'tutorial')

Now, let’s access the first element from this tuple:

tup1[0]

Extracting the last element from this tuple:

tup1[-1]

Now, we will go ahead and learn about Python lists.

Python Lists

Python Lists is an ordered collection of elements.

It can contain elements of different data types, unlike arrays.

Now, let’s create a list with different data types:

myList=['Python-list', 'Java', '10', '20']

Now, let’s do some operation on the list we created:
Fetching the first element from the list:

myList[0]

Adding an element while removing the other:

myList[1]='spark'

The below line of code will return the length of the list:

len(myList)

This will return the list in reversed order.

myList[1]='spark'

Now, we will further look at Python Sets.

Python Sets

Python sets are a collection of unordered and unindexed items.

Every element in a set is unique and it does contain duplicate values.

Sets can be used to perform mathematical calculations such as union, intersection, and differences.

Creating a set:

Name={"Varun", "Harkirat", "Balraj"}

Here, in set ‘Age’, value “22” is appearing twice. Since every element in set is unique, it will remove the duplicate value.
Operations on Sets:

1.add:  This method adds an element to the set if it is not present in it.

Name.add("anand")

2.union: It returns the union of two sets.

Detail=Age.union(Name)

3.intersection: This method returns the intersection of two sets.

Intersection_of_sets=Detail.intersection(Age)

4.difference: The difference of two sets(set1, set2) will return the elements which are present only in set1.

Difference_of_sets=Detail.difference(Age)

Now, we will look at Python Dictionary.

Python Dictionary

Python Dictionaries is an unordered collection of data. The data in the dictionary is stored as a key:value pair where the key should not be mutable and value can be of any type.

Creating a Dictionary:

Dictionary={'Sachin Tendulkar':'cricket','Harry Kane':'Football'}Dictionary=['Sachin Tendulkar']

Accessing elements from a dictionary:

Dictionary=Sachin Tendulkar

Removing elements from a dictionary:

del Dictionary=['Sachin Tendulkar']

Replacing elements in a dictionary:

Dictionary
Going ahead in this python tutorial, we will learn about conditional statements.

Conditional Statements

We use a conditional statement to run a single line of code or a set of codes if it satisfies certain conditions. If a condition is true, the code executes, otherwise, control passes to the next control statement.

Hello World

There are three types of conditional statements as illustrated in the above example:

  1. If statement: Firstly, “if” condition is checked and if it is true the statements under “if” statements will be executed. If it is false, then the control will be passed on to the next conditional statements.
  2. Elif statement: If the previous condition is false, either it could be “if” condition or “elif” after “if”, then the control is passed on to the “elif” statements. If it is true then the statements after the “elif” condition will execute. There can be more than one “elif” statement.
  3. Else statement: When “if” and “elif” conditions are false, then the control is passed on to the “else” statement and it will execute.

Now, let’s go ahead and learn about loops in this python tutorial.

Loops

If we have a block of code then statements in it will be executed sequentially. But, when we want a statement or a set of statements to be executed multiple times then we use loops.

Types of loops:

1.While loop: We use this loop when we want a statement or a set of statement to execute as long as the Boolean condition associated with it satisfies.

In the while loop, the number of iterations depends on the condition which is applied to the while loop.

while Loop in python

2.for loop: Here, we know the number of iterations unlike while loop. This for loop is also used for iterations of statements or a set of statements multiple times.

for Loop in python

3.nested loop: This type of loop consists of a loop inside a loop. It can be for loop or can be a combination of for and while loop.

nested Loop in python

Now, we will learn about user-defined functions in this python tutorial.

User-Defined Function 

In any programming language, functions are a better and systematic way of writing. Functions provide us the liberty to use the code inside it whenever it is needed just by calling the function by its name.

Syntax: def function()

def multiply (x,y,z): 

Going ahead in this Python tutorial, we will learn about Exception Handling.

Exception Handling

Basically, an exception is an abnormal condition or error that occurs during the execution of a program. Whenever an exception occurs in a program, the execution of the program halts and the further instruction of the programs are not executed.

We need to handle these exceptions in order to ensure the normal execution of the program.

Some of the common exceptions that occur in Python programs while executing are:

  1. NameError: This error occurs when a name is not found.
  2. ZeroDivisionError: When a number is divided by zero, ZeroDivisionError occurs.
  3. IndentationError: This error occurs due to the wrong indentation.
  4. IOError: When Input-Output operation fails, IOError occurs.

So, in Python we use the trycatchexcept and finally to handle the exceptions.

try-except block

In the Python program, the line of code that may throw exceptions is placed in the try block.

The try block should have except block with it to handle the exception. As an illustration – If any exception occurs in try block then the statements in except block will be executed.

Syntax:

try:

     #line of code

except Exception:

    #line of code

#rest of the code

Example:

file not found error

“else” block

In this case, the else block will be executed if no exception occurs.

else block

Syntax:

try:

#line of code

except Exception:

#line of code

else:

#If there is no exception then this piece of code will be executed

Example:

zero division error

“finally” block

If we want a piece of executable code, which we cannot skip under any circumstances, then we need to put this code in the finally block.

Syntax:

try:

#line of code

finally:

#This piece of code will definitely be executed.

Example:

file not found error
Here, in this tutorial, we learned all the basics of Python which are variables, string, numbers, data types, tuples, lists, sets, dictionary, conditional statements, loops, user-defined functions, and exception handling. If you want to go through more concepts of Python in-depth, this Python Tutorial consists of all the modules which will help you throughout your learning.