1 of 47

PYTHON WORKSHOP

S.Dhanya Abhirami

2 of 47

LET’S

DIVE INTO

PYTHON

3 of 47

4 of 47

1. Presence of Third Party Modules and Extensive Support Libraries :

The Python Package Index (PyPI) contains numerous third-party modules that make Python capable of interacting with most of the other languages and platforms.

Python provides a large standard library which includes areas like internet protocols, string operations, web services tools and operating system interfaces. Many high use programming tasks have already been scripted into the standard library which reduces length of code to be written significantly.

2. Open Source and Community Development:

 Python language is developed under an OSI-approved open source license, which makes it free to use and distribute, including for commercial purposes.

Further, its development is driven by the community which collaborates for its code through hosting conferences and mailing lists, and provides for its numerous modules.

3. Interpreted

Unlike C and C++, python code is translated line by line to machine language.

Easier to debug.

5 of 47

4. Learning Ease and Support Available:

 Python offers excellent readability and uncluttered simple-to-learn syntax which helps beginners to utilize this programming language. Additionally, the wide base of users and active developers has resulted in a rich internet resource bank to encourage development and the continued adoption of the language. You get numerous tutorials and documentations online.Cool!

5. User-friendly Data Structures:

Python has built-in list and dictionary data structures which can be used to construct fast runtime data structures.  Further, Python also provides the option of dynamic high-level data typing which reduces the length of support code that is needed.

6. Productivity and Speed(OOP) :

Python has clean object-oriented design, provides enhanced process control capabilities, and possesses strong integration and text processing capabilities and its own unit testing framework, all of which contribute to the increase in its speed and productivity. Python is considered a viable option for building complex multi-protocol network applications.

6 of 47

7 of 47

8 of 47

9 of 47

HISTORY

  • Guido van Rossum – Creator
  • Released in the early 1990s.
  • Its name comes from a 1970s British comedy

sketch television show called Monty Python’s Flying Circus

10 of 47

PYTHON

print(“Hello World”)

C++

#include<iostream.h>

void main()

{

cout<<“Hello world”;

}

11 of 47

Keywords

  • You can not use reserved words as variable names /identifiers

and del for is raise

assert elif from lambda return

break else global not try

class except if or while

continue exec import pass yield

def finally in print

12 of 47

Identifiers

  • Must start with a letter or underscore _
  • Must consist of letters and numbers and underscores
  • No keywords can be used as identifier
  • Spaces are not allowed
  • Python is Case Sensitive
  • name Name NAME Name all are different
  • Acceptable: address tomato push23 _myname
  • Not acceptable: 12address *abc var.12 hi hello

13 of 47

STRING

  • string is usually a bit of text you want to display to someone
  • Strings are enclosed in ‘ ’ or “ “.

14 of 47

>>>print (“My name is Dhanya”)

My name is Dhanya

>>> print (“Good morning”)

Good morning

>>>”Hey what’s up”

‘Hey what’s up’

>>>’ Python is cool.’

’ Python is cool.’

15 of 47

‘Good morning ma’am’

>>>print (‘Good morning ma’am’)

SyntaxError: invalid syntax

16 of 47

>>>print (“Good morning ma’am”)

Good morning ma’am

>>>print (‘She said “How are you?” ’)

She said “How are you?”

‘ She said “How are you?” ’

17 of 47

ESCAPE CHARACTER

  • If you want to print

a ‘ within ‘…’ or a “ within “…”

  • USE ‘\’.

>>> ‘Hello! It\’s me.’

Hello! It’s me.

18 of 47

Python as a Calculator

>>>1+1

2

>>>10-3

7

>>>2*4

8

>>>12/4

3

>>>5%3 #remainder

2

19 of 47

Variables

  • A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable name
  • The variable name must be a valid identifier
  • You can change the contents of a variable in a later statement

12.2

x

14

y

x = 12.2

y = 14

100

x = 100

20 of 47

Numeric Expressions

Operator

Operation

+

Addition

-

Subtraction

*

Multiplication

/

Division

//

Integer Division

**

Power

%

Remainder

21 of 47

Order of Evaluation

  • When we string operators together - Python must know which one to do first
  • This is called operator precedence
  • Which operator higher priority over the others

x = 1 + 2 * 3 - 4 / 5 ** 6

22 of 47

Operator Precedence Rules

Parenthesis

Power

Multiplication/Division

Addition/Subtraction

Left to Right

23 of 47

Parenthesis

Power

Multiplication

Addition

Left to Right

>>> x = 1 + 2 ** 3 / 4 * 5

>>> print x

11

1 + 2 ** 3 / 4 * 5

1 + 8 / 4 * 5

1 + 2 * 5

1 + 10

11

Note 8/4 goes before 4*5 because of the left-right rule.

24 of 47

Data types

  • In Python , you need not declare variables before using them
  • Python understands whether the variable is an integer , float or string

>>> x = 1 + 4

>>> print (x)

