Slide 1

Slide 1 text

Introduction to Python Sushant Mane President @Walchand Linux User's Group sushantmane.github.io

Slide 2

Slide 2 text

What is Python? ● Python is a programming language that lets you work quickly and integrate systems more effectively. ● Interpreted ● Object Oriented ● Dynamic language ● Multi-purpose

Slide 3

Slide 3 text

Let's be Comfortable ● Let’s try some simple math to get started! >>>print 1 + 2 >>>print 10 * 2 >>>print 5 - 3 >>>print 4 * 4

Slide 4

Slide 4 text

help() for help ● To get help on any Python object type help(object) eg. To get help for abs function >>>help(abs) ● dir(object) is like help() but just gives a quick list of the defined symbols >>>dir(sys)

Slide 5

Slide 5 text

Basic Data type's ● Numbers – int – float – complex ● Boolean ● Sequence – Strings – Lists – Tuples

Slide 6

Slide 6 text

Why built-in Types? ● Make programs easy to write. ● Components of extensions. ● Often more efficient than custom data structures. ● A standard part of the language

Slide 7

Slide 7 text

Core Data Types Row 1 Row 2 Row 3 Row 4 0 2 4 6 8 10 12 Column 1 Column 2 Column 3 Object type literals/creation Numbers 1234, 3.1415, 3+4j, Decimal, Fraction Strings 'spam', “india's", b'a\x01c' Lists [1, [2, 'three'], 4] Dictionaries {'food': 'spam', 'taste': 'yum'} Tuples (1, 'spam', 4, 'U') Files myfile = open(‘python', 'r') Sets set('abc'), {'a', 'b', 'c'} Other core types Booleans, type, None Program unit types Functions, modules, classes

Slide 8

Slide 8 text

Variables ● No need to declare ● Need to initialize ● Almost everything can be assigned to a variable

Slide 9

Slide 9 text

Numeric Data Types

Slide 10

Slide 10 text

int >>>a = 3 >>>a ● a is a variable of the int type

Slide 11

Slide 11 text

long >>>b = 123455L >>>b = 12345l ● b is a long int ● For long -- apeend l or L to number

Slide 12

Slide 12 text

float >>>p = 3.145897 >>>p ● real numbers are represented using the float ● Notice the loss of precision ● Floats have a fixed precision

Slide 13

Slide 13 text

complex >>c = 3 + 4j ● real part : 3 ● imaginary part : 4 >>c.real >>c.imag >>abs(c) ● It’s a combination of two floats ● abs gives the absolute value

Slide 14

Slide 14 text

Numeric Operators ● Addition : 10 + 12 ● Substraction : 10 - 12 ● Division : 10 / 17 ● Multiplication : 2 * 8 ● Modulus : 13 % 4 ● Exponentiation : 12 ** 2

Slide 15

Slide 15 text

Numeric Operators ● Integer Division (floor division) >>>10 / 17 0 ● Float Division >>>10.0 / 17 0.588235 >>>flot(10) / 17 0.588235 ● The first division is an integer division ● To avoid integer division, at least one number should be float

Slide 16

Slide 16 text

Variables And Assignment

Slide 17

Slide 17 text

Variables ● All the operations could be done on variables >>>a = 5 >>>b = 3.4 >>>print a, b

Slide 18

Slide 18 text

Assignments ● Assignment >>>c = a + b ● c = c / 3 is equivalent to c /= 3 ● Parallel Assignment >>>a, b = 10, 12 >>>c, d, red, blue = 123, 121, 111, 444

Slide 19

Slide 19 text

Booleans and Operations ● All the operations could be done on variables >>>t = True >>>t >>>f = not True >>>f >>>f or t ● can use parenthesis. >>>f and (not t)

Slide 20

Slide 20 text

Container Data Types i.e. Sequences

Slide 21

Slide 21 text

Sequences ● Hold a bunch of elements in a sequence ● Elements are accessed based on position in the sequence ● The sequence data-types – list – tuple – dict – str

Slide 22

Slide 22 text

list ● Items are enclosed in [ ] and separated by “ , ” constitute a list >>>list = [1, 2, 3, 4, 5, 6] ● Items need not to have the same type ● Like indexable arrays ● Extended at right end ● List are mutable (i.e. will change or can be changed) ● Example >>>myList = [631, “python”, [331, ”computer” ]]

Slide 23

Slide 23 text

List Methods ● append() : myList.append(122) ● insert() : myList.insert(2,”group”) ● pop() : myList.pop([i] ) ● reverse() : myList.reverse() ● sort() : myList.sort([ reverse=False] ) – where [] indicates optional

