intro to python programming language

Post on 11-Apr-2017

98 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1Copyright © 2012 Tata Consultancy Services Limited

Presentation on

Python Programming

2

Introduction

Python Basics

Python Decision Making

Python Loops

Python Sequence Types

Python Functions

Python File I/O

Outline

3

Introduction

Python is a clear and powerful object-oriented programming language.

Uses an elegant syntax, making the programs you write easier to read.

Comes with a large standard library that supports many common programming tasks.

Python's interactive mode makes it easy to test short snippets of code.

Runs on many different computers and operating systems: Windows, MacOS, many brands of Unix, OS/2.

Is free software in two senses. It doesn't cost anything to download or use Python, or to include it in your application. Python can also be freely modified and re-distributed.

4

Python: The Basics

5

A Code Sample

x = 34 – 23 # A commenty = “Hello” # Another one.z = 3.45if z == 3.45 or y == “Hello”: x = x + 1 y = y + “ World” # String concat.print xprint y

6

Enough to Understand the Code

Assignment uses = and comparison uses ==.

For numbers + - * / % are as expected.

Special use of + for string concatenation.

Special use of % for string formatting (as with printf in C)

Logical operators are words (and, or, not) not symbols

The basic printing command is “print”

The first assignment to a variable creates it.

Variables types don’t need to be declared.

Python figures out the variables types on its own.

7

Whitespace

Whitespace is meaningful in Python: especially indentation and placement of newlines.

Use a newline to end a line of code.

Use ‘\’ when must go to next line prematurely

No braces { } to mark blocks of code in Python…

Use consistent indentation instead.

The first line with less indentation is outside of the block

The first line with more indentation starts a nested block.

Often a colon appears at the start of a new block. (Eg. For function and class definitions.)

8

Comments

Start comments with # - the rest of line is ignored.

Can include a “documentation string” as the first line of any new function or class that you define.

The development environment, debugger, and other tools use it: it’s good style to include one.

def my_function(x, y): “””This is the docstring. This function does …..””” # The code would go here…

9

Assignment Statements

Binding a variable in Python means setting a name to hold a reference to some object.

Assignment creates references, not copies.

Names in Python do not have an intrinsic type. Objects have types.

A reference is deleted via garbage collection after any names bound to it have passed out of scope.

10

Multiple Assignment

One can also assign to multiple names at the same time.

>>> x, y = 2, 3>>> x2>>> y3

11

Naming Rules

Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores.

Bob bob _bob _2_bob_ bob_2 BoB

There are some reserved words. Those words cannot be used to label identifiers in a Python program.

12

Variables in Python A variable stores a piece of data, and gives it a specific name.

Python is a dynamically typed language.

Variables need not be declared in Python before using them.

Variables can be used on the fly and Python infers its type based on the value stored by the variable.

Example: Set the variable “age” equal to the value 20.

>>> age = 20 Now “age” can be used in any arithmetic operations, such as,

>>> age_after_10 = age + 10 # 30

13

Basic Data Types Python supports the usual data types, such as,

Integers

Floats

Strings

If both operands are of type int, floor division is performed and an int is returned.

If either operand is a float, classic division is performed and a float is returned.

In addition to int and float, Python supports other types of numbers, such as Decimal, Fraction and Complex numbers.

14

Fun with Python Arithmetic

>>> 17 / 3 # int / int -> int5>>> 17 / 3.0 # int / float -> float5.666666666666667>>> 17 % 3 # the % operator returns the remainder2>>> 5 ** 2 # 5 squared25

15

Python Strings Besides numbers, Python can also manipulate strings, which can be expressed

in several ways.

Strings can be enclosed in single quotes ('...') or double quotes ("…").

The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes.

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''.

Strings can be concatenated (glued together) with the + operator, and repeated with *.

>>> 3 * ‘un’ + ‘ium’ ‘unununium’

16

String Examples

>>> 'doesn\'t' # use \' to escape the single quote..."doesn't">>> "doesn't" # ...or use double quotes instead"doesn't">>> '"Isn\'t," she said.''"Isn\'t," she said.'>>> print '"Isn\'t," she said.'"Isn't," she said.

17

