Introduction to Python Language

INTRODUCTION:

This blog is based on Python i.e. Introduction to python Language?, and is very beneficial for those who have started a career in Python.
In this blog, I will be discussing all the topics of python language in a better and understandable way with the practical implementation.

Introduction to python?

  • Python is a high-level, Scripting and object-oriented programming language with dynamic semantics developed by Guido Van Rossum in 1991.
  • Dynamic semantics means statements, expressions, syntax that we use in our programs.
  • Python is also useful for writing script because of fast execution and reduces the cost of a program.

So, Let’s start learning and understanding the topics of python.

  • What is Python?
  • How To install Python?

When we talk about python installation, firstly, we need to go to the following Url www.python.org/downloadand download the latest version of python. Currently, I am using Python 3.6 with 64 bit(This vary on the bit version of the computer).

After Download We set the path of python in our system for running the programs.

How to set Path of Python?

Step 1: First, go to the directory where python has been installed like C:\Users\Amiq-pc\AppData\Local\Programs\Python\Python36.

Step 2: Right-click on Computer icon and click on properties. Under this, we click on Advanced system settings as shown in the image given below.

Step 3: Click on Environment Variable tab.

Step 4: After setting the path we need to check whether python is running in our system or not. Let’s create a small program of python:

a=int(input("Please enter a number:"));
if(a%2==0):
 print("Even")
else:
 print("Odd")

To Execute the code, we need to press f5 and then the output will be displayed in the dialog box.

Python Variables

In python, we don’t pass any data type for declaring a variable. It automatically converts as which variable belongs to which dataType at the execution time. This is the beauty of python. For Ex:

a=10;    // Int Type

Lname=’Ameeq’ ;   // String Type

Sal=25555.28;   // Float Type

t=x=p=10;   // Multiple Assignment

Python Keywords

Keywords are the reserved words and are the special keywords that are used in python. These keywords can’t be used as variable name.

True False None and as
asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda

Python Identifiers

Identifiers are the names that are used to represent programming elements such as variables, functions, arrays, and so on. There are some restrictions that identifier provides for the elements such as :

  1. We can not use any Special Character except underscore(_).
  2. We can not use keywords name as an identifier name.
  3. The first character of an identifier should be character or underscore(_) but not a digit.

Python Operators

These are the following operators that must be used in Python.

