+ All Categories
Home > Technology > Python programming under_windows

Python programming under_windows

Date post: 13-Apr-2017
Category:
Upload: chitu-banchhor
View: 221 times
Download: 0 times
Share this document with a friend
117
Python Programming Python Programming By By CHITRAKANT BANCHHOR CHITRAKANT BANCHHOR IT,SCOE, IT,SCOE, Pune Pune
Transcript
Page 1: Python programming under_windows

Python ProgrammingPython ProgrammingByBy

CHITRAKANT BANCHHORCHITRAKANT BANCHHOR

IT,SCOE,IT,SCOE, PunePune

Page 2: Python programming under_windows

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

Page 3: Python programming under_windows

StepStep--IIPython programmingPython programming

InstallationInstallation

StepStep--IIPython programmingPython programming

InstallationInstallation

Page 4: Python programming under_windows

Download installerDownload installer•• The first step is to obtain a recent distribution:The first step is to obtain a recent distribution:

www.python.org

Page 5: Python programming under_windows
Page 6: Python programming under_windows

Interactive ShellInteractive Shell•• Two variations:Two variations:1.1. IDLE (GUI)IDLE (GUI)2.2. python (command line)python (command line)

Page 7: Python programming under_windows

Hello World!Hello World! in pythonin python

Page 8: Python programming under_windows

HelloWorld.pyHelloWorld.py

Page 9: Python programming under_windows
Page 10: Python programming under_windows

•• Type statements or expressions at prompt:Type statements or expressions at prompt:

Page 11: Python programming under_windows

End of Step-IEnd of Step-I

Page 12: Python programming under_windows

StepStep--IIIIPython programmingPython programming

BasicsBasics

StepStep--IIIIPython programmingPython programming

BasicsBasics

Page 13: Python programming under_windows

Basic data types in PythonBasic data types in Python

•• Integers (default for numbers)Integers (default for numbers)

Page 14: Python programming under_windows

•• FloatsFloats

Page 15: Python programming under_windows

•• StringsStrings

Page 16: Python programming under_windows

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

Page 17: Python programming under_windows

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

Page 18: Python programming under_windows

convert the integer to a stringconvert the integer to a stringconvert the integer to a stringconvert the integer to a string

Page 19: Python programming under_windows

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

Page 20: Python programming under_windows

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.

Page 21: Python programming under_windows

InputInput

Page 22: Python programming under_windows

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.

Page 23: Python programming under_windows

Conditional LoopsConditional Loops

Page 24: Python programming under_windows

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.

Page 25: Python programming under_windows

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>

Page 26: Python programming under_windows

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>

Page 27: Python programming under_windows

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>

Page 28: Python programming under_windows
Page 29: Python programming under_windows

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.

Page 30: Python programming under_windows

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.

Page 31: Python programming under_windows

Logic and ProbabilityLogic and Probability

Page 32: Python programming under_windows

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.

Page 33: Python programming under_windows

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.

Page 34: Python programming under_windows

Symbol Meaning

>

>=

<=

<

==

!=

<> not equal to (same as !=)

Page 35: Python programming under_windows

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:

Page 36: Python programming under_windows

End of Step-IIEnd of Step-IIEnd of Step-IIEnd of Step-II

Page 37: Python programming under_windows

StepStep--IIIIIIPython programmingPython programming

User defined functionsUser defined functions

StepStep--IIIIIIPython programmingPython programming

User defined functionsUser defined functions

Page 38: Python programming under_windows

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..

Page 39: Python programming under_windows

General syntax (General syntax ( locallocal oror global functionsglobal functions ):):

def functionName(parameters):statements

Page 40: Python programming under_windows
Page 41: Python programming under_windows

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.

Page 42: Python programming under_windows

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:

Page 43: Python programming under_windows

•• We can also store the returned values in separate variables:We can also store the returned values in separate variables:

Page 44: Python programming under_windows

Using default argumentsUsing default arguments

Page 45: Python programming under_windows

•• 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

Page 46: Python programming under_windows

•• 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)

Page 47: Python programming under_windows

End of Step-IIIEnd of Step-IIIEnd of Step-IIIEnd of Step-III

Page 48: Python programming under_windows

StepStep--IVIVPython programmingPython programming

Data types, data structuresData types, data structures

StepStep--IVIVPython programmingPython programming