5

>>>x=“Dhanya”

>>>x

Dhanya

>>> y = 'hello ' + 'there'

>>> print (y)

hello there

25 of 47

Type Casting

  • When you perform an operation where one operand is an integer and the other operand is a floating point the result is a floating point
  • The integer is converted to a floating point before the operation

>>>n=10

>>>float(n)

10.0

>>>str(n)

‘10’

26 of 47

Comments

  • Anything after a ‘# ‘ is ignored by Python
  • Why comment?
    • Describe what is going to happen in a sequence of code
    • Make your code easy to read
    • Turn off a line of code - perhaps temporarily

27 of 47

MULTILINE COMMENTS

  • Enclose the comment in triple quotes

“””” this is comment line 1

this is comment line 2

this is comment line 3””””

28 of 47

String Operations

  • Some operators apply to strings
    • + implies concatenation
    • * implies multiple concatenation
  • Python knows when it is dealing with a string or a number and behaves appropriately

>>> print ('abc' + '123’)

abc123

>>> print ('Hi' * 5)

HiHiHiHiHi

>>>

29 of 47

RELATIONAL OPERATORS

  • > Greater Than
  • < Less Than
  • == Equal To
  • >= Greater Than or Equal To
  • <= Less Than or Equal To
  • != Not Equal To

Note: a==10 is different from a=10 (Why?)

30 of 47

Logical Operators

Operator

Description

Example

and

Called Logical AND operator. If both the operands are true then then condition becomes true.

(a and b) is true.

or

Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.

(a or b) is true.

not

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

not(a and b) is false.

31 of 47

MORE ON STRINGS

  • length - len()
  • indexing
  • slicing
  • join()
  • split()
  • in
  • string formatting

32 of 47

Branching

  • If
  • Elif
  • Else
  • Nested if-else

33 of 47

Syntax of if-else

if condition1:

do this

elif condition2:

do something else

else:

do this

Take care of indentation and semicolon

34 of 47

Iteration

To execute a block of code repeatedly we use loops.

In a loop:

condition is checked

If true, loop body is entered

Loop body is executed over and over again until condition becomes false

Once false, we exit the loop

  • For loop
  • While loop
  • Break
  • Range function

35 of 47

while Loop

count = 0

print(“before while loop”)

while (count < 9):

print 'The count is:', count

count = count + 1

print “Out of while loop"

while condition:

do this

36 of 47

>>>range(0,10)

>>>range(10)

>>>range(0,10,2)

For generating a sequence

range( from,to,jump)

37 of 47

for Loop

  • Example

for i in range(0,10):

print (i**2)

for alphabet in ‘Dhanya':

print ('Current Letter :',alphabet)

38 of 47

  • break

Come out of the loop

  • continue

Go to next iteration

  • pass

Don’t do anything, like a placeholder

39 of 47

LIST

  • l=[1,2,3,4]
  • Index starts from 0
  • l[0:2]
  • l[::-1]
  • l2=[5,6,7]
  • l.append(l2)
  • l.extend(l2)
  • del l[2]
  • l1=[1,2,3]+[90,0]
  • l1.sort()
  • l1.sort(reverse=True)
  • l1.pop()

  • l1.index(3)
  • h=[‘hi’]*3
  • len(h)
  • h.count(hi)
  • s=“hello”
  • l=list(s)
  • s=‘x’.join(l)
  • L2=[‘a’,3,’*’,3.5] #any type

DATA STRUCTURES

40 of 47

SET

  • s=set()
  • s={‘a’,’b’,’c’}
  • len(s)
  • s1={1,2,5,7}
  • s2={2,5,8,9}
  • s1.intersection(s2)
  • s1.union(s2)
  • s1.pop()

41 of 47

TUPLE

  • t=(1,2,‘A’,’B’) #any data type
  • len(t)
  • Accessing using index
  • t[3]
  • del(t)
  • Useful for representing co-ordinates in cartesian plane

42 of 47

DICTIONARY

Key-value pairs

No need of integer indices

Note key must be immutable

>>> d={1:"hi",'a':2}

>>> d['a']

>>> d[1]

>>>d.keys()

>>>d.values()

43 of 47

KEEP IN MIND

MUTABLE

ORDERED

SYNTAX

STRING

NO

YES

“a” or ‘a’

LIST

YES

YES

[a,b ]

DICTIONARY

YES

NO

{key:value}

TUPLE

NO

YES

(a,b)

SET

YES

NO

{a,b}

44 of 47

FUNCTIONS

def functionname(parameters):

… body of function

Now its your turn write a function to print sum of first n numbers,

Given n

45 of 47

  • Recursive function
  • Function without argument
  • Function with arguments
  • Function with default parameter

Some variations

46 of 47

Modules

  • When you have a large program, just dividing into functions isn’t enough
  • It is easier to save parts of the code in different files
  • Save as a .py file
  • Importing techniques:

import module

from module import *

47 of 47