Introduction
Python is an open-source high-level object-oriented programming language which is developed by Guido van Rossum in the early 1990s at the National Research Institute for Mathematics and Computer Science in the Netherlands.
It is a dynamic, interpreted, interactive, functional, object-oriented, highly readable and case sensitive language. Some people say Python is a scripting language but it is not actually a scripting language only it is much more than that.
Earlier its name was Monty Python which was a British comedy group. Nowadays, It is widely used for ad-hoc analysis as well as in Data Analytics for the following,
- Weather Forecasting
- Scientific Analytics
- Ad Testing
- Risk Management Analysis
Features of Python
Followings are the features of Python:
Interpreted
It is an interpreted language so, we don't need to compile the program before the execution.
As we know in interpreted languages the program code is first converted into some interpreted code and after that, it is converted into machine language.
Program Code <interpreted> Interpreted Code <converted> Machine language
Dynamic
Python is dynamically-typed as well as strongly typed programming language.
Object-Oriented
It is also object-oriented programming because class and object are the two main aspects of object-oriented which is supported by Python. One thing we should know is it supports object-oriented programming but it doesn't force to use the object-oriented programming features
Interactive
Python has an interactive interpreter. So, it is easy to check the python command line by line. One can execute the sample.py file directly on the python command shell. Here .py is the extension of python.
Functional
Functional code is characterized by one thing: the absence of side effects. It doesn’t rely on data outside the current function.
Functional programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input.
Prerequisites for these articles
There are some following prerequisites for this article
- Windows Operating System
- Python
Note
By default, Python is not installed with Windows operating systems like Mac and Ubuntu. So, first, we need to install Python. For this article, I have installed Python 2.7
which is not the latest version but you can install the latest version as well.
Python Installation Process
- First, download it from here, download
- Now install it on your computer. For detail information about the installation process click here
Programming Syntax
Python is more readable than other programming languages. Let us see a glimpse of basic programming syntax. Here I am going to use IDLE (Integrated Development and Learning Environment) Python GUI of Python 2.7.
The syntax for print a string "Hello Python"
- >>> print("Hello Python")
- Hello Python
Here ( >>>) triple angle brackets represent the python prompt where one can execute any python command or expression
Image: Python IDLE
Where is IDLE
If Python is installed in our machine, we can find it from the installed programs. In Windows 8.x or 10, search IDLE and if you have a lower version of Windows find it from All Programs list.
IDLE Features
There is a problem with Python IDLE prompt is that once we execute a command, it cannot be edited like a windows command prompt. But it has another awesome feature by which we can escape from this problem. Let us see
Step 1
Go to the File menu of Python IDLE and click on New File option to create a new file
File > New File
After clicking on the New File option, a new editor window will be opened.
Step 2
Now write your python program here (in a newly opened window) and save this file with .py extension at any location where you want. For this article, I have written a small program to print a string, Hello Python, and a number and saved this file with name python.py
Step 3
Now go to the Run menu and click on Run Module to execute this program or click F5. If your program file is not saved before clicking the F5 key or Run Module, a warning prompt will be opened which asks your choice regarding "Source must be saved".
Run > Run Module
Output
- Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
- Type "copyright", "credits" or "license()" for more information.
- >>>
- ================ RESTART: C:/Users/PRAVEEN/Desktop/python.py ================
- Hello Python
- 10
In this output, we can see that Hello Python and 10 are the outputs of this program which is saved in python.py file at location highlighted in green background.
Note
Apart from python IDLE, we can execute/do the python programming by using the following IDE
- Python Shell
- Visual Studio
- Pycharm and more other interactive IDEs are available for python programming
Python Shell
We can execute/write python code on Python Shell as well. Let us see, where Python Shell and how we can write code on Python shell prompt.
Step 1
Open Windows Command Prompt
Step 2
Switch to python installed directory. In my machine python installation path is C:\Python27
C:Windows\System32> cd c:\Python27 and press enter to switch to this directory
C:\Python27>
Now type python and press enter key
C:\Python27>python
Now python shell command prompt is enabled, here we can do code. Let us see the following figure which represents the graphical view of the above steps.
Note
"If the environment setting for python path is already configured in your system then you can directly type python and press enter.
C:Windows\System32>python "
In upcoming articles, I will explain how we can do python programming using Visual Studio. I would like to explain briefly how we can do python programming with Visual Studio.
Identifiers in Python
Basically, identifiers are names given to a program's variables, class, objects, functions and etc. Python has some sets of rules for the naming of identifiers.
Rules
- It can be a combination of alphabets or alphanumeric but it must not start with numbers.
- It may be either in lowercase, uppercase or mix of upper & lower case.
- It can have underscore (_)
- No other special character like (%, @, $, & and etc) is allowed in python identifiers except underscore (_).
Correct Identifires
- >>> print('Indetifires Observation:')
- Indetifires Observation:
- >>> name='Mohit'
- >>> Name='Krishna'
- >>> _name='Rajesh'
- >>> _Name='Kunal'
- >>> name2='kumar'
- >>> Name2='Singh'
- >>> _name2='Gupta'
- >>> _Name2='Kapur'
- >>> print(name +' '+ name2)
- Mohit kumar
- >>> print(Name +' '+ Name2)
- Krishna Singh
- >>> print(_name +' '+ _name2)
- Rajesh Gupta
- >>> print(_Name +' '+ _Name2)
- Kunal Kapur
Invalid Identifires (Wrong Identifier)
- >>> 1name='Ganga'
- SyntaxError: invalid syntax #variable name must not be start with a number
- >>> 2_name='Rohan'
- SyntaxError: invalid syntax
- >>> @name='uiraj'
- SyntaxError: invalid syntax #variable name must not have @ or any special char
- >>> name@='Neeraj'
- SyntaxError: invalid syntax
- >>> $name='Kritika'
- SyntaxError: invalid syntax
Note
no any other special character like (%, @, $, & and etc) is allowed in python identifiers.
Naming Convention in Python
- Class
the name of the class starts with uppercase and all other identifiers with lowercase
- Private Identifiers
name starts with _underscore.
_name='Raman'
- Strongly Private Identifiers
name starts with a double underscore.
__name='Rohit'
- Language Identifiers
It starts and ends with a double underscore (__).
__system__
Indentation
Basically, Indentation is leading white space at the beginning of a logical line which is used to determine the grouping of statements.
In other programming languages indentation is used to make the code beautify but in Python, it is mandatory to separate the block of code.
Note
The white space for indentation should be at least 4 characters or a tab.
Example
Comments in Python
As like other programming languages, Python has also two types of code comments
- Single Line Comment
# is used for single-line comment. Let's see with an example code
- Multi-Line Comment
For multi-line comments, we have two options. We can use either triple double quotes (""") or single quotes ('''). Let's see with example code With Double Quotes
-
-
-
-
-
- language="Python"
-
- ''
-
-
-
- print(language)
Code highlighted with yellow background represents the multi-lines comments by using triple double quotes and single quotes
Data Types
Like other programming languages, Python has some data types as well. Each variable's value in Python has a data type. Basically everything in Python is an object where data type is a class and variables are their objects.
Note
As with some other programming languages, here we don't need to declare the data type at the time of variable declaration. Basically it is restricted to declare the data type for any variables, here Python internally identifies the type by the value which is assigned to a variable.
Let's see more about the data types. Followings are the list of native data types,
- Boolean
It may be either True or False.
But it is a little different from other programming languages, here we can do any type of arithmetical operation with Boolean type without conversion of the data type. because True is considered as 1 and False as 0.
Example:
- Integer
Any non-floating numbers in Python are integer type
Example
- Float
Any numbers which have some floating value are float type
Example
- Fraction
Python is not limited to integer and floating types. Here we can assign a fancy fractional value in a variable that is done by us on paper usually.
Example- >>> x = fractions.Fraction(1, 5)
- >>> print(x)
- >>> 1/5
- Complex
It is a combination of real and imaginary values. We write the complex number in the form of x +yj where x is real and y is an imaginary part.
Example
- List
The list is an ordered sequence of items. It is one of the most used data types in Python and is very flexible. All the items in a list do not need to be of the same type.
Example
- >>> companies = ['Microsoft', 'IBM', 'TCS', 'AON', 'Google']
- >>> x = [ 'abc', 'efg', '123', True, 100 ]
- Tuples
Like List, tuples are also an ordered immutable list. We can say that it's like a read-only list that cannot be modified once created. One more difference is that Tuples is enclosed between parenthesis ( ( ) ) where the list between the square braces ( [ ] ).
Example
- >>> companies = ( 'Microsoft', 'IBM', 'TCS', 'AON', 'Google)
- >>> x = [ 'abc', 'efg', '123', True, 100 ]
- Dictionary
Dictionary data type is like a hash table or array which keeps the data into key-value pair. Here the list of key-value pair items are enclosed between curly braces ( { } )
Example- >>> data={'Name' : 'Praveen', 'Email' : '[email protected]', 'Mobile' : '+91 4444558888' ,'PIN' : 110045}
- Sets
Set is an unordered collection of unique items. Set is defined by values separated by a comma inside braces { }. Items in a set are not ordered. Set can have unique items otherwise it will eliminate at duplicate items while doing any operation with a set. We do all kinds of operations like Union, Intersection on two sets.
Example- >>> a = { 1, 2, 3, 4, 5}
- >>> b ={ ''a', 'e', 'i', 'o', 'u' }
- String
A string is a sequence of Unicode characters. We can use single quotes ( ' ) or double quotes ( " ) to represent strings. Multi-line strings can be denoted using triple single quotes or triple double quotes (''' or """).
Example- >>> me= ''I am Praveen'
- >>> me = "I am Praveen"
- >>> me = ' ' ' Hello Friends,
This is the example of multi-line strings in Python programming using a triple single quote. ' ' '- >>> me = """ Hello Friends,
This is the example of multi-line strings in Python programming using a triple-double quote. """
Program Practices on Data Types
Boolean
# assign a value into boolean type into variable x and print it
- >>> x=True
- >>> print(x)
- True
# check the type of variable x
- >>> x=True
- >>> type(x)
- <class 'bool'>
- >>> print("The type of variable 'x' is",type(x))
- The type of variable 'x' is <class 'bool'>
# checking boolean condition: 1st Way
- >>> x=True
- >>> if x:
- print("The value of x is: ",x);
- The value of x is: True
# checking boolean condition: 2nd Way
- >>> x=True
- >>> if x == True:
- print("The value of x is: ",x);
- The value of x is: True
# checking boolean condition: 3rd Way
- >>> x=True
- >>> if x == 1:
- print("The result of '(x == 1)' is: ",x);
- The result of '(x == 1)' is: True
Note
In Python, the integer value 1 is considered as True and 0 as False. So we can do arithmetical operations with boolean types without data type conversion.
# Arithmetical Operation with Boolean Type
- >>> x=True
- >>> y=True
- >>> print("x + y is: ", x + y)
- x + y is: 2
- >>> print("x - y is:", x - y)
- x - y is: 0
- >>> print("x * y is: ", x * y)
- x * y is: 1
- >>> print("x / y is: ", x / y)
- x / y is: 1.0
- >>> print("x % y is: ", x % y)
- x % y is: 0
# Ternary condition with Boolean Type
- >>> x=True;
- >>> x = False if x==True else True
- >>> print('value of x is: ',x)
- value of x is: False
Integer
# assign numeric value into a variable x
- x=5
- print(x)
- type(x)
- print("Type of 'x' is: ",type(x))
Float
# assign float value into a variable x
- >>>
- >>> x=5.2
- >>> print("x = ",x)
- x = 5.2
- >>> print("Type of 'x' is: ",type(x))
- Type of 'x' is: <class 'float'>
Fractions
To use fraction we need to import a python library for fractions. It is a very interesting feature in Python. No other programming languages do any operation with this type of operation
- >>> import fractions
- >>> x=fractions.Fraction(1,5)
- >>> x
- Fraction(1, 5)
- >>> print(x)
- 1/5
Complex Number
- >>> x = 2 + 4j
- >>> y = 2 + 2j
- >>> z = x + y
- >>> print(z)
- (4+6j)
List
Add a list of strings and print its items using for loop, further we will read more about looping statement
- >>> companies = ['Microsoft', 'IBM', 'TCS', 'AON', 'Google']
- >>> for i in range(len(companies)):
- index=i+1
- print(index,companies[i])
- (1, 'Microsoft')
- (2, 'IBM')
- (3, 'TCS')
- (4, 'AON')
- (5, 'Google')
Add new items in existing list
- >>> companies.append(['C# Corner'])
- >>> print(companies)
- ['Microsoft', 'IBM', 'TCS', 'AON', 'Google', ['C# Corner']]
Update Item: here I am going to update the company name AON to AON Hewitt by updating the item of list
- >>> companies = ['Microsoft', 'IBM', 'TCS', 'AON', 'Google']
- >>> companies[3]='AON Hewitt'
- >>> print(companies)
- ['Microsoft', 'IBM', 'TCS', 'AON Hewitt', 'Google']
Delete item from list
- >>> x=[0,1,2,3,4,5]
- >>> del x[0]
- >>> print x
- [1, 2, 3, 4, 5]
Tuples
It is like a read-only list whose element can not be updated once declared
- >>> _tuple = (1,2,3,4,5)
- >>> _tuple
- (1, 2, 3, 4, 5)
- >>> _tuple[0]
- 1
- >>> _tuple[0]=10
-
- Traceback (most recent call last):
- File "<pyshell#16>", line 1, in <module>
- _tuple[0]=10
- TypeError: 'tuple' object does not support item assignment
Delete tupple
- >>>
- >>> _tuple=(1,2,3,4,5)
- >>> del _tuple
Dictionary
Declare a dictionary type variable with named student
- >>> student={'Name':'Rohan','Roll':4206}
- >>> for key in student:
- print(student[key])
- Rohan
- 4206
To Create empty dictionary
Remove Item from dictionary
- >>>
- >>> student.pop('Contact')
- '9700000081'
- >>> print(student)
- {'Name': 'Rohan', 'Roll': 4206}
Remove all items from the dictionary
- >>> student.clear()
- >>> student
- {}
Set
Create Set
- >>>
- >>> teamA={'Raman','Shyam','Vijay'}
- >>> teamB={'Rohit','Raman','Shekar','Arjun','Vijay'}
- >>> print(teamA,teamB)
- (set(['Raman', 'Vijay', 'Shyam']), set(['Raman', 'Rohit', 'Shekar', 'Vijay', 'Arjun']))
Add Item into a Set variable
- >>> teamA.add('Jeny')
- >>> teamA
- set(['Raman', 'Jeny', 'Vijay', 'Shyam'])
Add multiple Items in a Set variable
- >>> teamA={'Raman','Shyam','Vijay'}
- >>> teamA.update(['Praveen','Rahul'])
- >>> teamA
- set(['Raman', 'Praveen', 'Vijay', 'Shyam', 'Rahul'])
Remove Items from a Set
We have two functions discard() and remove() by which we can remove a particular item from a Set.
Only difference between both of these are that if item is not exists in the Set, discard() will do nothing but remove() will show a KeyError.
- >>> x=set(['a','e','i','o','u','x','z'])
- >>> print(x)
- set(['a', 'e', 'i', 'o', 'u', 'x', 'z'])
- >>>
- >>> x.discard(x)
- >>> x
- set(['a', 'e', 'i', 'o', 'u', 'x', 'z'])
- >>> x.discard('x')
- >>> x
- set(['a', 'e', 'i', 'o', 'u', 'z'])
- >>> x.remove('z')
- >>>
- >>> x.discard('m')
- >>>
- >>> x.remove('m')
-
- Traceback (most recent call last):
- File "<pyshell#25>", line 1, in <module>
- x.remove('m')
- KeyError: 'm'
Union of two sets
As we know the union of sets is combination of all unique items of both sets. In Python we can get the union of two sets by using union() function.
- >>> developer={'Ram','Shyam','Krishna','Praveen'}
- >>> author={'Praveen','Ramesh'}
- >>>
- >>> developer.union(author)
- set(['Krishna', 'Ramesh', 'Shyam', 'Praveen', 'Ram'])
- >>> author.union(developer)
- set(['Krishna', 'Ramesh', 'Shyam', 'Praveen', 'Ram'])
We can do the same result by using bitwize OR ( I ) OPERATOR as well. Let's see how it works.
- >>> developer | author
- set(['Krishna', 'Ramesh', 'Shyam', 'Praveen', 'Ram'])
- >>> author | developer
- set(['Krishna', 'Ramesh', 'Shyam', 'Praveen', 'Ram'])
Intersection: Intersection of two sets represents all common elements which exists in both sets.
- >>> developer.intersection(author)
- set(['Praveen'])
We can do the same result by using bitwise AND ( & ) OPERATOR as well. Let's see how it works.
- >>> developer & author
- set(['Praveen'])
Remove All Items
clear(): this function is used to remove all items of a sets.
- >>> developer.clear()
- >>> developer
- set([])
Strings
String Printing: either we can put a string into single quotes or double.
- >>>
- >>> print('Hello Python')
- Hello Python
- >>>
- >>> print("Hello Python")
- Hello Python
Multi-line string
We can use triple single quotes or double quotes to assign a variable with multi-line strings.
- >>> about=
-
- >>> print(about)
- I am a
- software developer
String Formatting while print a string
- >>> name="Ram"
- >>> roll=54
- >>> print("I am %s, my roll no is %d" %(name,roll))
- I am Ram, my roll no is 54
String Concatenation
- >>> firstName ='Praveen'
- >>> lastName = "Kumar"
- >>> fullName = firstName + ' ' + lastName
- >>> print(fullName)
- Praveen Kumar
String Repetition
- >>>
- >>> x='Abc'
- >>> print('Repeat x 3 times',x*3)
- ('Repeat x 3 times', 'AbcAbcAbc')
- >>> x*2
- 'AbcAbc'
Conditional Statements
While writing a program in Python or any other programming language, most of the time we come across some scenarios where we have to do some conditional check before executing/processing a block of statements. So to handle such scenarios, we have some conditional statements. They are as follows
- if Statement
- if-else statement
- nested if-else
The if Statement
- >>>
- >>> isHungry=True
- >>> if isHungry:
- print('Yes, I am hungry!')
- Yes, I am hungry!
The if-else Statement
- >>> x = False
- >>> if x == True:
- print('x is True')
- else:
- print('x is False')
- x is False
- >>> person = 'Ramu'
- >>> age = 24
- >>> if person=='Ramu' and age < 20:
- print('Ramu age is less than 20 years')
- else:
- print('Ramu is greater than 20 years')
- print('He is ', age,' years old.')
- >>> Ramu is greater than 20 years
- ('He is ', 24, ' years old.')
The Nested if else Statement
- >>> age=20
- >>> city='New Delhi'
- >>> if(age>20 and city=='New Delhi'):
- print('He is from New Delhi and he is uner 20')
- elif age==20 and city=='New Delhi':
- print('He is from New Delhi and he is 20 years old')
- else:
- print('He is neither fromm New Delhi nor his age is valid')
- He is from New Delhi and he is 20 years old
Looping Statement
for loop
- >>> list=['Pendrive','Mouce','Headphone','Keyboard']
- >>> for item in list:
- print(item)
range() function is used to print all items which lies between start and stop
range(startAfter, stopBefore)
- >>>
- >>> for x in range(0,6):
- print(x)
-
- 1
- 2
- 3
- 4
- 5
range(start, stop, step): To print all numbers which lies between start and stop with the increment of
- >>> for x in range(1,10,2):
- print(x)
- 1
- 3
- 5
- 7
- 9
while loop
-
- >>> print('Example1')
- >>> i=1
- >>> while(i < 5):
- print(i)
- i+=1
- >>> i = 0
- >>> while(i < 100):
- print("List of even numbers:")
- if(i < 100 and i % 2==0):
- print(i)
- i+=1
- >>> list=[1,2,3,4,5]
- >>> i = 1
- >>> while(i <= len(list)):
- print(i,'-',list[i])
- i+=1
Break and Continue with while loop
- >>> i=0
- >>> while(True):
- print(i)
- i+=1
- if(i > 10):
- break
continue
- >>> i=0
- >>> while(True):
- print(i)
- i+=1
- if(i < 25):
- print('continue',i)
- continue
- else:
- break
break & continue
- >>> i=0
- >>> while(True):
- i+=1
- if(i % 2==0):
- print('continue')
- continue
- elif i > 10:
- print('break')
- break
- print(i)
Functions
A function is a block of reusable code, so once a function is defined in a program, we can call it n number of times if required. In python, the way of writing a function is a little different.
A function must have a name and return type like other programming languages, apart from this it may have some arguments or not. In Python, there is keyword def which is used to define a function and it is required for every user-defined functions.
def functionName( [argument is optional]),
#do anything
#print anything
return [expression | string | none]
function with no arguments and return type as none
- >>>
- >>> def sayHello():
- print("Hello Guys");
- return
-
- >>> sayHello()
- Hello Guys
function with an argument and return none
- >>> def square(number):
- print(number**2)
- return
- >>> square(3)
- 9
function with two arguments and return sum of these.
- >>> def add(n1,n2):
- total=n1+n2
- return total
-
- >>> add(100,50)
- 150
Get User Input
- >>> x=input('Enter name: ')
- Enter name: 'Mohan'
- >>> x
- 'Mohan'
- >>> def getName():
- name=input("Please enter your name")
- return "Name: ",name
-
- >>> getName()
- Please enter your name 'Prakash'
- ('Name: ', 'Prakash')
Class and Object
- >>> class Game:
- def getGameName(self):
- return "Football"
-
-
- >>> game=Game() #object instantiation
- >>> game.getGameName() # method calling
- 'Football'
In the above example, there is a class named Game and a method with name getGameName() having a parameter as self. Here self represents the object as a default parameter. To know more about the argument self, click
self parameter
Summary
In this article, we learned about the overview of Python programming like the installation process, program syntax, data types, identifiers, indentations, comments, and Python IDE. Further, we learn about creating web applications using Visual Studio with Python.
If you have any queries, feedback or suggestions, kindly share your valuable thoughts by comment.
Thanks!