Preliminary Practices On Python Programming

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"
  1. >>> print("Hello Python")  
  2. Hello Python  
Here ( >>>) triple angle brackets represent the python prompt where one can execute any python command or expression
 
IDLE Prompt 
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
 
CreateNewFile 
 
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 
 
SaveProgram 
 
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
 
ExecuteProgram 
 
Output
  1. Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 201620:42:59) [MSC v.1500 32 bit (Intel)] on win32  
  2. Type "copyright""credits" or "license()" for more information.  
  3. >>>   
  4. ================ RESTART: C:/Users/PRAVEEN/Desktop/python.py ================  
  5. Hello Python  
  6. 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 "
 
PythonShell
 
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 
  1. >>> print('Indetifires Observation:')
  2. Indetifires Observation:
  3. >>> name='Mohit'
  4. >>> Name='Krishna'
  5. >>> _name='Rajesh'
  6. >>> _Name='Kunal'
  7. >>> name2='kumar'
  8. >>> Name2='Singh'
  9. >>> _name2='Gupta'
  10. >>> _Name2='Kapur'
  11. >>> print(name +' '+ name2)
  12. Mohit kumar
  13. >>> print(Name +' '+ Name2)
  14. Krishna Singh
  15. >>> print(_name +' '+ _name2)
  16. Rajesh Gupta
  17. >>> print(_Name +' '+ _Name2)
  18. Kunal Kapur
Invalid Identifires (Wrong Identifier)
  1. >>> 1name='Ganga'
  2. SyntaxError: invalid syntax #variable name must not be start with a number
  3. >>> 2_name='Rohan'
  4. SyntaxError: invalid syntax
  5. >>> @name='uiraj'
  6. SyntaxError: invalid syntax #variable name must not have @ or any special char
  7. >>> name@='Neeraj'
  8. SyntaxError: invalid syntax
  9. >>> $name='Kritika'
  10. 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
 
Indentation
 
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
    1. >>> #Learn Python Programming  
  • 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
    1. """Learn 
    2. Python 
    3. Programming 
    4. Here"""  
    5.   
    6. language="Python"  
    7.   
    8. '''Learn Python 
    9. Programming 
    10. Here'''  
    11.   
    12. 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.
 