Strings Continued…

Strings can be indexed (subscripted), with the first character having index 0.

There is no separate character type; a character is simply a string of size one.

Indices may also be negative numbers, while counting from the right.

Say, word = ‘Python’

>>> word[-1] # last character ‘n’>>> word[-2] # second last character ‘o’

18

Strings Continued…

In addition to indexing, slicing is also supported. While indexing is used to

obtain individual characters, slicing allows you to obtain a substring.

In slicing, the start is always included, and the end always excluded. This

makes sure that s[:i] + s[i:] is always equal to s.

19

Python Decision Making:

if, if…else, if…elif…else

20

Python Decision Structures

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

If the suite of an if clause consists of a single line, it may go on the same line as the header statement.

21

If in Action…

#!/usr/bin/pythonvar = 100if var == 100: print “Value of expression is 100”print “Good Bye!”

22

Loops In Python:

while, for…in, nested loops

23

Loop Statements Programming languages provide various control structures that allow for more

complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.

Python provides the following looping constructs:

While loop

For loop

Loop Control Statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Eg:. Break, continue, pass.

24

While Loop A while loop statement in Python, repeatedly executes a target statement as

long as a given condition is true.

Syntax:

while expression: statement(s)Eg: #!/usr/bin/python count = 0 while count < 9: print “The count is:”, count count = count + 1

25

For loop It has the ability to iterate over the items of any sequence, such as list or a

string.

Syntax:

for iterating_var in sequence: statement(s) If a sequence contains an expression list, it is evaluated first. Then, the first

item in the sequence is assigned to the iterating varaiable iterating_var.

Each item in the sequence is iterated over, until the entire sequence is exhausted.

26

For loop in action…● Eg:.

#!usr/bin/pythonfor letter in ‘Python’: # First Example print ‘Current letter:’, letterFruits = [‘banana’, ‘apple’, ‘mango’]for fruit in fruits: # Second Example print “Current Fruit:”, fruit

27

Iterating by sequence index An alternative way of iterating through each item is by index offset into the

sequence itself.

Eg:.

fruits = [“banana”, “apple”, “mango”] for index in range(len(fruits)): print “Current fruit:”, fruits[index] In the above example, we took assistance of the len() built-in function, which

provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.

28

Using else statements with Loops

Python supports to have an else statement associated with a loop

If the else statement is used with a for loop, the else statement is executed when the loop has exhausted the sequence.

If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

29

Else with loops Example● The following example illustrates the combination of an else statement with

statement that searches for prime numbers from 10 through 20.

for num in range(10, 20): # to iterate between 10 to 20 for i in range(2, num): # to iterate on the factors of the number if num % i == 0: # To determine the first factor j = num / i # To calculate the second factor print ‘%d equals %d * %d’ % (num, i, j) break else: print num, ‘is a prime number’

30

Sequence Types:

Tuples, Lists, and Strings

31

Sequence Types Tuple

A simple immutable ordered sequence of items

Items can be of mixed types, including collection types

Strings Immutable

Conceptually very much like a tuple

List Mutable ordered sequence of items of mixed types.

32

Similar Syntax

All three sequence types (tuples, strings, and lists) share much of the same syntax and functionality.

Key Difference:

Tuples and strings are immutable

Lists are mutable

The operations shown in this section can be applied to all sequence types

Most examples will just show the operation performed on one.

33

Sequence Types 1

Tuples are defined using parentheses (and commas).

>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) Lists are defined using square brackets (and commas).

>>> li = [“abc”, 34, 4.34, 23] Strings are defined using quotes (“, ‘, or “””).

>>> st = “Hello World” >>> st = ‘Hello World’ >>>st = “””This is a multi-line string thatuses triple quotes.”””

34

Sequence Types 2

We can access individual members of a tuple, list, or string using square bracket “array” notation.

Note that all are 0 based…

>>> tu[1] # Second item in the tuple. ‘abc’ >>> li[1] # Second item in the list. 34 >>> st[1] # Second character in string. ‘e’

35

Positive and Negative Indices

>>> t = (23, ‘abc’, 4.56, 2,3), ‘def’) Positive index: count from left, starting with 0.