Slide 24

Slide 24 text

Tuples ● Items are enclosed in ( ) and separated by ”, ” constitute a list >>>tup = (1, 2, 3, 4, 5, 6) ● Nesting is Possible ● Outer Parentheses are optional ● tuples are immutable (i.e. will never change cannot be changed) ● Example >>>myTuple = (631, “python”, [ 331 , ”computer” ])

Slide 25

Slide 25 text

Tuple Methods Concatenation : myTuple + (13, ”science”) Repeat : myTuple * 4 Index : myTuple[i] Length : len( myTuple ) Membership : ‘m’ in myTuple

Slide 26

Slide 26 text

Strings

Slide 27

Slide 27 text

Strings . . . ● Contiguous set of characters in between quotation marks eg. ”wceLinuxUsers123Group” ● Can use single or double quotes >>>st = 'wceWlug' >>>st = ”wceWlug”

Slide 28

Slide 28 text

Strings . . . ● three quotes for a multi-line string. >>> ''' Walchand . . . Linux . . . Users . . . Group''' >>> ”””Walchand . . . Linux . . . Users . . . Group”””

Slide 29

Slide 29 text

Strings Operators ● “linux"+"Users" 'linuxUsers' # concatenation ● "linux"*2 'linuxlinux' # repetition ● "linux"[0] 'l' # indexing ● "linux"[-1] 'x' # (from end) ● "linux"[1:4] 'iu' # slicing ● len("linux") 5 # size ● "linux" < "Users" 1 # comparison ● "l" in "linux" True # search

Slide 30

Slide 30 text

Strings Formating ● % ● Can usually just use %s for everything, it will convert the object to its String representation. ● eg. >>> "One, %d, three" % 2 'One, 2, three' >>> "%d, two, %s" % (1,3) '1, two, 3' >>> "%s two %s" % (1, 'three') '1 two three'

Slide 31

Slide 31 text

Strings and Numbers >>>ord(text) ● converts a string into a number. ● Example: ord("a") is 97, ord("b") is 98, ...

Slide 32

Slide 32 text

Strings and Numbers >>>chr(number) ● Example: chr(97) is 'a', chr(98) is 'b', ...

Slide 33

Slide 33 text

Python : No Braces ● Uses indentation instead of braces to determine the scope of expressions ● Indentation : space at the beginning of a line of writing eg. writing answer point-wise

Slide 34

Slide 34 text

Python : No Braces ● All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) ● forces the programmer to use proper indentation ● indenting is part of the program!

Slide 35

Slide 35 text

Python : No Braces ● All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) ● forces the programmer to use proper indentation ● indenting is part of the program!

Slide 36

Slide 36 text

Control Flow

Slide 37

Slide 37 text

Control Flow ● If statement : powerful decision making statement ● Decision Making And Branching ● Used to control the flow of execution of program ● Basically two-way decision statement

Slide 38

Slide 38 text

If Statement >>> x = 12 >>> if x <= 15 : y = x + 15 >>> print y ● if condition : statements Indentation

Slide 39

Slide 39 text

If-else Statement ● if condition : Statements else : Statements >>> x = 12 >>> if x <= 15 : y = x + 13 Z = y + y else : y = x >>> print y

Slide 40

Slide 40 text

If-elif Statement ● if condition : Statements elif condition : Statements else : Statements >>> x = 30 >>> if x <= 15 : y = x + 13 elif x > 15 : y = x - 10 else : y = x >>> print y

Slide 41

Slide 41 text

Looping

Slide 42

Slide 42 text

Looping ● Decision making and looping ● Process of repeatedly executing a block of statements

Slide 43

Slide 43 text

while loop ● while condition : Statements >>> x = 0 >>> while x <= 10 : x = x + 1 print x >>> print “x=”,x

Slide 44

Slide 44 text

Loop control statement break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop

Slide 45

Slide 45 text

while – else clause ● while condition : Statements else : Statements >>> x = 0 >>> while x <= 6 : x = x + 1 print x else : y = x >>> print y The optional else clause runs only if the loop exits normally (not by break)

Slide 46

Slide 46 text

For loop >>>for n in [1,5,7,6]: print n >>>for x in range(4): print x iterating through a list of values

Slide 47

Slide 47 text

range() ● range(N) generates a list of numbers [0,1, ...,N-1] ● range(i , j, k) ● I --- start (inclusive) ● j --- stop (exclusive) ● k --- step

Slide 48

Slide 48 text

For – else clause ● for var in Group : Statements else : Statements >>>for x in range(9): print x else : y = x >>> print y For loops also may have the optional else clause