Example
  1. >>> int x=10 #wrong way to assign a value in a variable   
  2. >>> x=10 #Right way  
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: 
    1. >>> isActive = True # or False   
  • Integer
     
    Any non-floating numbers in Python are integer type
     
    Example
    1. >>> x = 5  
  • Float 
     
    Any numbers which have some floating value are float type
     
    Example
    1. >>> x = 2.7   
  • 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
    1. >>> x = fractions.Fraction(15)  
    2. >>> print(x)  
    3. >>> 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
    1. >>> x = 4 + 2j   
  • 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
    1. >>> companies = ['Microsoft''IBM''TCS''AON''Google']  
    2. >>> x = [ 'abc''efg''123'True100 ]   
  • 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
    1. >>> companies = ( 'Microsoft''IBM''TCS''AON', 'Google)  
    2. >>> x = [ 'abc''efg''123'True100 ]  
  • 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
    1. >>> 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
    1. >>> a = { 12345}  
    2. >>> 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
    1. >>> me= ''I am Praveen'  
    2. >>> me = "I am Praveen"  
    3. >>> me = ' ' ' Hello Friends,   
    This is the example of multi-line strings in Python programming using a triple single quote. ' ' '
    1. >>> 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
  1. >>> x=True
  2. >>> print(x)
  3. True
# check the type of variable x
  1. >>> x=True
  2. >>> type(x)
  3. <class 'bool'>
  4. >>> print("The type of variable 'x' is",type(x))
  5. The type of variable 'x' is <class 'bool'>
# checking boolean condition: 1st Way
  1. >>> x=True
  2. >>> if x:
  3.       print("The value of x is: ",x);
  4. The value of x is: True
# checking boolean condition: 2nd Way
  1. >>> x=True
  2. >>> if x == True:
  3.       print("The value of x is: ",x);
  4. The value of x is: True
# checking boolean condition: 3rd Way
  1. >>> x=True
  2. >>> if x == 1:
  3. print("The result of '(x == 1)' is: ",x);
  4. 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
  1. >>> x=True
  2. >>> y=True
  3. >>> print("x + y is: ", x + y)
  4. x + y is: 2
  5. >>> print("x - y is:", x - y)
  6. x - y is: 0
  7. >>> print("x * y is: ", x * y)
  8. x * y is: 1
  9. >>> print("x / y is: ", x / y)
  10. x / y is: 1.0
  11. >>> print("x % y is: ", x % y)
  12. x % y is: 0
# Ternary condition with Boolean Type
  1. >>> x=True;
  2. >>> x = False if x==True else True
  3. >>> print('value of x is: ',x)
  4. value of x is: False
Integer
 
# assign numeric value into a variable x
  1. x=5
  2. print(x)
  3. type(x)
  4. print("Type of 'x' is: ",type(x))
Float
 
# assign float value into a variable x
  1. >>> #Float: Working with float type
  2. >>> x=5.2
  3. >>> print("x = ",x)
  4. x = 5.2
  5. >>> print("Type of 'x' is: ",type(x))
  6. 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
  1. >>> import fractions  
  2. >>> x=fractions.Fraction(1,5)  
  3. >>> x  
  4. Fraction(15)  
  5. >>> print(x)  
  6. 1/5  
Complex Number
  1. >>> x = 2 + 4j  
  2. >>> y = 2 + 2j  
  3. >>> z = x + y  
  4. >>> print(z)  
  5. (4+6j)   
List
 
Add a list of strings and print its items using for loop, further we will read more about looping statement
  1. >>> companies = ['Microsoft''IBM''TCS''AON''Google']  
  2. >>> for i in range(len(companies)):  
  3.     index=i+1  
  4.     print(index,companies[i])    
  5. (1'Microsoft')  
  6. (2'IBM')  
  7. (3'TCS')  
  8. (4'AON')  
  9. (5'Google')   
Add new items in existing list
  1. >>> companies.append(['C# Corner'])  
  2. >>> print(companies)  
  3. ['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
  1. >>> companies = ['Microsoft''IBM''TCS''AON''Google']  
  2. >>> companies[3]='AON Hewitt'  
  3. >>> print(companies)  
  4. ['Microsoft''IBM''TCS''AON Hewitt''Google']   
 Delete item from list
  1. >>> x=[0,1,2,3,4,5]  
  2. >>> del x[0]  
  3. >>> print x  
  4. [12345]  
Tuples
 
It is like a read-only list whose element can not be updated once declared 
  1. >>> _tuple = (1,2,3,4,5)  
  2. >>> _tuple  
  3. (12345)  
  4. >>> _tuple[0]  
  5. 1  
  6. >>> _tuple[0]=10  
  7.   
  8. Traceback (most recent call last):  
  9.   File "<pyshell#16>", line 1in <module>  
  10.     _tuple[0]=10  
  11. TypeError: 'tuple' object does not support item assignment  
Delete tupple 
  1. >>> # Delete tuple  
  2. >>> _tuple=(1,2,3,4,5)  
  3. >>> del _tuple  
Dictionary
 
Declare a dictionary type variable with named student 
  1. >>> student={'Name':'Rohan','Roll':4206}  
  2. >>> for key in student:  
  3.     print(student[key])  
  4. Rohan  
  5. 4206   
To Create empty dictionary
  1. >>> # empty {} braces is used to create empty dictionary without any key and value  
  2. >>> student = {}  
Remove Item from dictionary 
  1. >>># Remove item  
  2. >>> student.pop('Contact')  
  3. '9700000081'  
  4. >>> print(student)  
  5. {'Name''Rohan''Roll'4206}  
Remove all items from the dictionary
  1. >>> student.clear()  
  2. >>> student  
  3. {}  
Set
 
Create Set 
  1. >>> #Creaate Set  
  2. >>> teamA={'Raman','Shyam','Vijay'}  
  3. >>> teamB={'Rohit','Raman','Shekar','Arjun','Vijay'}  
  4. >>> print(teamA,teamB)  
  5. (set(['Raman''Vijay''Shyam']), set(['Raman''Rohit''Shekar''Vijay''Arjun']))    
 Add Item into a Set variable
  1. >>> teamA.add('Jeny')  
  2. >>> teamA  
  3. set(['Raman''Jeny''Vijay''Shyam'])  
Add multiple Items in a Set variable
  1. >>> teamA={'Raman','Shyam','Vijay'}  
  2. >>> teamA.update(['Praveen','Rahul'])  
  3. >>> teamA  
  4. 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. 
  1. >>> x=set(['a','e','i','o','u','x','z'])  
  2. >>> print(x)  
  3. set(['a''e''i''o''u''x''z'])  
  4. >>> # discard()  
  5. >>> x.discard(x)  
  6. >>> x  
  7. set(['a''e''i''o''u''x''z'])  
  8. >>> x.discard('x')  
  9. >>> x  
  10. set(['a''e''i''o''u''z'])  
  11. >>> x.remove('z')  
  12. >>> #Again discard a item which is not exists in a this set  
  13. >>> x.discard('m')  
  14. >>> #Now remove an item which is not exists in a this set  
  15. >>> x.remove('m')  
  16.   
  17. Traceback (most recent call last):  
  18.   File "<pyshell#25>", line 1in <module>  
  19.     x.remove('m' 
  20. 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. 
  1. >>> developer={'Ram','Shyam','Krishna','Praveen'}  
  2. >>> author={'Praveen','Ramesh'}  
  3. >>> #Union with developer and author  
  4. >>> developer.union(author)  
  5. set(['Krishna''Ramesh''Shyam''Praveen''Ram'])  
  6. >>> author.union(developer)  
  7. 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. 
  1. >>> developer | author  
  2. set(['Krishna''Ramesh''Shyam''Praveen''Ram'])  
  3. >>> author | developer  
  4. set(['Krishna''Ramesh''Shyam''Praveen''Ram'])    
Intersection: Intersection of two sets represents all common elements which exists in both sets.
  1. >>> developer.intersection(author)  
  2. set(['Praveen'])   
Intersections of two sets 
 
We can do the same result by using bitwise AND ( & ) OPERATOR as well. Let's see how it works.  
  1. >>> developer & author  
  2. set(['Praveen'])  
Remove All Items
 
clear(): this function is used to remove all items of a sets.
  1. >>> developer.clear()  
  2. >>> developer  
  3. set([])    
Strings
 
String Printing: either we can put a string into single quotes or double.
  1. >>> #Print a string using single quote  
  2. >>> print('Hello Python')  
  3. Hello Python  
  4. >>> #Print a string using double quote  
  5. >>> print("Hello Python")  
  6. Hello Python  
Multi-line string
 
We can use triple single quotes or double quotes to assign a variable with multi-line strings. 
  1. >>> about='''I am a 
  2. software developer'''  
  3. >>> print(about)  
  4. I am a  
  5. software developer  
 String Formatting while print a string 
  1. >>> name="Ram"  
  2. >>> roll=54  
  3. >>> print("I am %s, my roll no is %d" %(name,roll))  
  4. I am Ram, my roll no is 54  
String Concatenation
  1. >>> firstName ='Praveen'  
  2. >>> lastName = "Kumar"  
  3. >>> fullName = firstName + ' ' + lastName  
  4. >>> print(fullName)  
  5. Praveen Kumar  
String Repetition 
  1. >>> # String Repeatation  
  2. >>> x='Abc'  
  3. >>> print('Repeat x 3 times',x*3)  
  4. ('Repeat x 3 times''AbcAbcAbc')  
  5. >>> x*2  
  6. '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
  1. >>> #Example: if statement
  2. >>> isHungry=True
  3. >>> if isHungry:
  4.       print('Yes, I am hungry!')
  5. Yes, I am hungry!
The if-else Statement
  1. >>> x = False
  2. >>> if x == True:
  3.       print('x is True')
  4.     else:
  5.       print('x is False')
  6. x is False
  1. >>> person = 'Ramu'
  2. >>> age = 24
  3. >>> if person=='Ramu' and age < 20:
  4.        print('Ramu age is less than 20 years')
  5.     else:
  6.        print('Ramu is greater than 20 years')
  7.     print('He is ', age,' years old.')
  8. >>> Ramu is greater than 20 years
  9. ('He is ', 24, ' years old.')
The Nested if else Statement
  1. >>> age=20
  2. >>> city='New Delhi'
  3. >>> if(age>20 and city=='New Delhi'):
  4.       print('He is from New Delhi and he is uner 20')
  5.    elif age==20 and city=='New Delhi':
  6.       print('He is from New Delhi and he is 20 years old')
  7.    else:
  8.       print('He is neither fromm New Delhi nor his age is valid')
  9. He is from New Delhi and he is 20 years old
Looping Statement
 
for loop
  1. >>> list=['Pendrive','Mouce','Headphone','Keyboard']
  2. >>> for item in list:
  3. print(item)
range() function is used to print all items which lies between start and stop
 
range(startAfter, stopBefore) 
  1. >>> # To Print from 1 to 5
  2. >>> for x in range(0,6):
  3. print(x)
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
range(start, stop, step): To print all numbers which lies between start and stop with the increment of 
  1. >>> for x in range(1,10,2):  
  2.             print(x)  
  3. 1  
  4. 3  
  5. 5  
  6. 7  
  7. 9   
while loop
  1. # while loop
  2. >>> print('Example1')
  3. >>> i=1
  4. >>> while(i < 5):
  5.       print(i)
  6. i+=1
  1. >>> i = 0
  2. >>> while(i < 100):
  3.       print("List of even numbers:")
  4.       if(i < 100 and i % 2==0):
  5.          print(i)
  6.      i+=1
  1. >>> list=[1,2,3,4,5]
  2. >>> i = 1
  3. >>> while(i <= len(list)):
  4.       print(i,'-',list[i])
  5.       i+=1
Break and Continue with while loop
  1. >>> i=0
  2. >>> while(True):
  3.       print(i)
  4.       i+=1
  5.       if(i > 10):
  6.          break
continue
  1. >>> i=0
  2. >>> while(True):
  3.       print(i)
  4.       i+=1
  5.       if(i < 25):
  6.          print('continue',i)
  7.          continue
  8.       else:
  9.          break
break & continue
  1. >>> i=0  
  2. >>> while(True):  
  3.       i+=1  
  4.       if(i % 2==0):  
  5.          print('continue')  
  6.          continue  
  7.       elif i > 10:  
  8.          print('break')  
  9.          break  
  10.       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 
  1. >>> # without argument and return type  
  2. >>> def sayHello():  
  3.     print("Hello Guys");  
  4.     return  
  5.   
  6. >>> sayHello()  
  7. Hello Guys  
function with  an argument and return none 
  1. >>> def square(number):  
  2.     print(number**2)  
  3.         return   
  4. >>> square(3)  
  5. 9
function with two arguments and return sum of these. 
  1. >>> def add(n1,n2):  
  2.     total=n1+n2  
  3.     return total  
  4.   
  5. >>> add(100,50)  
  6. 150  
Get User Input 
  1. >>> x=input('Enter name: ')  
  2. Enter name: 'Mohan'  
  3. >>> x  
  4. 'Mohan'  
  1. >>> def getName():  
  2.     name=input("Please enter your name")  
  3.     return "Name: ",name  
  4.   
  5. >>> getName()  
  6. Please enter your name 'Prakash'  
  7. ('Name: ''Prakash')  
Class and Object 
  1. >>> class Game:  
  2.     def getGameName(self):  
  3.         return "Football"  
  4.   
  5.       
  6. >>> game=Game()  #object instantiation
  7. >>> game.getGameName()    # method calling
  8. '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! 


Recommended Free Ebook
Similar Articles