>>> t[1]‘abc’ Negative lookup: count from right, starting with -1.

>>> t[-3]4.56

36

Slicing: Return Copy of a Subset 1

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Return a copy of the container with a subset of the original members. Start

copying at the first index, and stop copying before the second index.

>>> t[1:4](‘abc’, 4.56, (2,3)) You can also use negative indices when slicing.

>>> t[1:-1](‘abc’, 4.56, (2,3))

37

Slicing: Return Copy of a Subset 2

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Omit the first index to make a copy starting from the beginning of the

container.

>>> t[:2](23, ‘abc’) Omit the second index to make a copy starting at the first index and going to

the end of the container.

>>> t[2:](4.56, (2,3), ‘def’)

38

Copying the Whole Sequence

To make a copy of an entire sequence, you can use [:].

>>> t[:](23, ‘abc’, 4.56, (2,3), ‘def’) Note the difference between these two lines for mutable sequences:

>>> list2 = list1 # 2 names refer to 1 ref # Changing one affects both>>> list2 = list1[:] # Two independent copies, two refs

39

The ‘in’ Operator

Boolean test whether a value is inside a container:

>>> t = [1, 2, 3, 4, 5]>>> 3 in tFalse>>> 4 in tTrue>>> 4 not in tFalse

40

‘in’ Operator Continued…

For strings, tests for substrings

>>> a = ‘abcde’>>> ‘c’ in aTrue>>> ‘cd’ in aTrue>>> ‘ac’ in aFalse Be careful: the in keyword is also used in the syntax of for loops and list

comprehensions.

41

The + Operator

The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments.

>>> (1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)>>> [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]>>> “Hello” + “ “ + “World”‘Hello World’

42

The * Operator

The * operator produces a new tuple, list, or string that “repeats” the original content.

>>> (1, 2, 3) * 3(1, 2, 3, 1, 2, 3, 1, 2, 3)>>> [1, 2, 3] * 3[1, 2, 3, 1, 2, 3, 1, 2, 3]>>> “Hello” * 3‘HelloHelloHello’

43

Mutability:

Tuples vs. Lists

44

Tuples: Immutable

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def)>>> t[2] = 3.14You can’t change a tuple.

You can make a fresh tuple and assign its reference to a previously used name.

>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)

45

Lists: Mutable

>>> li = [‘abc’, 23, 4.34, 23]>>> li[1] = 45>>> li[‘abc’, 45, 4.34, 23]We can change lists in place.

Name li still points to the same memory reference when we’re done.

The mutability of lists means that they aren’t as fast as tuples.

46

Operations on lists Only 1

>>> li = [1, 11, 3, 4, 5]>>> li.append(‘a’) # Our first exposure to method syntax>>> li[1, 11, 3, 4, 5, ‘a’]>>> li.insert(2, ‘i’)>>> li[1, 11, ‘i’, 3, 4, 5, ‘a’]

47

The extend method vs the + operator

‘+’ creates a fresh list (with a new memory reference)

Extend operates on list li in place.

>>> li.extend([9, 8, 7])>>> li[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7] Confusing:

• Extend takes a list as an argument.

• Append takes a singleton as an argument.

>>> li.append([10, 11, 12])

48

Operations on Lists Only 3

>>> li = [‘a’, ‘b’, ‘c’, ‘b’]>>> li.index(‘b’) # index of first occurrence1>>> li.count(‘b’) # number of occurences2>>> li.remove(‘b’) # remove first occurrence>>> li[‘a’, ‘c’, ‘b’]

49

Operations on Lists Only 4

>>> li = [5, 2, 6, 8]>>> li.reverse() # reverse the list *in place*>>> li[8, 6, 2, 5]>>> li.sort() # sort the list *in place*>>> li[2, 5, 6, 8]>>> li.sort(some_function)# sort in place using user-defined comparison

50

Tuples vs. Lists

Lists slower but more powerful than tuples.

Lists can be modified, and they have lots of handy operations we can perform on them.

Tuples are immutable and have fewer features.

To convert between tuples and lists use the list() and tuple() functions:

>>> li = list(tu)>>> tu = tuple(li)

51