Data types, data structuresData types, data structures

Page 49: Python programming under_windows

•• 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

Page 50: Python programming under_windows

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

Page 51: Python programming under_windows
Page 52: Python programming under_windows

•• 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.

Page 53: Python programming under_windows

•• 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.

Page 54: Python programming under_windows

•• Integers:Integers:

Page 55: Python programming under_windows

•• Floats:Floats:

Page 56: Python programming under_windows

•• Imaginary:Imaginary:

Page 57: Python programming under_windows

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

Page 58: Python programming under_windows

SequenceSequenceSequenceSequence

Page 59: Python programming under_windows

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

Page 60: Python programming under_windows

TuplesTuples

Page 61: Python programming under_windows

•• A Tuple is a sequence that can not be changed.A Tuple is a sequence that can not be changed.

TuplesTuples

Page 62: Python programming under_windows

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

Page 63: Python programming under_windows

•• 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 :

Page 64: Python programming under_windows

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 :

Page 65: Python programming under_windows
Page 66: Python programming under_windows

•• The length of aThe length of a tupletuple is obtained using the functionis obtained using the function lenlen():():

len( months )

Page 67: Python programming under_windows

ListsLists

Page 68: Python programming under_windows

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.

Page 69: Python programming under_windows

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.

Page 70: Python programming under_windows

Creating a List:Creating a List:

Page 71: Python programming under_windows
Page 72: Python programming under_windows

Modifying a List:Modifying a List:

Page 73: Python programming under_windows

Lists:Lists: deldel

Page 74: Python programming under_windows

Lists:Lists: appendappend

Page 75: Python programming under_windows
Page 76: Python programming under_windows

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):

Page 77: Python programming under_windows
Page 78: Python programming under_windows
Page 79: Python programming under_windows

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():

Page 80: Python programming under_windows

Output

Page 81: Python programming under_windows

Lists:Lists: sort()sort()••A list can be sorted via the function sort():A list can be sorted via the function sort():

Output

Page 82: Python programming under_windows

Lists:Lists: reverse()reverse()••The function reverse() reverses a list:The function reverse() reverses a list:

Output

Page 83: Python programming under_windows

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:

Page 84: Python programming under_windows

Output

Page 85: Python programming under_windows

Lists: indexLists: index()()• The function index() returns the index of the first occurrence of an item:

Output

Page 86: Python programming under_windows

StringString

Page 87: Python programming under_windows

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’

Page 88: Python programming under_windows

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.“ )

Page 89: Python programming under_windows

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:

Page 90: Python programming under_windows

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.

Page 91: Python programming under_windows

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

Page 92: Python programming under_windows
Page 93: Python programming under_windows
Page 94: Python programming under_windows

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().().

Page 95: Python programming under_windows
Page 96: Python programming under_windows
Page 97: Python programming under_windows
Page 98: Python programming under_windows

Slicing stringsSlicing strings•• Python makes it easy to access substringsPython makes it easy to access substrings –– this is called slicing:this is called slicing:

Page 99: Python programming under_windows

output

Page 100: Python programming under_windows

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

Page 101: Python programming under_windows

SetsSets•• An unordered collection with no duplicate elementsAn unordered collection with no duplicate elements

Page 102: Python programming under_windows

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:

Page 103: Python programming under_windows

Set operationsSet operations

Page 104: Python programming under_windows

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

Page 105: Python programming under_windows

Mapping TypesMapping Types

Page 106: Python programming under_windows

DictionaryDictionary

Page 107: Python programming under_windows

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

……………………………

}

Page 108: Python programming under_windows

•• An empty dictionary D is defined as follows :An empty dictionary D is defined as follows :

D = { }

Page 109: Python programming under_windows
Page 110: Python programming under_windows

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

Page 111: Python programming under_windows

Other operationsOther operations

Page 112: Python programming under_windows
Page 113: Python programming under_windows

We can check if a key is in the dictionary:We can check if a key is in the dictionary:

Page 114: Python programming under_windows

To get the list of all keys:To get the list of all keys:

Page 115: Python programming under_windows

we can also get the list of all valueswe can also get the list of all values

Page 116: Python programming under_windows
Page 117: Python programming under_windows

Thank You!Thank You!

CHITRAKANT BANCHHORCHITRAKANT BANCHHOR

Thank You!Thank You!


Recommended