ilucbe python v1.2

84
Programming is Fun An introduction to Python Indian Linux Users Group Coimbatore http://ilugcbe.org.in [email protected] ILUG-CBE Programming is Fun

Upload: jaganadh-gopinadhan

Post on 19-May-2015

634 views

Category:

Technology


0 download

DESCRIPTION

Materials for Hands on Python tutorials

TRANSCRIPT

Page 1: Ilucbe python v1.2

Programming is FunAn introduction to Python

Indian Linux Users Group Coimbatorehttp://ilugcbe.org.in

[email protected]

ILUG-CBE Programming is Fun

Page 2: Ilucbe python v1.2

Our Inspiration

Kenneth Gonsalves (1953-2012)

ILUG-CBE Programming is Fun

Page 3: Ilucbe python v1.2

About

ILUG-CBE Programming is Fun

Page 4: Ilucbe python v1.2

Purpose

Learn art of computer programming with one of the easiestprogramming language in the world.

Get ready to enjoy the joy of programming in Python.

ILUG-CBE Programming is Fun

Page 5: Ilucbe python v1.2

Warning

This is a hands on training program.

No theory included in the slides; it may discussed wheneverand wherever it is required.

Be patient,listen, practice and ask questions

Do not hesitate to experiment

Our volunteers are here to help you in practising

Be courageous enough to try

We are leaning Python not rocket science

Be simple and think in a simplistic way

Are You Ready !

ILUG-CBE Programming is Fun

Page 6: Ilucbe python v1.2

Why Python

Why

Used almost everywhere

Fun

Concise

Simple

Powerful

Filled with spices to write effective programs

ILUG-CBE Programming is Fun

Page 7: Ilucbe python v1.2

Installation

Already installed in GNU/Linux systemsIf you are using M$ Windows download Python from python.orgIf you are downloading Python for Windows remember todownload Python 2.7 only.

ILUG-CBE Programming is Fun

Page 8: Ilucbe python v1.2

Interactive Interpreter

ILUG-CBE Programming is Fun

Page 9: Ilucbe python v1.2

Interpreter

Contains REPL

Read

Evaluate

Print

Loop

ILUG-CBE Programming is Fun

Page 10: Ilucbe python v1.2

Interpreter

ILUG-CBE Programming is Fun

Page 11: Ilucbe python v1.2

Hello World!!

Why Hello World

Writing ’Hello World’ program is the ritual to please theprogramming gods to be a good programmer!!

>>> print "Hello World"Hello world

ILUG-CBE Programming is Fun

Page 12: Ilucbe python v1.2

Let’s Jump to Programming

ILUG-CBE Programming is Fun

Page 13: Ilucbe python v1.2

Programming Practice - 1

Create a file hello.pytype print ”Hello World”Listen to the screen for instructions.In-case of any issues just raise your hand our volunteers will bethere to help you.

ILUG-CBE Programming is Fun

Page 14: Ilucbe python v1.2

Programming Practice - 1

Run the program

$python hello.py

ILUG-CBE Programming is Fun

Page 15: Ilucbe python v1.2

Time to make your hands dirty

Note

Make sure that you have understood the first step.In-case of trouble we can practice it for couple of minutes.

ILUG-CBE Programming is Fun

Page 16: Ilucbe python v1.2

Variables

age = 33 # Integeravg = 33.35 # Floatname = "linux" # Stringbool = True # Booleananother = "44" # String

ILUG-CBE Programming is Fun

Page 17: Ilucbe python v1.2

Variables - naming

use lowercase

use underscore between words my age

do not start with numbers

do not use built-ins

do not use keywords

ILUG-CBE Programming is Fun

Page 18: Ilucbe python v1.2

Reserved

and del for is raise assert elif from lambda return break else globalnot try class except if or while continue exec import pass yield deffinally in print

ILUG-CBE Programming is Fun

Page 19: Ilucbe python v1.2

Time to make your hands dirty

ILUG-CBE Programming is Fun

Page 20: Ilucbe python v1.2

Everything is an object

Everything in python is an object

An object has

identity (id)

type (type)

value (mutable or immutable)

>>> age = 33>>> type(age)<type ’int’>>>> id(age)167263248>>> age 34>>> id(age)167263236

ILUG-CBE Programming is Fun

Page 21: Ilucbe python v1.2

Casting