1.Arithmetic Operators(+,-,*,/,%,**,//):  Arithmetic Operators includes with the following examples:

+(for Addition) Ex: 10+20=30.

-(for Subtraction)  Ex: 50-25=25.

*(for Multiplication) Ex: 2*3=6.

/(for division) Ex: 10/2=5.

%(for Modulos) Ex: 10%2=0;

**(for exponent) Ex: 2**3=8.

//(for floor division) Ex: 20/3=6.

2.Relational Operators(<,>,<=,>=,==,!=,<>): Relational Operators includes with the following examples:

<(for lessthan) Ex: 10<20=True.

>(for greaterthan)  Ex: 20>10=True.

<=(for lessthan or equal to) Ex: 5<=5=True.

>=(for greterthan or equal to) Ex: 9>=12=False.

==(for equal to) Ex: 10==10=True;

!=(for not equal to) Ex: 10!=8=True.

<>(for Not equal to(similar to !=)) Ex: 20<>3=True.

3.Assignment Operator(=,/=,+=,-=*=,%=,**=,//=): It includes with the following examples:

=(for Assignment) Ex: a=20.

/=(for Divide and Assignment)  Ex: a/=2,a=10.

+=(for add and Assignment) Ex: a+=10,a=30.

-=(for subtract and Assignment) Ex: a-=5,a=15.

*=(for Multiply and Assignment) Ex: a*=1,a=20.

%=(for Modulos and Assignment) Ex: a%=7,a=6.

**=(for exponent and Assignment) Ex: b=5,b**=2,b=25.

//=(for floor division and Assignment) Ex: b//=2,b=12.

4.Logical Operator(and,or,not): Here, I am showing you how to use logical operator in python.

and(Logical AND) Ex: 5>3 and 4>2. Output will be True.

or(Logical OR) Ex: 3<5 or 5>6. Output will be True.

not(Logical NOT) Ex: not(5>4). Output will be False.

5.Membership Operator(in,not in): In this Operator we use in and not in Operator. Let’s see the Example.

in(Returns true if a variable is in sequence of  another variable, otherwise false)

not in (Returns true if a variable is not in sequence of another variable, otherwise false)

a=20;
b=30;
list=[20,30,40,50,60]; 
if (a in list): 
print "a is in given list" 
else: 
print "a is not in given list" 
if(b not in list): 
print "b is not given in list" 
else: 
print "b is given in list"

Output: a is in given the list

             b is given in the list.

Python Comments

There are two types of Comments in Python.

  1. Single lined Comment: These type of comments are used when we comment only a single line. is used for single line comments. For Ex:
# This is a single line Comment.

2. Multi-lined Comment: These comments are given inside triple quotes. For Ex:

''' This is
multiple lines
comment in
python'''

Control Statements in Python

Control Statements includes if, if else, nested if, else if, for loop, while loop, do while loop, break, continue.

if: This Statement is used to test a specified condition is true.

Syntax:

if (condition):

statements

Example:

a=20

if a==20:

print(“My name is Ameeq”)

if else: This Statement is used to test a specified condition and if Condition is true then “if” is executes otherwise “else” executes.

Syntax:

if(condition):

statements

else:

statements

Example:

year=2018

if year%4==0:

print “Leap year”

else:

print “Not a Leap Year”

Output:

Not a Leap Year.

Nested if: In these statements, we can check multiple conditions.

Syntax:

if (Condition):

statement

else:

if (Condition):

statement

else:

statement

Example:

a=10 
if a>=20: 
print "Condition True" 
else: 
if a>=15: 
print "Check second value" 
else: 
print "All Conditions are false"

Output:

All Conditions are false

For Loop: It is used to iterate the elements of a collection. Range function(range) is used to iterate the sequence of elements. Its Syntax is given below:

Syntax: 

for <variable> in <sequence>:

Example: 

n=5

for a in range(1,6):

print n*a

Output: 

5, 10, 15, 20, 25.

While loop: It is used to execute the number of statements till the condition is true. If the condition is false, then the control will come out of the loop. Its Syntax is given below:

Syntax: 

while <expression>:

statement or body

Example:

n=153 
sum=0 
while n>0: 
r=n%10 
sum+=r 
n=n/10 
print sum

Output: 9.

Do-While Loop: It is used to iterate the elements in a collection. The do-while loop is always executed once whether the condition is true or false.

Break in Python: In python or any programming language, the break is a jump statement which is used to transfer execution control and breaks the current execution.

Example:

for name in 'Amiq': 
if name == 'i': 
break 
print (name)

Output: Am

Continue in python: It’s used is same as other programming are used. It is also a jump statement which is used to skip execution of current execution. It’s syntax as follows:

Example:

a=0 
while a<=5: 
a=a+1 
if a%2==0: 
continue 
print a 
print "Loop End"

Output: 1 3 5 Loop End

Now I will define you the most important topic of python i.e. OOPs (Object Oriented Programming).

OOPs in Python

As discussed earlier, Python is an Object Oriented Programming language. With the help of this, we develop the application using Object Oriented approach through classes and objects.

OOPs follows some major principles for developing an application. Here, I will define you each and every principle of OOPs in detail.

  1. Class
  2. Object
  3. Inheritance
  4. Polymorphism
  5. Data Abstraction
  6. Encapsulation

1. Class: Class is a template where we put our logic and is a collection of multiple objects. A class is a logical entity which has some attributes and methods.

For Ex: Let’s take an example of a student Class where Classroom is a Class and it has some properties, attributes, and methods like Student RollNumber, Name and Age, Father’s Name etc.

Syntax:

class ClassName:

.

.

<n- statements> …

2. Object: Object is a runtime entity that has some state and behavior. It may be physical or logical. In Python, everything is an object. For Example chair, pen, Desk, Mobile etc.

3. Inheritance: Inheritance is a powerful feature in OOPs. Inheritance means acquires all the properties and data of the current package into the new package. The current package is a Parent class or Superclass or Base Class and the new package is a Child class or Derived Class or Subclass. Let’s take an example so that we clear the concept of inheritance in a better way.

Syntax:

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived class

Example:

class Test:
name = ""

def __init__(self, name):
self.name = name

def printName(self):
print "Name = " + self.name

class Developer(Test):
def __init__(self, name):
self.name = name

def doCoding(self):
print "The Python World"

abc = Test("Amy")
abc.printName()

xyz = Developer("testing")
xyz.printName()
xyz.doCoding()

Output:

Name = Amy
Name = testing
The Python World

4. Polymorphism: Polymorphism is also an important feature of OOPs. The word “Polymorphism” is made of two words “poly” + “morphism”. “Poly” means many and “morphism” means forms or shapes. So, It means one thing many forms. For Example, A Shopkeeper has treated differently with his/her Customers in his shop and the same shopkeeper treated differently with his/her family at home.

This is called Polymorphism.

5. Data Abstraction: It is used to restrict or we can say it provides restrictions to access the methods and variables. Data Abstraction is achieved through encapsulation(We will discuss in the later point).

In terms of OOPs, Abstraction means hiding the internal details from the user and showing the functionality to the user. A Mobile Phone, Laptop is the best example of Data Abstraction.

6. Encapsulation: Encapsulation means wrapping up of data or code into a single unit for the purpose of safety or being modified accidentally (for making the class private). It is also a powerful feature of OOPs.

What is Self and __init __ Methods in Python?

Before we understand about self and __init__ methods in python, We know the concept of class and object(Already discussed above).

So, ‘Self’ represents the instance of the class. With the help of “self” keyword, we can easily access the attributes and methods of the class.

‘__init__’ in python is a reserved keyword. It is same as Constructor(discuss in later) in Object oriented concepts. This method calls automatically when an object is created.

For Example:

class Car(object):

def __init__(self, modelNum, Carcolor, companyName, Carspeed):
self.Carcolor = Carcolor
self.companyName = companyName
self.Carspeed = Carspeed
self.modelNum = modelNum

def start(self):
print("started")

def stop(self):
print("stopped")

def accelarate(self):
print("accelarating...")

def change_gear(self):
print("gear changed")


hyundai = Car("i20", "stardust", "Hyundai", 120)
maruti_suzuki = Car("Ritz", "white", "Maruti Suzuki", 100)

Here, we created the objects of Car class and pass these arguments (“i20″,”Stardust”, “Hyundai,120) to “__init__” method to initialize the object of Car Class.

Constructor in Python

A constructor is a special type of function which is used to initialize the members of the class. It has the same name as the class name and used with the __init__ method to initialize the object. A constructor can be parameterized and non-parameterized.

For Example:

class Sum:
def __init__(self,a=0,b=0):
self.first=a
self.second=b
def getSum(self,a,b):
c=0
c=a+b
print(c)
s1=Sum(5,10)
s1.getSum()

Output is:

c=15.

We discuss more related to Parameterized or non-Parameterized constructor. For Example

class Student: 
def __init__(self):    // non parametrized constructor
print("This is non parametrized constructor")

&

class Student: 
def __init__(self, name):    // parametrized constructor
print("This is parametrized constructor")

Strings in Python

Now, I will explain you about strings in python. Before going to the depth, let me introduce you with the term “String”. A string is a contiguous sequence of characters, symbols. It is used to store a sequence of characters such as name, address, phone number, etc.

Python strings are immutable sequences of characters, symbols that are used to handle textual data in python. We can create python string by enclosing single as well as double quotes.

How to access python string?

  • We can access python string from both the directions (forward and backward)
  • Forward indexing starts with 0,1,2…
  • Backward indexing starts with -1,-2,-3…
  • This is the beauty of python string.

Example:

There are several operators that are used in Python Strings which are as follows:

1.Basic Operator

2.Membership Operator

3.Relational Operator

Let’s discuss these operators in details.

1.Basic Operator: There are 2 types of basic operators in python string “+”(Concatenation Operator) and “*”(Replication Operator).Let’s discuss in brief.

Concatenation Operator(+): It is used to add 2 strings and creates a new string.

For Ex: “Mohd” + “Ameeq”.

Note: We can not concatenate ‘str’ and ‘int’ objects.

Replication Operator(*): This type of operator is used to repeat a string number of times. This Operator works for two parameters, one is the integer value and the other one is the string.

For Ex: 3*Amy

The output is: ‘AmyAmyAmy’.

2.Membership Operator: These types of operators includes in and not in Operators.

in: It returns ‘true’ if a character or the substring is present in the given string, otherwise false.
not in: It returns ‘true’ if a character or the substring is not present in the given string, otherwise false.

For Example, 

>>>str1=”Mohd”

>>>str2=”Md”

>>>str3=”Amy”

>>>str2 in str1

true

>>>str3 not in str2

true

3.Relational Operators: It includes Comparison (<,><=,>=,==,!=,<>) and these are compared based on the ASCII value or Unicode.

For Example,

>>>”Ameeq” == “AmEeq”

true

>>>25<=20

false.

List in Python

If we talk about the programming language, A list is a data structure which is used to store various data types.

Lists are mutable and it is enclosed between a square([]) brackets and with the help of list, we can perform various operations like insertion and deletion on the list in python.

List elements are accessed from both the direction (forward and backward).

following are examples that show how to create a list in python.

li=[10,20,’Ameeq’]

li2=[‘Mohd’,22.5]

Tuple in Python

In python, A tuple is a sequence of immutable(which cannot be changed or modified) objects. A tuple can be used to store different types of objects and these objects are enclosed within parenthesis followed by a separated comma.

A Tuple is similar to a list(As discussed earlier) in python.

The only difference is that list is enclosed between square bracket while tuple is enclosed between parenthesis and one more difference is that a list has mutable objects whereas a tuple has immutable objects.

Tuple elements are accessed from both the direction (forward and backward).

The examples are as follows:

tu=(10,50,60)

tu2=(‘Amy’,75.5,5)

Functions in Python

As we know all, A function is a block of statements where we organize our code and reusable it.

A function is a section of a program that performs a specific task or we can say, a function is a reusable component which can be used many times according to the need of the user. I am sharing some important points related to functions:

  • Functions provide better modularity for the software, application.
  • It provides a high degree of code reusing.
  • Functions have several names which exactly works like functions i.e. methods, subroutines etc.
  • Functions may return value or not(According to the return type passed in a function).

Types of functions 

Python provides 2 types of functions:

  1. Built-in Function
  2. User-Defined Function

Built-in Function: These types of functions are readymade or predefined functions that are already built in the library of python. We can use these functions anywhere in the code.

User-Defined Function: These types of functions are created by the user or programmer itself for performing a specific task.

How to Declare and Define a function in Python?

In python, we can declare a function like,

Syntax: functionName(args)

Ex: SumFunc(26)

and, We define a function using a def keyword.

Syntax: def functionName(args):

Example: def testFunc(a,b):

Python Dictionary

The term dictionary in programming language means key and value pair i.e. Item. A dictionary in python is an unordered set of key and value pair enclosed within curly braces.

In a dictionary, the key which we have passed must be unique and both key and value are separated by a colon(:). Items are separated from each other by a comma(,) to form a dictionary. Following are the example of a dictionary.

A dictionary is mutable means we can update the value of dictionary but not key because the key is unique.

>>>dic1={50:’Mohd’,51:’Ameeq’,52:’Loginworks Softwares Pvt. Ltd.’}

{50:’Mohd’,51:’Ameeq’,52:’Loginworks Softwares Pvt. Ltd.’}

How to Access Dictionary value?

We can Access dictionary values by its key. For Example,

dic1[51]=’Ameeq’

dic1[50]=’Mohd’

print(dic1[51])

print(dic1[50])

How to Update Dictionary values?

The Dictionary values are updated using a key-value pair i.e. item. In python, values can be updated or modified.

test1={'id':10,'CName':'Loginworks','CompanyMode:'Private'}

test1['CompanyMode']='Private Limited'

print test1

How to Delete Dictionary values?

The Dictionary items can be deleted using a key only. In python, the del keyword is used for performing the deletion operation in the dictionary. Its Syntax is given below:

del  <dictionary_name>[key] 

For Example:

testEx1={'id':1,'FName':'Mohd','Company:'LWS'}

testEx2={100:'Sam'101:'Yuvi'102:'MS'}

del testEx1[1]
del testEx2[101]

print testEx1
print testEx2

Output:

{100:‘Sam’102:‘MS’}

Modules in Python

In python, Module is a unique feature that is used to divide or categorized code into smaller parts. A module is a type of file where classes, functions are defined into a single file.

with the help of modules, we can Reuse and Categorized our code.

Reuse means reusability, we can use our code in anywhere wherever we want &,

Categorized means, dividing our code of the same type can be placed in one module.

The import statement is used to import a module in our project. The syntax is given below:

Syntax: import filename1,filename2

Example: We make two files of python and use these file in another file using

module (import keyword).

The first file is Add.py

def addfunc(a,b):
 c=a+b
 print c
 return

and, the Second file is Sub.py

def subfunc(a,b):
 c=a-b
 print c
 return

finally, we use these files in our new file(wherever we required using import statement).

import Add, Sub
Add.addfunc(10,15)
Sub.subfunc(20,10)

Output: 25

10

There are several built-in modules that are already provided by the python are as follows:

math() function contains

ceil(n)

sqrt(n)

exp(n)

floor(n),sin(n),cos(n),tan(n) etc.


CONCLUSION:

With this, we come to an end of this tutorial on “Introduction to Python Language”.
Nowadays, it is a smart concept and many big companies used python for developing an interactive application. Moreover, I have defined all about python world, how to run programs, OOPs, functions, Dictionary, List, modules etc. So, learn this language of python and go ahead and take a good package in your hands. I have elaborated this blog to deliver easy, simple and valuable content regarding this innovated language to learn step by step. I hope this blog will be more valuable and important for a new learner.
However, suggestions or queries are always welcome, so, do write in the comment section.

Thank You For Learning!!!

Get in Touch

Leave a Comment