Date post: | 13-Apr-2017 |
Category: |
Technology |
Upload: | chitu-banchhor |
View: | 221 times |
Download: | 0 times |
Python ProgrammingPython ProgrammingByBy
CHITRAKANT BANCHHORCHITRAKANT BANCHHOR
IT,SCOE,IT,SCOE, PunePune
ReferencesReferences Programming in Python 3 By Mark Summerfield, Addison WesleyProgramming in Python 3 By Mark Summerfield, Addison Wesley
The Quick Python Book By VERNON L. CEDER, Manning PublicationsThe Quick Python Book By VERNON L. CEDER, Manning Publications
Beginning Python From Novice to Professional By Magnus LieBeginning Python From Novice to Professional By Magnus Lie HetlandHetland ,,ApressApress
StepStep--IIPython programmingPython programming
InstallationInstallation
StepStep--IIPython programmingPython programming
InstallationInstallation
Download installerDownload installer•• The first step is to obtain a recent distribution:The first step is to obtain a recent distribution:
www.python.org
Interactive ShellInteractive Shell•• Two variations:Two variations:1.1. IDLE (GUI)IDLE (GUI)2.2. python (command line)python (command line)
Hello World!Hello World! in pythonin python
HelloWorld.pyHelloWorld.py
•• Type statements or expressions at prompt:Type statements or expressions at prompt:
End of Step-IEnd of Step-I
StepStep--IIIIPython programmingPython programming
BasicsBasics
StepStep--IIIIPython programmingPython programming
BasicsBasics
Basic data types in PythonBasic data types in Python
•• Integers (default for numbers)Integers (default for numbers)
•• FloatsFloats
•• StringsStrings
Python and Data TypingPython and Data Typing
1.1. Dynamic typing:Dynamic typing:
•• Python determines the data types in a program automaticallyPython determines the data types in a program automatically
2. Strong typing:2. Strong typing:
•• Example:Example: Python does not allow just append an integer to a string.Python does not allow just append an integer to a string.
first convert the integer to a string itself.first convert the integer to a string itself.
ErrorError
convert the integer to a stringconvert the integer to a stringconvert the integer to a stringconvert the integer to a string
Python keywordPython keyword
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not,
or, pass, print, raise, return, try, while
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not,
or, pass, print, raise, return, try, while
VariablesVariables No declaration:No declaration: Variables are not declared.Variables are not declared.
Creates at assignment :Creates at assignment : The variable is created when first time a value isThe variable is created when first time a value isassigned into it.assigned into it.
Variables are references to objects:Variables are references to objects:
In python everything is an object.In python everything is an object.
No declaration:No declaration: Variables are not declared.Variables are not declared.
Creates at assignment :Creates at assignment : The variable is created when first time a value isThe variable is created when first time a value isassigned into it.assigned into it.
Variables are references to objects:Variables are references to objects:
In python everything is an object.In python everything is an object.
InputInput
Conversion methodsConversion methods•• The string can be converted by using the conversion methodsThe string can be converted by using the conversion methods intint(string),(string),
floatfloat(string), etc.(string), etc.
Conditional LoopsConditional Loops
Counting and conditional loopsCounting and conditional loops
Types of loops
Counting Conditional
for in Pythonfor in Pythonand many other languagesand many other languages
while in Python and many other languageswhile in Python and many other languages
for is used when the number offor is used when the number ofcycles is known in advancecycles is known in advance
The conditional loop is used when it is notThe conditional loop is used when it is notknown how many cycles will be needed.known how many cycles will be needed.
Conditions and theConditions and the elifelif statementstatement•• Python supports typical if else statements in addition it hasPython supports typical if else statements in addition it has elifelif statement.statement.
if <logical_expression_1>:<do_action_1>
elif <logical_expression_2>:<do_action_2>
else:<do_action_3>
if <logical_expression_1>:<do_action_1>
elif <logical_expression_2>:<do_action_2>
else:<do_action_3>
if <logical_expression_1>:<do_action_1>
else:if <logical_expression_2>:<do_action_2>
else:<do_action_3>
if <logical_expression_1>:<do_action_1>
elif <logical_expression_2>:<do_action_2>
else:<do_action_3>
if <logical_expression_1>:<do_action_1>
else:if <logical_expression_2>:<do_action_2>
else:<do_action_3>
if <logical_expression_1>:<do_action_1>
elif <logical_expression_2>:<do_action_2>
else:<do_action_3>
The while loopThe while loop•• The while loop in Python has the following general format:The while loop in Python has the following general format:
while <logical_expression> :<sequence_of_commands>
The break statementThe break statement•• The break statement can be used to exit a loop at any time.The break statement can be used to exit a loop at any time.
The continue statementThe continue statement•• Sometimes we know that finishing all commands in the loop’s body is notSometimes we know that finishing all commands in the loop’s body is not
necessary.necessary.
•• Python has the continue command for this.Python has the continue command for this.
Logic and ProbabilityLogic and Probability
True and FalseTrue and False•• Python has a builtPython has a built--in data type,in data type, boolbool, for expressing True and False values., for expressing True and False values.
•• Certain expressions in Python, those that use comparison operators, evaluateCertain expressions in Python, those that use comparison operators, evaluateto True or False.to True or False.
Boolean variablesBoolean variables•• Similar to numbers and strings, Boolean values can be stored in variables.Similar to numbers and strings, Boolean values can be stored in variables.
Symbol Meaning
>
>=
<=
<
==
!=
<> not equal to (same as !=)
Boolean operationsBoolean operations•• If A and B are logical expressions, then A and B is True only if A as well as BIf A and B are logical expressions, then A and B is True only if A as well as B
are True, otherwise it is False:are True, otherwise it is False:
End of Step-IIEnd of Step-IIEnd of Step-IIEnd of Step-II
StepStep--IIIIIIPython programmingPython programming
User defined functionsUser defined functions
StepStep--IIIIIIPython programmingPython programming
User defined functionsUser defined functions
Defining new functionsDefining new functions•• In Python, the definition of a new function begins with the keywordIn Python, the definition of a new function begins with the keyword defdef..
General syntax (General syntax ( locallocal oror global functionsglobal functions ):):
def functionName(parameters):statements
Passing arbitrary argumentsPassing arbitrary arguments•• Python does not require that we specify the type of function arguments.Python does not require that we specify the type of function arguments.
•• The functionThe function sum(a, b)sum(a, b) works for real numbers, complex numbers, vectors,works for real numbers, complex numbers, vectors,strings, and any other objects where the operation ’+’ is defined.strings, and any other objects where the operation ’+’ is defined.
Returning multiple valuesReturning multiple values•• Python functions can return multiple values which often comes handy.Python functions can return multiple values which often comes handy.
•• Example:Example: following function returns multiple values:following function returns multiple values:
•• We can also store the returned values in separate variables:We can also store the returned values in separate variables:
Using default argumentsUsing default arguments
•• Few rules to remember:Few rules to remember:
1.1. Default arguments need to be introduced after standard (nonDefault arguments need to be introduced after standard (non--default)default)arguments.arguments.
•• The following code will result into an error:The following code will result into an error:
def add( a=5, b):return a + b
•• If multiple default arguments are present, they have to follow the nonIf multiple default arguments are present, they have to follow the non--default ones.default ones.
def add(x, a=2, b=3):return x + a + b
print add(1)print add(1)print add(5, 6)print add(5, 6)print add(1, a = 6)print add(1, a = 6)print add(1, b = 6)print add(1, b = 6)
End of Step-IIIEnd of Step-IIIEnd of Step-IIIEnd of Step-III
StepStep--IVIVPython programmingPython programming
Data types, data structuresData types, data structures
StepStep--IVIVPython programmingPython programming
Data types, data structuresData types, data structures
•• Python has a great set of useful data types.Python has a great set of useful data types.
•• Python's data types are built in the core of the language.Python's data types are built in the core of the language.
Python data typesPython data types
Boolean valuesBoolean values•• In python programming language, the Boolean dataIn python programming language, the Boolean data--type is a primitive datatype is a primitive data--
type having one of two values:type having one of two values: TrueTrue oror FalseFalse
•• There is another special data typeThere is another special data type -- NoneNone.
•• NoneNone data typedata type :: means non existent, not known or empty.means non existent, not known or empty.
NoneNone
The function does nothing.The function does nothing.
It does not explicitly return any value.It does not explicitly return any value.
Such a function will implicitly return None object.Such a function will implicitly return None object.
•• Python programming language has:Python programming language has:
1.1. integer numbers,integer numbers,2.2. floating point numbersfloating point numbers3.3. complex numbers.complex numbers.
NumbersNumbers•• Python programming language has:Python programming language has:
1.1. integer numbers,integer numbers,2.2. floating point numbersfloating point numbers3.3. complex numbers.complex numbers.
•• Integers:Integers:
•• Floats:Floats:
•• Imaginary:Imaginary:
Collection Data TypesCollection Data Types1. Sequence Types
Tuples Named Tuples Lists
2. Set Types Sets Frozen Sets
2. Set Types Sets Frozen Sets
3. Mapping Types Dictionaries Default Dictionaries Ordered Dictionaries
4. Iterating and Copying Collections Iterators and Iterable Operations and Functions Copying Collections
SequenceSequenceSequenceSequence
Sequence OverviewSequence Overview•• Python has six builtPython has six built--in types of sequences.in types of sequences.
1. Lists
2. Tuples
3. Strings
4. Unicode Strings
5. Buffer objects
6. Range objects
1. Lists
2. Tuples
3. Strings
4. Unicode Strings
5. Buffer objects
6. Range objects
The most common ones:The most common ones: lists,lists, tuplestuples
TuplesTuples
•• A Tuple is a sequence that can not be changed.A Tuple is a sequence that can not be changed.
TuplesTuples
1.1. Creating a Tuple:Creating a Tuple:
TuplesTuples are normally created by assigning a sequence of commaare normally created by assigning a sequence of comma--separatedseparatedvalues to a variable, which is known as sequence packingvalues to a variable, which is known as sequence packing
•• TuplesTuples are used for sequences of data that does not changeare used for sequences of data that does not change
•• Example:Example: The names of weekdays,The names of weekdays, Names of months.Names of months.
2. Changing the Values in a Tuple :2. Changing the Values in a Tuple :
A tuple can contain text strings, integers, real numbers, otherA tuple can contain text strings, integers, real numbers, other tuplestuples, etc., etc.
3. A tuple can be heterogeneous :3. A tuple can be heterogeneous :
•• The length of aThe length of a tupletuple is obtained using the functionis obtained using the function lenlen():():
len( months )
ListsLists
ListsLists•• Lists are similar toLists are similar to tuplestuples..
•• The only difference is that we can change a list.The only difference is that we can change a list.
•• Lists can be changed with following operations:Lists can be changed with following operations:
Adding and deleting entries,Adding and deleting entries, Reorder items in a list, etc.Reorder items in a list, etc.
•• Lists are similar toLists are similar to tuplestuples..
•• The only difference is that we can change a list.The only difference is that we can change a list.
•• Lists can be changed with following operations:Lists can be changed with following operations:
Adding and deleting entries,Adding and deleting entries, Reorder items in a list, etc.Reorder items in a list, etc.
About ListAbout List•• A list is an ordered, commaA list is an ordered, comma--separated list of items enclosed inseparated list of items enclosed in
square brackets.square brackets.
•• Items need not all be of the same type.Items need not all be of the same type.
•• An item can also be another list.An item can also be another list.
•• A list is an ordered, commaA list is an ordered, comma--separated list of items enclosed inseparated list of items enclosed insquare brackets.square brackets.
•• Items need not all be of the same type.Items need not all be of the same type.
•• An item can also be another list.An item can also be another list.
Creating a List:Creating a List:
Modifying a List:Modifying a List:
Lists:Lists: deldel
Lists:Lists: appendappend
Lists:Lists: pop()pop()•• The function pop() deletes an item and returns it for further use (as opposed to delThe function pop() deletes an item and returns it for further use (as opposed to del
which just deletes the item):which just deletes the item):
Lists:Lists: insert()insert()••New item can be inserted at an arbitrary position using the function insert():New item can be inserted at an arbitrary position using the function insert():
Output
Lists:Lists: sort()sort()••A list can be sorted via the function sort():A list can be sorted via the function sort():
Output
Lists:Lists: reverse()reverse()••The function reverse() reverses a list:The function reverse() reverses a list:
Output
Lists:Lists: count()count()•• The function count() counts the number of occurrences of an item in the list:The function count() counts the number of occurrences of an item in the list:
Output
Lists: indexLists: index()()• The function index() returns the index of the first occurrence of an item:
Output
StringString
StringsStrings•• By a string we mean a text surrounded by double or single quotes:By a string we mean a text surrounded by double or single quotes:
Example-1: "this is a string1“
Example-2: ’this is a string2’
Example-1: "this is a string1“
Example-2: ’this is a string2’
Using quotesUsing quotes•• Let us now understand how to use quotes in strings.Let us now understand how to use quotes in strings.
•• The safest way is to use them with a backslash:The safest way is to use them with a backslash:
print ( “ I saidprint ( “ I said \\"yes"yes\\“ to him.“ )“ to him.“ )
Multiline strings and backslashesMultiline strings and backslashes•• If we want to use multiline strings, the best way is to enclose them in tripleIf we want to use multiline strings, the best way is to enclose them in triple
quotes:quotes:
Concatenation and repetitionConcatenation and repetition•• Strings can be concatenated (glued together) with the ’+’ operator, andStrings can be concatenated (glued together) with the ’+’ operator, and
repeated with the ’*’ operator.repeated with the ’*’ operator.
Starting String index:Starting String index: 00
Negative numbers as String indices:Negative numbers as String indices:
--11 :: for the last elementfor the last element
--22 : for the second last element: for the second last element
Referring to letters by their indicesReferring to letters by their indices
Negative numbers as String indices:Negative numbers as String indices:
--11 :: for the last elementfor the last element
--22 : for the second last element: for the second last element
Parsing strings with the for loopParsing strings with the for loop•• The length of a string is obtained using the functionThe length of a string is obtained using the function lenlen().().
Slicing stringsSlicing strings•• Python makes it easy to access substringsPython makes it easy to access substrings –– this is called slicing:this is called slicing:
output
String_1[ : 12 ] Omitting the first index in a slice defaults to zero
String_1[0 : ] Omitting the second index defaults to length of the string
SetsSets•• An unordered collection with no duplicate elementsAn unordered collection with no duplicate elements
Removing DuplicatesRemoving Duplicates
Here, you assign some values and remove the duplicates by assigning them to a set:Here, you assign some values and remove the duplicates by assigning them to a set:
Set operationsSet operations
Symmetric operation:Symmetric operation:
Returns a new set that has every item that is in set s and every item that is inReturns a new set that has every item that is in set s and every item that is inset t, but excluding items that are in both setsset t, but excluding items that are in both sets
Mapping TypesMapping Types
DictionaryDictionary
DictionariesDictionaries
Dictionary = {“Name” : 123456
……………………………
}
•• A dictionary is an unordered collection of zero or more keyA dictionary is an unordered collection of zero or more key––value pairsvalue pairs
Dictionary = {“Name” : 123456
……………………………
}
•• An empty dictionary D is defined as follows :An empty dictionary D is defined as follows :
D = { }
Dictionaries are mutable:Dictionaries are mutable: we can easily add or remove items.we can easily add or remove items.
Dictionaries can not be slicedDictionaries can not be sliced:: Dictionaries are unordered andDictionaries are unordered andhave no notion of index position and so cannot be sliced orhave no notion of index position and so cannot be sliced or stridedstrided..
About DictionaryAbout Dictionary
Other operationsOther operations
We can check if a key is in the dictionary:We can check if a key is in the dictionary:
To get the list of all keys:To get the list of all keys:
we can also get the list of all valueswe can also get the list of all values
Thank You!Thank You!
CHITRAKANT BANCHHORCHITRAKANT BANCHHOR
Thank You!Thank You!