>>> age = 33>>> str(age)’33’>>> float(age)33.0>>> long(age)33L>>> int(age)33

ILUG-CBE Programming is Fun

Page 22: Ilucbe python v1.2

Time for some maths

+ , - , * , ** (power),% (modulo), // (floor division), < (less than)> greater than, <=, >=, ==

ILUG-CBE Programming is Fun

Page 23: Ilucbe python v1.2

It is maths time now

ILUG-CBE Programming is Fun

Page 24: Ilucbe python v1.2

String

>>> name = ’linux’>>> address = "Coimbatore 1st street">>> description = """ We are teaching python toyoung chaps""">>> with_new = "this sentence have one \n new line"

ILUG-CBE Programming is Fun

Page 25: Ilucbe python v1.2

String

>>> name = "linux">>> nameu = name.upper()>>> namel = nameu.lower()>>> namel.find(’l’)>>> ",".join(name)>>> name.startswith(’l’)>>> name.endswith(’x’)>>> namet = name.title()>>> wspace = " with space ">>> stripped = wspace.strip()

ILUG-CBE Programming is Fun

Page 26: Ilucbe python v1.2

Playing with String

ILUG-CBE Programming is Fun

Page 27: Ilucbe python v1.2

Comments

Single line comments starts with #

Multi-line comments should be with in ””” ”””

>>> avg = 45.34 #float>>> name = "ilug-cbe" """ This is amultiline comment """

ILUG-CBE Programming is Fun

Page 28: Ilucbe python v1.2

Boolean

>>> t = True>>> f = Flase

>>> n = None

ILUG-CBE Programming is Fun

Page 29: Ilucbe python v1.2

Conditionals

equality,greater,less,is, is not ...

==, ! =, >, >=, <, <=, is, is not

ILUG-CBE Programming is Fun

Page 30: Ilucbe python v1.2

Conditionals

>>> 1 == 1>>> 1 >= 0>>> 0 <= 1>>> 0 != 1>>> "Rajani" is "rajani">>> "Vijay" is not "Rajani">>> name = None>>> if name is not None:... #do something

ILUG-CBE Programming is Fun

Page 31: Ilucbe python v1.2

Boolean operators

Used to combine conditional logic

and

or

not

ILUG-CBE Programming is Fun

Page 32: Ilucbe python v1.2

if ...

if mark > 60 and mark < 100:print "First Class"

elif mark < 60:print "Second Class Only :-("

else:print "Ooops !!!!"

ILUG-CBE Programming is Fun

Page 33: Ilucbe python v1.2

if ... elif time

ILUG-CBE Programming is Fun

Page 34: Ilucbe python v1.2

Sequences

list

List is an ordered collection of objects.

names = ["rms","linus","guido","larry"]marks = [45,50,60,80,90]mixed = ["linux",12,12.35,90L]

ILUG-CBE Programming is Fun

Page 35: Ilucbe python v1.2

Sequences - list

names = []print namesnames.append("linus")print namesnumbers = [6,9,2,3,1,8,4]print len(numbers)print numbers.sort()print numbers.reverse()another = [9,3,6]numbers.extend(another)print numbersnumbers.insert(0,20)print numbers

ILUG-CBE Programming is Fun

Page 36: Ilucbe python v1.2

Sequences - list

print numbers[0]print numbers[-1]print numbers[2:-2]print numbers[:-2]print numbers[2:]print numbers[:]

ILUG-CBE Programming is Fun

Page 37: Ilucbe python v1.2

Sequences -tuple

tuple

Tuple is like list only. But tuple is immutable

nums = (1,2,3,4)print numsprint len(nums)print nums[0]print nums[-1]

ILUG-CBE Programming is Fun

Page 38: Ilucbe python v1.2

Sequences range

nums = range(20)print numsselected = range(20,60)print selectedjump2 = range(10,100,2)print jump2

ILUG-CBE Programming is Fun

Page 39: Ilucbe python v1.2

Let’s do some sequencing

ILUG-CBE Programming is Fun

Page 40: Ilucbe python v1.2

Iteration

names = ["linus","rms","guido","larry"]for name in names:print "hello %s" %(name)

for num in range(10,20,2):print num

ILUG-CBE Programming is Fun

Page 41: Ilucbe python v1.2

Iteration

for i in range(len(names)):print i,names[i]

for i,v in enumerate(names):print i,v

ILUG-CBE Programming is Fun

