Python Programming - Basics
Session – Objective
- Python Features and its Applications
- Python Basics
-Versions
-Variable and Types
-Conditional and Looping structures
-Module based Programming
-Container Objects – Data Storage Objects
-OOP Introduction
-File and Exception handling
INTERNAL
Python
Overview:
-High level , Interpreted, Object Oriented and scripting language
2.Version -Desktop:
Stable: 2.7
Latest: 3.x
Link:https://www.python.org/downloads/release/python-2710/
Desktop Modes:
-IDE
-Command Mode
Supports to code in interactive and scripting style
3.Online Editors:
https://www.onlinegdb.com/online_python_compiler
http://www.codeskulptor.org/
-3- INTERNAL
Variables – Whats New in Python?
• Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
• Python variables do not have to be explicitly declared to reserve memory space.
The declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
INTERNAL
Python - I/O
How to accept the values from user?
Input statement:
-input() –best option
Output statement:
Print statement:
Note: If using 2.7 version then follow the below syntax
print variable/”string to display”
Ex: print a
print “Hi”
If version is 3.5 and above then use as below
print (variable / “String to display”)
Ex: print(a)
print(“Hi”)
print(“Hi”, variable)
In ppt some examples are covered with 2.7 and some are 3.5 above INTERNAL
Conditional Statements - IF ELIF ELSE
Syntax: Example:
if expression: #!/usr/bin/python
statement(s) var1,var2 = 1,100
elif expression: if var1:
statement(s) print("var1 value is:",var1)
else: elif var1:
statement(s) print("var2 value is:",var2)
else:
print("var1 and var2 are not
defined");
INTERNAL
Nested IF
Syntax: Example:
if expression1: #!/usr/bin/python
statement(s) Var1,var2 = 100,200
if expression2: if var1:
statement(s) print ("var1 value is:”,var1)
elif expression3: if var2:
statement(s) print ("var2 value is:”,var2)
else: else:
statement(s) print ("var2 is not defined“)
elif expression4: else:
statement(s) print ("var1 is not defined“)
else:
statement(s) OUTPUT:
var1 value is:100
var2 value is:200
INTERNAL
How Block is identified - Whats new in Python?
INTERNAL
Looping statements
While: Example:
#!/usr/bin/python
while expression: count = 0
statement(s) while count < 9:
count = count + 1
else:
while expression: print “count is not less than 9”
statement(s) print 'The count is:', count
else: print "Good bye!"
statement(s)
OUTPUT:
count is not less than 9
The count is:8
Good bye!
INTERNAL
Looping Statements - Contnd...
For: Example:
#!/usr/bin/python
for iterating_var in sequence: for letter in 'TCSHYD':
statements(s) print( 'Current Letter :', letter)
print ("Good bye!“)
OUTPUT:
for iterating_var in sequence:
Current Letter :T
statements(s)
Current Letter :C
else:
Current Letter :S
statement(s)
Current Letter :H
Current Letter :Y
Current Letter :D
Good bye!
INTERNAL
Loop control statements
Break: Continue:
#!/usr/bin/python #!/usr/bin/python
for letter in 'Python': for letter in 'Python':
if letter == 'h': if letter == 'h':
break ; continue
print 'Current Letter :', letter ; print ('Current Letter :', letter ;)
print "over"; print( "over“)
OUTPUT: OUTPUT:
Current Letter :P Current Letter : P
Current Letter :y Current Letter : y
Current Letter :t Current Letter : t
over Current Letter : o
Current Letter : n
over INTERNAL
Show Loops Ex – with User defined types
Show – DoctorEx without class
INTERNAL
Functions -
Brief the concept with Example
A function is a block of organized, reusable code that is used
to perform a single, related action.
Functions provide better modularity for your application and a
high degree of code reusing.
Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are
called user-defined functions
INTERNAL
Functions
Defining a Function:
Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
INTERNAL
Functions
Syntax:
def functionname( parameters ):
“documentation”
function_suite
return [expression]
Example:
def sample( str ):
“This is my first function”
print (str)
return
INTERNAL
Functions
Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
#!/usr/bin/python
# Function definition is here
def sample( str ):
“This is my first function”
print (str);
return;
# Now you can call printme function
sample("I'm first call to user defined function!");
sample("Again second call to the same function");
docstring=sample.__doc__ INTERNAL
Functions
When the python script is executed, it produces the following result:
I'm first call to user defined function!
Again second call to the same function
This is my first function
INTERNAL
Functions
Pass by reference:
All parameters (arguments) in the Python language are passed by reference. It
means if you change what a parameter refers to within a function, the change
also reflects back in the calling function.
INTERNAL
Functions
#!/usr/bin/python
def changeme( mylist ):
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
INTERNAL
Functions
Function Arguments:
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
INTERNAL
Functions
Required arguments:
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
#!/usr/bin/python
def printme( str ):
print (str);
return;
# Now you can call printme function
printme();
INTERNAL
Functions
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
INTERNAL
Functions
Keyword arguments:
Keyword arguments are related to the function calls. When you use
Keyword arguments in a function call, the caller identifies the arguments by
the parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.
#!/usr/bin/python
def printme( str ):
print (str);
return;
printme( str = "My string");
INTERNAL
Functions
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
INTERNAL
Functions
Default arguments:
A default argument is an argument that assumes a default value if a value is
not provided in the function call for that argument.
#!/usr/bin/python
def printinfo( name, age = 35 ):
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );
INTERNAL
Functions
The return Statement:
The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return None.
#!/usr/bin/python
def sum( arg1, arg2 ):
total = arg1 + arg2
print "Inside the function : ", total
return total;
total = sum( 10, 20 );
print "Outside the function : ", total
INTERNAL
Python - Data Storage Objects – Why?
➢ Lists
➢ Tuples
➢ Dictionary
➢ Set
- 27
INTERNAL
-
Lists
The list type is a container that holds a number of other objects, in a given
order.
Syntax to Create List:-
L = [ ] (or)
L = [expression, …]
Ex:-
L=[1,2,3,4,5,6,7,8]
L1 = ['Java', 'Python', 2015, 2016]
L3=[1,2,[3,4,5],4,5]
Accessing Elements in a List:- L[0] returns 1
List functions: len,max,min, insert, append, reverse, sort etc
- 28
INTERNAL
-
Lists – Ex
INTERNAL
Lists – How to Apply in Real Time –
Show Ex -
INTERNAL
Tuple
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The only difference is that tuples can't be changed.
Creating Tuples:-
T = ()
T = (expression, …)
Ex:-
T=(1,2,3,4,5,6,7,8)
T1 = ('Java', 'Python', 2015, 2016)
T2=(1,2,[3,4,5],4,5)
Accessing Elements in a Tuples:- T[0] returns 1
Tuple also has similar kind of operations as list has .
Execute the programs implemented on list using Tuple?
Note:
Explore the functions on tuple with examples?
- 31
INTERNAL
-
Tuple - Ex
INTERNAL
Tuple – How to Apply in Real Time ?
Show Ex
INTERNAL
Set
A set is a dictionary with no values. It has only unique keys. Its syntax is similar to that for
a dictionary. But we omit the values.
Syntax for Creating Set:-
S = set()
S = {expression, …}
Ex:-
s={1,2,3,4,5,6,7,8}
S1 = {'Java', 'Python', 2015, 2016}
S2=set([1,2,3])
Accessing Elements in a Set:- Using For loop
- 34
INTERNAL
-
Set – How to Apply in Real Time ?
INTERNAL
Dictionary
A dictionary is mutable that can store any number of objects. Dictionaries consist
of pairs (called items) of keys and their corresponding values.
Keys of a particular dictionary are unique while values may not be.
The values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Creating Dictionaries:-
D={}
D={1:'Java',2:'Python',3:'HTML'}
Accessing Elements in a Dictionary:-
D[1] returns 'Java'
D[2] returns 'Python'
Create a dictionary in such a way that, if I give the week day in number I should
be in a position to get Week Day Name, Similarly for Month
- 36
INTERNAL
-
Example
INTERNAL
Dictionary – Ex2
INTERNAL
Dictionary – How to Apply in Real Time ?
Demo on its applications
INTERNAL
Exception Handling
What is an Exception?
What are the issues when an Exception occurs?
How to mitigate the Issue – raised by an Exception?
Examples context for an Exception to get raised? – Who should
aware of this?
INTERNAL
Exception Handling - Ex:
INTERNAL
File Handling - Ex:
INTERNAL
INTERNAL
OOPs Intro
Why OOP Programming?
OOP Features?
-Abstraction
-Technical Implementation of Abstraction :-Encapsulation
-Inheritance
-Polymorphism etc..
Note: Explain the above feature Vs any OOP Program
INTERNAL
OOPs Intro with Classes/Objects
Python has been an object-oriented language from day one. Because of
this, creating and using classes and objects are downright easy.
Creating Classes:
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via
ClassName.__doc__.
The class_suite consists of all the component statements defining class
INTERNAL
Classes/Objects
Python has been an object-oriented language from day one. Because of
this, creating and using classes and objects are downright easy.
Creating Classes:
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via
ClassName.__doc__.
The class_suite consists of all the component statements defining class
members, data attributes and functions.
INTERNAL
Classes/Objects
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
INTERNAL
Classes/Objects
The variable empCount is a class variable whose value would be shared
among all instances of a this class. This can be accessed as
Employee.empCount from inside the class or outside the class.
The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when you create a
new instance of this class.
You declare other class methods like normal functions with the exception
that the first argument to each method is self. Python adds the self
argument to the list for you; you don't need to include it when you call the
methods.
INTERNAL
Classes/Objects
Creating instance objects:
To create instances of a class, you call the class using class name and
pass in whatever arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
INTERNAL
Classes/Objects
Show Example?
INTERNAL
https://dev.mysN.com/downloads/connecto
Python My SQL connectors – Database connectivity
r/python/?os=31
https://dev.mysql.com/downloads/connector/python/?os=31
INTERNAL
https://dev.mysN.com/downloads/connecto
Python My SQL connectors – Database connectivity
r/python/?os=31
https://dev.mysql.com/downloads/connector/python/?os=31
INTERNAL
Python My SQL connectors – Database connectivity
- Run the rpm’s for the installation and verify
Refer the document, “steps to follow - MySQL connectivity.docx”, shared
INTERNAL
Applications - Snapshot
INTERNAL
Applications – Snapshot2
INTERNAL
Applications – Snapshot3
Python's standard library supports many Internet
Python's standard library supports many Internet protocols:
protocols:
HTML and XML
• HTML and XML
JSON
• JSON
E-mail processing.
Python's
Support for FTP, standard
IMAP, and otherlibrary supports
Internet many
protocols.
• E-mail processing.
Easy-to-use Internet
socket protocols:
interface.
HTML and XML
• Support for FTP, IMAP, and other Internet protocols.
JSON
• Easy-to-use socket interface.
E-mail processing.
Support for FTP, IMAP, and other Internet
protocols.
Easy-to-use socket interface.
INTERNAL
Applications – Snapshot4
Scientific and Numeric
Python is widely used in scientific and numeric computing:
• SciPy is a collection of packages for mathematics, science, and
engineering.
• Pandas is a data analysis and modeling library.
• IPython is a powerful interactive shell that features easy editing and
recording of a work session, and supports visualizations and parallel
computing.
• The Software Carpentry Course teaches basic skills for scientific
computing, running bootcamps and providing open-access teaching
materials.
INTERNAL
Applications – Snapshot5
DJango : Tool To design webpages using Python ,rich set of libraries
Python can be used to code for IOT devices : Rasberry PI , Robotics
DJango : Tool To design webpages using
Python Scripting : Python
To interact and perform operations on cloud using AWB
Python can be used to code for IOT
devices : RasberiPI , Robotics
Python Scripting : To interact and perform
operations on cloud using AWB
INTERNAL
Thank You