SlideShare a Scribd company logo
Learn Python in
20 minutes
printing
print “hello world”
print ‘hello world’
Strings must be inside quotes
print ‘hello world’
print ‘hello world’,
Comma can be used to prevent new line.
printing
print ‘hello ’ + ‘world’
print ‘hello ’ * 3
print ‘4’ + ‘6’
print 4 + 6
print 4 > 6
hello world
hello hello hello
10
46
False
printing
x = ‘hello world’
y = 4
x,y = ‘hello world’,4
variables
s = ‘hello world’
print s.upper() HELLO WORLD
strings
s.capitalize() Capitalizes the first character.
s.center(width [, pad]) Centers the string in a field of length width.
s.count(sub [,start [,end]]) Counts occurrences of sub
s.endswith(suffix [,start [,end]]) Checks the end of the string for a suffix.
s.find(sub [, start [,end]]) Finds the first occurrence of sub or returns -1.
s.isalnum() Checks whether all characters are alphanumeric.
s.isalpha() Checks whether all characters are alphabetic.
s.isdigit() Checks whether all characters are digits.
s.islower() Checks whether all characters are lowercase.
s.isspace() Checks whether all characters are whitespace.
s.istitle() Checks whether the string is titlecased
s = ‘hello world’
String methods
s.capitalize() Hello world
s.center(15 ,’#’) ##hello world##
s.count(‘l’) 3
s.endswith(‘rld’) True
s.find(‘wor’) 6
'123abc'.isalnum() True
'abc'.isalpha() True
'123'.isdigit() True
‘abc’.islower() True
' '.isspace() True
'Hello World'.istitle() True
s = ‘hello world’
String method examples
s.join(t) Joins the strings in sequence t with s as a separator.
s.split([sep [,maxsplit]]) Splits a string using sep as a delimiter
s.ljust(width [, fill]) Left-aligns s in a string of size width.
s.lower() Converts to lowercase.
s.partition(sep) Partitions string based on sep.Returns (head,sep,tail)
s.replace(old, new [,maxreplace]) Replaces a substring.
s.startswith(prefix [,start [,end]]) Checks whether a string starts with prefix.
s.strip([chrs]) Removes leading and trailing whitespace or chrs.
s.swapcase() Converts uppercase to lowercase, and vice versa.
s.title() Returns a title-cased version of the string.
s = ‘hello world’
String more methods
'/'.join(['a','b','c']) a/b/c
'a/b/c'.split('/') ['a', 'b', 'c']
s.ljust(15,’#’) hello world####
‘Hello World’.lower() hello world
'hello;world'.partition(';') ('hello', ';', 'world')
s.replace('hello','hi') hi world
s.startswith(‘hel’) True
'abcabca'.strip('ac') bcab
'aBcD'.swapcase() AbCd
s.title() Hello World
s = ‘hello world’
String methods examples
if a > b :
print a,’ is greater’
else :
print a,’ is not greater’
If
if a > b :
print a,’ is greater’
elif a < b :
print a,’ is lesser’
else :
print ‘Both are equal’
Else – if
i = 0
while i < 10 :
i += 1
print i
1
2
3
4
5
6
7
8
9
10
While
xrange is a built-in function which returns a sequence of integers
xrange(start, stop[, step])
for i in xrange(0,10):
print i,
for i in xrange(0,10,2):
print i,
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8
For - in
s.append(x) Appends a new element, x, to the end of s
s.extend(t) Appends a new list, t, to the end of s.
s.count(x) Counts occurrences of x in s.
s.index(x [,start [,stop]]) Returns the smallest i where s[i]==x.
s.insert(i,x) Inserts x at index i.
s.pop([i]) Returns the element i and removes it from the list.
s.remove(x) Searches for x and removes it from s.
s.reverse() Reverses items of s in place.
s.sort([key [, reverse]]) Sorts items of s in place.
s = [ ‘jan’ , ’feb’ , ’mar’ , ’apr’ , ’may’ ]
x = ‘jun’
List
Slices represent a part of sequence or list
a = ‘01234’
a[1:4]
a[1:]
a[:4]
a[:]
a[1:4:2]
123
1234
0123
01234
13
Slice
s = ( ‘jan’ , ’feb’ , ’mar’ , ’apr’ , ’may’ )
Tuples are just like lists, but you can't change their values
Tuples are defined in ( ), whereas lists in [ ]
tuple
s = { ‘jan’ : 12, ’feb’ : 32, ’mar’ : 23, ’apr’ : 17, ’may’ : 9 }
print s[‘feb’]
for m in s :
print m, s[m]
32
jan 12
feb 32
mar 23
apr 17
may 9
Dictionary
len(m) Returns the number of items in m.
del m[k] Removes m[k] from m.
k in m Returns True if k is a key in m.
m.clear() Removes all items from m.
m.copy() Makes a copy of m.
m.fromkeys(s [,value]) Create a new dictionary with keys from sequence s
m.get(k [,v]) Returns m[k] if found; otherwise, returns v.
m.has_key(k) Returns True if m has key k; otherwise, returns False.
m.items() Returns a sequence of (key,value) pairs.
m.keys() Returns a sequence of key values.
m = { ‘jan’ : 12, ’feb’ : 32, ’mar’ : 23, ’apr’ : 17, ’may’ : 9 }
x = ‘feb’
Dictionary
for var in open(‘input.txt’, ‘r’) :
print var,
Read file
f1 = open(‘output.txt’,’w’)
f1.write(‘first linen’)
f1.write(‘second linen’)
f1.close()
Write file
def getAreaPerimeter(x,y) :
a = x * y
p = 2*(x+y)
print ‘area is’,a,’perimeter is’,p
getAreaPerimeter(14,23)
area is 322 perimeter is 74
Functions
def getAreaPerimeter(x,y) :
areA = x * y
perimeteR = 2*(x+y)
return (areA,perimeteR)
a,p = getAreaPerimeter(14,23)
print ‘area is’,a,’perimeter is’,p
area is 322 perimeter is 74
Function with return
Built-in functions
More details
Useful modules
import re
m1 = re.match(’(S+) (d+)’, ’august 24’)
print m1.group(1)
print m1.group(2)
m1 = re.search(‘(d+)’,’august 24’)
print m1.group(1)
august
24
24
Regular expressions
Command line arguments
sys - System-specific parameters and functions
script1.py: import sys
print sys.argv
python script1.py a b
[‘script1.py’, ‘a’, ‘b’]
sys.argv[0] script.py
sys.argv[1] a
sys.argv[2] b
from subprocess import Popen,PIPE
cmd = ‘date’
Popen(cmd,stdout=PIPE,shell=True).communicate()[0]
Thu Oct 22 17:46:19 MYT 2015
Calling unix commands inside python
import os
os.getcwd() returns current working directory
os.mkdir(path) creates a new directory
os.path.abspath(path) equivalent to resolve command
os.path.basename(path)
os.path.dirname(path)
os.path.join(elements)
> print os.path.join('a','b','c')
a/b/c
Os
Writing excel files
import xlwt
style0 = xlwt.easyxf('font: name Calibri, color-index red, bold on‘)
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
ws.write(0, 0, ‘sample text’, style0)
wb.save(‘example.xls’)
from collections import defaultdict
-for easy handling of dictionaries
import shutil -for copying files and directories
import math -for math functions
import this -to see the Idea behind Python
Few other modules
Guido Van Rossum (Dutch),
Creator of Python
Many years ago, in December 1989, I was looking
for a "hobby" programming project that would
keep me occupied during the week around
Christmas. My office ... would be closed, but I had a
home computer, and not much else on my hands. I
decided to write an interpreter for the new
scripting language I had been thinking about
lately: a descendant of ABC that would appeal to
Unix/C hackers. I chose Python as a working title
for the project, being in a slightly irreverent mood
(and a big fan of Monty Python's Flying Circus)
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
That’s it !
Created by Sidharth C. Nadhan
Hope this helped
You can find me at @sidharthcnadhan@gmail.com

More Related Content

What's hot (20)

PDF
Karate - Web-Service API Testing Made Simple
VodqaBLR
 
PDF
CNIT 127: L9: Web Templates and .NET
Sam Bowne
 
PDF
Introduction to kotlin coroutines
NAVER Engineering
 
PDF
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
Cory Forsyth
 
PDF
Fuzzing: The New Unit Testing
Dmitry Vyukov
 
PPTX
Golang Vs Rust
Simplilearn
 
PDF
Python Foundation – A programmer's introduction to Python concepts & style
Kevlin Henney
 
PDF
Date and Time Module in Python | Edureka
Edureka!
 
PDF
GraalVM Native and Spring Boot 3.0
MoritzHalbritter
 
PDF
Space Camp :: API Lifecycle, Part I: Build and Test an API
Postman
 
PDF
Postman: An Introduction for Testers
Postman
 
PDF
Python made easy
Abhishek kumar
 
PDF
Python Debugging Fundamentals
cbcunc
 
PPTX
Solid Principles
humayunlkhan
 
PDF
Unit Testing in Python
Haim Michael
 
PPTX
Scala fundamentals
Alfonso Ruzafa
 
PPTX
Python basics
Jyoti shukla
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
PDF
Introduction to python
Mohammed Rafi
 
PDF
Python Modules
Soba Arjun
 
Karate - Web-Service API Testing Made Simple
VodqaBLR
 
CNIT 127: L9: Web Templates and .NET
Sam Bowne
 
Introduction to kotlin coroutines
NAVER Engineering
 
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
Cory Forsyth
 
Fuzzing: The New Unit Testing
Dmitry Vyukov
 
Golang Vs Rust
Simplilearn
 
Python Foundation – A programmer's introduction to Python concepts & style
Kevlin Henney
 
Date and Time Module in Python | Edureka
Edureka!
 
GraalVM Native and Spring Boot 3.0
MoritzHalbritter
 
Space Camp :: API Lifecycle, Part I: Build and Test an API
Postman
 
Postman: An Introduction for Testers
Postman
 
Python made easy
Abhishek kumar
 
Python Debugging Fundamentals
cbcunc
 
Solid Principles
humayunlkhan
 
Unit Testing in Python
Haim Michael
 
Scala fundamentals
Alfonso Ruzafa
 
Python basics
Jyoti shukla
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Introduction to python
Mohammed Rafi
 
Python Modules
Soba Arjun
 

Viewers also liked (6)

KEY
Why Learn Python?
Christine Cheung
 
PDF
Learn 90% of Python in 90 Minutes
Matt Harrison
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
ODP
Learn python
Kracekumar Ramaraju
 
PPTX
Learn python – for beginners
RajKumar Rampelli
 
PDF
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Why Learn Python?
Christine Cheung
 
Learn 90% of Python in 90 Minutes
Matt Harrison
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Learn python
Kracekumar Ramaraju
 
Learn python – for beginners
RajKumar Rampelli
 
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Ad

Similar to Learn python in 20 minutes (20)

PDF
Template Haskell
Sergey Stretovich
 
PPTX
第二讲 Python基礎
juzihua1102
 
PPTX
第二讲 预备-Python基礎
anzhong70
 
PDF
The Ring programming language version 1.10 book - Part 31 of 212
Mahmoud Samir Fayed
 
PPTX
Pythonlearn-11-Regex.pptx
Dave Tan
 
PDF
Arduino creative coding class part iii
Jonah Marrs
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PPTX
C# introduzione per cibo e altri usi vati
AlessandroSiroCampi
 
PPT
Python
Vishal Sancheti
 
PPTX
13 Strings and Text Processing
Intro C# Book
 
PPTX
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
DOCX
Artificial intelligence - python
Sunjid Hasan
 
PPTX
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
AbhimanyuChaure
 
PPTX
Python 101++: Let's Get Down to Business!
Paige Bailey
 
PPTX
Python Strings and strings types with Examples
Prof. Kartiki Deshmukh
 
PDF
Declarative Thinking, Declarative Practice
Kevlin Henney
 
PDF
9 character string &amp; string library
MomenMostafa
 
PDF
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
PDF
Beginner's Python Cheat Sheet
Verxus
 
Template Haskell
Sergey Stretovich
 
第二讲 Python基礎
juzihua1102
 
第二讲 预备-Python基礎
anzhong70
 
The Ring programming language version 1.10 book - Part 31 of 212
Mahmoud Samir Fayed
 
Pythonlearn-11-Regex.pptx
Dave Tan
 
Arduino creative coding class part iii
Jonah Marrs
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
C# introduzione per cibo e altri usi vati
AlessandroSiroCampi
 
13 Strings and Text Processing
Intro C# Book
 
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Artificial intelligence - python
Sunjid Hasan
 
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
AbhimanyuChaure
 
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python Strings and strings types with Examples
Prof. Kartiki Deshmukh
 
Declarative Thinking, Declarative Practice
Kevlin Henney
 
9 character string &amp; string library
MomenMostafa
 
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Verxus
 
Ad

Recently uploaded (20)

PPTX
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
Seminar Description: YOLO v1 (You Only Look Once).pptx
abhijithpramod20002
 
PDF
PROGRAMMING REQUESTS/RESPONSES WITH GREATFREE IN THE CLOUD ENVIRONMENT
samueljackson3773
 
PDF
Digital water marking system project report
Kamal Acharya
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PDF
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Seminar Description: YOLO v1 (You Only Look Once).pptx
abhijithpramod20002
 
PROGRAMMING REQUESTS/RESPONSES WITH GREATFREE IN THE CLOUD ENVIRONMENT
samueljackson3773
 
Digital water marking system project report
Kamal Acharya
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Distribution reservoir and service storage pptx
dhanashree78
 
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 

Learn python in 20 minutes

  • 2. printing print “hello world” print ‘hello world’ Strings must be inside quotes
  • 3. print ‘hello world’ print ‘hello world’, Comma can be used to prevent new line. printing
  • 4. print ‘hello ’ + ‘world’ print ‘hello ’ * 3 print ‘4’ + ‘6’ print 4 + 6 print 4 > 6 hello world hello hello hello 10 46 False printing
  • 5. x = ‘hello world’ y = 4 x,y = ‘hello world’,4 variables
  • 6. s = ‘hello world’ print s.upper() HELLO WORLD strings
  • 7. s.capitalize() Capitalizes the first character. s.center(width [, pad]) Centers the string in a field of length width. s.count(sub [,start [,end]]) Counts occurrences of sub s.endswith(suffix [,start [,end]]) Checks the end of the string for a suffix. s.find(sub [, start [,end]]) Finds the first occurrence of sub or returns -1. s.isalnum() Checks whether all characters are alphanumeric. s.isalpha() Checks whether all characters are alphabetic. s.isdigit() Checks whether all characters are digits. s.islower() Checks whether all characters are lowercase. s.isspace() Checks whether all characters are whitespace. s.istitle() Checks whether the string is titlecased s = ‘hello world’ String methods
  • 8. s.capitalize() Hello world s.center(15 ,’#’) ##hello world## s.count(‘l’) 3 s.endswith(‘rld’) True s.find(‘wor’) 6 '123abc'.isalnum() True 'abc'.isalpha() True '123'.isdigit() True ‘abc’.islower() True ' '.isspace() True 'Hello World'.istitle() True s = ‘hello world’ String method examples
  • 9. s.join(t) Joins the strings in sequence t with s as a separator. s.split([sep [,maxsplit]]) Splits a string using sep as a delimiter s.ljust(width [, fill]) Left-aligns s in a string of size width. s.lower() Converts to lowercase. s.partition(sep) Partitions string based on sep.Returns (head,sep,tail) s.replace(old, new [,maxreplace]) Replaces a substring. s.startswith(prefix [,start [,end]]) Checks whether a string starts with prefix. s.strip([chrs]) Removes leading and trailing whitespace or chrs. s.swapcase() Converts uppercase to lowercase, and vice versa. s.title() Returns a title-cased version of the string. s = ‘hello world’ String more methods
  • 10. '/'.join(['a','b','c']) a/b/c 'a/b/c'.split('/') ['a', 'b', 'c'] s.ljust(15,’#’) hello world#### ‘Hello World’.lower() hello world 'hello;world'.partition(';') ('hello', ';', 'world') s.replace('hello','hi') hi world s.startswith(‘hel’) True 'abcabca'.strip('ac') bcab 'aBcD'.swapcase() AbCd s.title() Hello World s = ‘hello world’ String methods examples
  • 11. if a > b : print a,’ is greater’ else : print a,’ is not greater’ If
  • 12. if a > b : print a,’ is greater’ elif a < b : print a,’ is lesser’ else : print ‘Both are equal’ Else – if
  • 13. i = 0 while i < 10 : i += 1 print i 1 2 3 4 5 6 7 8 9 10 While
  • 14. xrange is a built-in function which returns a sequence of integers xrange(start, stop[, step]) for i in xrange(0,10): print i, for i in xrange(0,10,2): print i, 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 For - in
  • 15. s.append(x) Appends a new element, x, to the end of s s.extend(t) Appends a new list, t, to the end of s. s.count(x) Counts occurrences of x in s. s.index(x [,start [,stop]]) Returns the smallest i where s[i]==x. s.insert(i,x) Inserts x at index i. s.pop([i]) Returns the element i and removes it from the list. s.remove(x) Searches for x and removes it from s. s.reverse() Reverses items of s in place. s.sort([key [, reverse]]) Sorts items of s in place. s = [ ‘jan’ , ’feb’ , ’mar’ , ’apr’ , ’may’ ] x = ‘jun’ List
  • 16. Slices represent a part of sequence or list a = ‘01234’ a[1:4] a[1:] a[:4] a[:] a[1:4:2] 123 1234 0123 01234 13 Slice
  • 17. s = ( ‘jan’ , ’feb’ , ’mar’ , ’apr’ , ’may’ ) Tuples are just like lists, but you can't change their values Tuples are defined in ( ), whereas lists in [ ] tuple
  • 18. s = { ‘jan’ : 12, ’feb’ : 32, ’mar’ : 23, ’apr’ : 17, ’may’ : 9 } print s[‘feb’] for m in s : print m, s[m] 32 jan 12 feb 32 mar 23 apr 17 may 9 Dictionary
  • 19. len(m) Returns the number of items in m. del m[k] Removes m[k] from m. k in m Returns True if k is a key in m. m.clear() Removes all items from m. m.copy() Makes a copy of m. m.fromkeys(s [,value]) Create a new dictionary with keys from sequence s m.get(k [,v]) Returns m[k] if found; otherwise, returns v. m.has_key(k) Returns True if m has key k; otherwise, returns False. m.items() Returns a sequence of (key,value) pairs. m.keys() Returns a sequence of key values. m = { ‘jan’ : 12, ’feb’ : 32, ’mar’ : 23, ’apr’ : 17, ’may’ : 9 } x = ‘feb’ Dictionary
  • 20. for var in open(‘input.txt’, ‘r’) : print var, Read file
  • 21. f1 = open(‘output.txt’,’w’) f1.write(‘first linen’) f1.write(‘second linen’) f1.close() Write file
  • 22. def getAreaPerimeter(x,y) : a = x * y p = 2*(x+y) print ‘area is’,a,’perimeter is’,p getAreaPerimeter(14,23) area is 322 perimeter is 74 Functions
  • 23. def getAreaPerimeter(x,y) : areA = x * y perimeteR = 2*(x+y) return (areA,perimeteR) a,p = getAreaPerimeter(14,23) print ‘area is’,a,’perimeter is’,p area is 322 perimeter is 74 Function with return
  • 26. import re m1 = re.match(’(S+) (d+)’, ’august 24’) print m1.group(1) print m1.group(2) m1 = re.search(‘(d+)’,’august 24’) print m1.group(1) august 24 24 Regular expressions
  • 27. Command line arguments sys - System-specific parameters and functions script1.py: import sys print sys.argv python script1.py a b [‘script1.py’, ‘a’, ‘b’] sys.argv[0] script.py sys.argv[1] a sys.argv[2] b
  • 28. from subprocess import Popen,PIPE cmd = ‘date’ Popen(cmd,stdout=PIPE,shell=True).communicate()[0] Thu Oct 22 17:46:19 MYT 2015 Calling unix commands inside python
  • 29. import os os.getcwd() returns current working directory os.mkdir(path) creates a new directory os.path.abspath(path) equivalent to resolve command os.path.basename(path) os.path.dirname(path) os.path.join(elements) > print os.path.join('a','b','c') a/b/c Os
  • 30. Writing excel files import xlwt style0 = xlwt.easyxf('font: name Calibri, color-index red, bold on‘) wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') ws.write(0, 0, ‘sample text’, style0) wb.save(‘example.xls’)
  • 31. from collections import defaultdict -for easy handling of dictionaries import shutil -for copying files and directories import math -for math functions import this -to see the Idea behind Python Few other modules
  • 32. Guido Van Rossum (Dutch), Creator of Python Many years ago, in December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus)
  • 33. The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
  • 34. That’s it ! Created by Sidharth C. Nadhan Hope this helped You can find me at @[email protected]