Page 42: Ilucbe python v1.2

Iteration break,continue and pass

for name in names:print nameif name == "guido":

break

for name in names:print nameif name == "linus":

continue

for name in names:print nameif name == "rms":

pass

ILUG-CBE Programming is Fun

Page 43: Ilucbe python v1.2

Iteration - while

my_number = 10

while my_number < 20:print my_numbermy_number += 2

ILUG-CBE Programming is Fun

Page 44: Ilucbe python v1.2

Let’s Iterate

ILUG-CBE Programming is Fun

Page 45: Ilucbe python v1.2

Dictionaries

Also called as hash, hashmap or associative array

address = {"name":"ILUG-CBE","houseno":"Nil","street":"any whare","city":"Coimbatore"}print address

ILUG-CBE Programming is Fun

Page 46: Ilucbe python v1.2

Dictionaries

address["state"] = "tamilnadu"address["web"] = "ilugcbe.org.in"

print address

ILUG-CBE Programming is Fun

Page 47: Ilucbe python v1.2

Dictionaries

print address.has_key("country")

print address.get("phone","No Phone Number Provided")

ILUG-CBE Programming is Fun

Page 48: Ilucbe python v1.2

Dictionaries

address.setdefault("country","India")

print address

print address.keys()

print address.values()

print address.items()

del address["country"]

print address

ILUG-CBE Programming is Fun

Page 49: Ilucbe python v1.2

Let’s practice Dictionaries

ILUG-CBE Programming is Fun

Page 50: Ilucbe python v1.2

Functions

def say_hai():print "hello"

say_hai()

ILUG-CBE Programming is Fun

Page 51: Ilucbe python v1.2

Functions

def add_two(num):return num + 2

res = add_two(4)

print res

ILUG-CBE Programming is Fun

Page 52: Ilucbe python v1.2

Functions

def add(a,b):"""adds two numbers"""return a + b

res = add_two(4,5)

print res

ILUG-CBE Programming is Fun

Page 53: Ilucbe python v1.2

Functions

def demo(*args):"""*args demo"""for arg in args:

print i * 2

demo(1,2,3,4,5,6)

ILUG-CBE Programming is Fun

Page 54: Ilucbe python v1.2

Functions

def demo(num,*args):"""*args demo"""for arg in args:

print i * num

demo(1,2,3,4,5,6)

ILUG-CBE Programming is Fun

Page 55: Ilucbe python v1.2

Functions

def demo(num,*args):"""*args demo"""mul = []for arg in args:

mul.append(i * num)

return sum(mul)

res = demo(2,2,3,4,5,6)

print res

ILUG-CBE Programming is Fun

Page 56: Ilucbe python v1.2

Functions

def marker(roll_no,details):if details[’marks’] > 60:

print "Roll no %d %s" %(roll_no, "First Class")

marker(12,marks = 62)

ILUG-CBE Programming is Fun

Page 57: Ilucbe python v1.2

Functions

def mulbythree(num,three=3):"""default argument example"""return num * three

res = mulbythree(43)print res

ILUG-CBE Programming is Fun

Page 58: Ilucbe python v1.2

Be functional now

ILUG-CBE Programming is Fun

Page 59: Ilucbe python v1.2

Tricks 1

nums = [1,2,3,4,5,6,7,8,9]mulbt = [num * 2 for num in nums]

print numsprint mulbt

ILUG-CBE Programming is Fun

Page 60: Ilucbe python v1.2

Tricks - 2

nums = [1,2,3,4,5,6,7,8,9]mulbt = [num * 2 for num in nums if num / 2 != 0]

print numsprint mulbt

ILUG-CBE Programming is Fun

Page 61: Ilucbe python v1.2

Tricks - 3

nums = [1,2,3,4,5,6,7,8,9]numtuple = tuple(nums)

print type(nums)print type(numtuple)

ILUG-CBE Programming is Fun

Page 62: Ilucbe python v1.2

Tricks - 4

print "ILUGCBE".lower().upper().title()

ILUG-CBE Programming is Fun

Page 63: Ilucbe python v1.2

User input

name = raw_input("Tell your name: ")

print name

age = int(raw_input("Tell your age: "))

print age

ILUG-CBE Programming is Fun

Page 64: Ilucbe python v1.2

Tricks time

ILUG-CBE Programming is Fun

Page 65: Ilucbe python v1.2

Lambda