Python Dictionary Each key is separated from its value by a colon ( : ), the items are separated by

commas, and the whole thing is enclosed in curly braces.

An empty dictionary without any items is written with just two curly braces, like this { }.

Keys are unique within a dictionary while values my not be.

The values can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

52

Accessing Values in a Dictionary To access dictionary elements, we can use the familiar square brackets along

with the key to obtain its value.

Eg:. dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’} print dict[‘Name’] print dict[‘Age’] If we attempt to access a data item with a key, which is not part of the

dictionary, we will get an error.

53

Updating Dictionary We can update a dictionary by adding a new entry or key-value pair,

modifying an existing entry, or deleting an existing entry.

Eg:.

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’} dict[‘Age’] = 8 # Update existing entry dict[‘School’] = “DPS School” # Add new entry

54

Delete Dictionary Elements We can either remove individual dictionary elements or clear the entire

contents of a dictionary.

We can also delete the entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement.

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}del dict[‘Name’] # Delete an elementdict.clear() # Clear the contents of the dictionarydel dict # Remove the entire dictionary structure.

55

Python Functions:

code organization and reusability

56

Function as a Concept

A function is a block of organized, reusable code that is used to perform a single, related action.

Functions provide better modularity for an application and a high degree of code reusing.

Python gives us may built-in functions like print(), etc.

We can also create our own functions. These are called user-defined functions.

57

Defining a Function

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. We can also define parameters inside these parentheses.

The first statement of a function can be an optional statement – the documentation string of the function or docstring.

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.

58

Function Structure

def function_name ( parameters ): “function_docstring” function_suite return [expression]Eg:.

def printme (str): “This prints a passed string into this function” print str return

59

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

Keyword arguments are related to the function calls. When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

Default arguments are arguments that assume a default value if a value is not provided in the function call for that argument.

When we may need to process a function for more arguments than we specified while defining the function, we use variable-length arguments. They are also known as splat-arguments

60

Python files I/O:

input and output with persistence

61

Python File Manipulation Python provides basic functions and methods necessary to manipulate files by

default.

Most of the file manipulation is done using a file object.

The various file handling methods supported are:

open()close()write()read()tell()

62

The open() Function Before we can read or write to a file, we have to open it.

This function creates a file object, which would be utilized to call other support methods associated with it.

Syntax:

file_object = open(file_name [, access_mode][, buffering]) The commonly used access modes are ‘r’, ‘rb’, ‘r+’, ‘rb+’, ‘w’, ‘wb’, ‘w+’,

‘wb+’ and ‘a’.

Eg:.

fo = open(“foo.txt”, “wb”)

63

The close() Method The close() method of a file object flushes any unwritten information and

closes the file object, after which no more I/O can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file.

Syntax:

file_object.close()

64

The write() Method The write() method writes any string to an open file. It is important to note that

Python strings can have binary data and not just text.

The write() method does not add a newline character(‘\n’) to the end of the string.

Syntax:

File_object.write(string)

65

The read() Method The read() method reads a string from an open file.

Syntax:

file_object.read ( [count] ) Here, the passed parameter is the number of bytes to be read from the opened

file.

This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

66

An Example…

fo = open(“foo.txt”, “r+”) # Open a filestr = fo.read(10)print “Read string is: “, strposition = fo.tell() # Check current positionprint “Current file position: “, positionposition = fo.seek(0,0) # Reposition pointer to the beginningstr = fo.read(10)print “Again read string is: “, strfo.close()

67

Renaming and Deleting Files Python os module provides methods that helps us perform file-processing

operations, such as renaming and deleting files.

To use this module, we need to import it first and then only we can call any related functions.

Rename Method – os.rename (curr_file_name, new_file_name) Remove Method – os.remove (file_name) In order to import a module, we just type: import module_name

68

Directory Manipulation in Python The os module has several methods that help us create, remove and change

directories.

Some of the commonly used methods are:

mkdir() - os.mkdir(“dir_name”) chdir() - os.chdir(“new_dir) getcwd() – os.getcwd() rmdir() – os.rmdir(‘dir_name’)

69Copyright © 2012 Tata Consultancy Services Limited

Thank You

top related