Slide 49

Slide 49 text

User : Input >>> var = input(“Enter your name :”) >>> var = raw_input(“Enter your name & BDay”) ● The raw_input(string) method returns a line of user input as a string ● The parameter is used as a prompt

Slide 50

Slide 50 text

Functions

Slide 51

Slide 51 text

functions ● Code to perform a specific task. ● Advantages: ● Reducing duplication of code ● Decomposing complex problems into simpler pieces ● Improving clarity of the code ● Reuse of code ● Information hiding

Slide 52

Slide 52 text

functions ● Basic types of functions: ● Built-in functions Examples are: dir() len() abs() ● User defined Functions created with the ‘ def ’ keyword.

Slide 53

Slide 53 text

Defining functions >>> def f(x): … return x*x >>> f(1) >>> f(2) ● def is a keyword ● f is the name of the function ● x the parameter of the function ● return is a keyword; specifies what should be returned

Slide 54

Slide 54 text

Calling a functions >>>def printme( str ): >>> #"This prints a passed string into this function" >>> print str; >>> return; … To call function, printme >>>printme(“HELLO”); Output HELLO

Slide 55

Slide 55 text

Modules

Slide 56

Slide 56 text

modules ● A module is a python file that (generally) has only ● definitions of variables, ● functions and ● classes

Slide 57

Slide 57 text

Importing modules Modules in Python are used by importing them. For example, 1] import math This imports the math standard module. >>>print math.sqrt(10)

Slide 58

Slide 58 text

Importing modules.... 2] >>>from string import whitespace only whitespace is added to the current scope >>>from math import * all the elements in the math namespace are added

Slide 59

Slide 59 text

creating module Python code for a module named ‘xyz’ resides in a file named file_name.py. Ex. support.py >>> def print_func( par ): print "Hello : ", par return The import Statement: import module1[, module2[,... moduleN] Ex: >>>import support >>>support.print_func(“world!”);

Slide 60

Slide 60 text

Doc-Strings ● It’s highly recommended that all functions have documentation ● We write a doc-string along with the function definition >>> def avg(a, b): … """ avg takes two numbers as input and returns their average""" … return (a + b)/2 >>>help(avg)

Slide 61

Slide 61 text

Returning multiple values Return area and perimeter of circle, given radius Function needs to return two values >>>def circle(r): … pi = 3.14 … area = pi * r * r … perimeter = 2 * pi * r … return area, perimeter >>>a, p = circle(6) >>>print a

Slide 62

Slide 62 text

File Handling

Slide 63

Slide 63 text

Basics of File Handling ● Opening a file: Use file name and second parameter-"r" is for reading, the "w" for writing and the "a" for appending. eg. >>>fh = open("filename_here", "r") ● Closing a file used when the program doesn't need it more. >>>fh.close()

Slide 64

Slide 64 text

functions File Handling Functions available for reading the files: read, readline and readlines. ● The read function reads all characters. >>>fh = open("filename", "r") >>>content = fh.read()

Slide 65

Slide 65 text

functions File Handling ● The readline function reads a single line from the file >>>fh = open("filename", "r") >>>content = fh.readline() ● The readlines function returns a list containing all the lines of data in the file >>>fh = open("filename", "r") >>>content = fh.readlines()

Slide 66

Slide 66 text

Write and write lines To write a fixed sequence of characters to a file: >>>fh = open("hello.txt","w") >>>fh.write("Hello World")

Slide 67

Slide 67 text

Write and writelines You can write a list of strings to a file >>>fh = open("hello.txt", "w") >>>lines_of_text = ["a line of text", "another line of text", "a third line"] >>>fh.writelines(lines_of_text)

Slide 68

Slide 68 text

Renaming Files Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files. rename() Method >>>import os >>>os.rename( "test1.txt", "test2.txt" )

Slide 69

Slide 69 text

Deleting Files remove() Method >>>os.remove(file_name)

Slide 70

Slide 70 text

OOP Class

Slide 71

Slide 71 text

Class A set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods Code: class Employee: 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

Slide 72

Slide 72 text

Class ● empCount is a class variable shared among all instances of this class. This can be accessed as Employee.empCount from inside the class or outside the class. ● first method __init__() is called class constructor or initialization method that Python calls when a new instance of this class is created. ● You declare other class methods like normal functions with the exception that the first argument to each method is self.

Slide 73

Slide 73 text

Class Creating instances emp1 = Employee("Zara", 2000) Accessing attributes emp1.displayEmployee()

Slide 74

Slide 74 text

Queries ?

Slide 75

Slide 75 text

thank you !