product = lambda x,y : x * y

res = product(12,13)print res

ILUG-CBE Programming is Fun

Page 66: Ilucbe python v1.2

Lambda

dbtnt = lambda x : x * 2 if x % 2 == 0 else x

res = dbtnt(12)print res

ILUG-CBE Programming is Fun

Page 67: Ilucbe python v1.2

Lambda

bors = lambda x: x > 100 and ’big’ or ’small’

for i in (1, 10, 99, 100, 101, 110):print i, ’is’, f(i)

ILUG-CBE Programming is Fun

Page 68: Ilucbe python v1.2

Object Oriented Programming - basics

class MyClass:"""This is my class"""def __init__(self):

#nothing

def say_hai(self):print "Hai"

obj = MyClass()obj.say_hai()

ILUG-CBE Programming is Fun

Page 69: Ilucbe python v1.2

Object Oriented Programming - basics

class MyClass(object):"""This is my class"""def __init__(self):

#nothing

def say_hai(self):print "Hai"

obj = MyClass()obj.say_hai()

ILUG-CBE Programming is Fun

Page 70: Ilucbe python v1.2

Object Oriented Programming - basics

class Student:"""Student class"""

def __init__(self):self.college = "My College"

def greet(self,name):"""Function to greet student"""print "Hello %s from %s" %(name, self.college)

student = Student()student.greet("Jaganadh")

ILUG-CBE Programming is Fun

Page 71: Ilucbe python v1.2

Object Oriented Programming - inheritance

class BeStudent:def __init__(self):

Student.__init__(self)self.class = "BE First Year"

def greet(self,name):print "Hello %s from %s %s class" %(name,self.college,self.class)

student = BeStudent()student.greet("Jaganadh G")

ILUG-CBE Programming is Fun

Page 72: Ilucbe python v1.2

Object Oriented Time

ILUG-CBE Programming is Fun

Page 73: Ilucbe python v1.2

File I/O - read file

input = open("file.txt",’r’)contents = input.read()input.close()

print contents

input = open("file.txt",’r’)contents = input.readlines()input.close()

print contents

ILUG-CBE Programming is Fun

Page 74: Ilucbe python v1.2

File I/O - write to file

names = ["linus","rms","larry","guido"]output = open("out_file.txt",’w’)for name in names:

output.write(name)output.write("\n")

ILUG-CBE Programming is Fun

Page 75: Ilucbe python v1.2

File I/O - write to file

names = ["linus","rms","larry","guido"]output = open("out_file.txt",’a’)for name in names:

output.write(name)output.write("\n")

ILUG-CBE Programming is Fun

Page 76: Ilucbe python v1.2

Let’s play with files

ILUG-CBE Programming is Fun

Page 77: Ilucbe python v1.2

Batteries

Standard Libraries

Python comes with batteries included. Lots of useful libraries arethere in the language. Let’s see some of these libraries now

import mathprint math.piprint math.sqrt(10)print math.factorial(10)print math.sin(10)print math.pow(10,2)print math.log(10)print math.log(10,2)print math.log10(10)print math.exp(10)

ILUG-CBE Programming is Fun

Page 78: Ilucbe python v1.2

Batteries - sys

import sysprint sys.platform

afl = sys.argv[1]

print sys.versionprint sys.maxintprint sys.maxsize

ILUG-CBE Programming is Fun

Page 79: Ilucbe python v1.2

Batteries - os

import osprint os.curdir()print os.getlogin()print os.getcwd()print os.name

ILUG-CBE Programming is Fun

Page 80: Ilucbe python v1.2

Batteries - time,random

import timeprint time.ctime()print time.gmtime()

import randomprint random.random()print random.choice([1,2,3,4,5,6])

ILUG-CBE Programming is Fun

Page 81: Ilucbe python v1.2

Battery Recharge

ILUG-CBE Programming is Fun

Page 82: Ilucbe python v1.2

Question Time

ILUG-CBE Programming is Fun

Page 83: Ilucbe python v1.2

Contributors

Jaganadh G @jaganadhg

Biju B @bijubk

Satheesh Kumar D

Sreejith S @tweet2sree

Rajith Ravi @chelakkandupoda

ILUG-CBE Programming is Fun

Page 84: Ilucbe python v1.2

Contact US

Web

http://ilugcbe.org.inmail [email protected]

ILUG-CBE Programming is Fun