SlideShare a Scribd company logo
Python Basics
Whitespace matters! Your code will not run correctly if you use improper indentation.
#this is a comment
Basic Python Logic
if:
if test:
#do stuff if test is true
elif test 2:
#do stuff if test2 is true
else:
#do stuff if both tests are false
while:
while test:
#keep doing stuff until
#test is false
for:
for x in aSequence:
#do stuff for each member of aSequence
#for example, each item in a list, each
#character in a string, etc.
for x in range(10):
#do stuff 10 times (0 through 9)
for x in range(5,10):
#do stuff 5 times (5 through 9)
Python Strings
A string is a sequence of characters, usually used to store text.
creation:
 the_string = “Hello World!”

 
 the_string = ‘Hello World!’
accessing:
 the_string[4]
 
 returns ‘o’
splitting:
 the_string.split(‘ ‘)
 returns [‘Hello’, ‘World!’]

 
 the_string.split(‘r”)
 returns [‘Hello Wo’, ‘ld!’]
To join a list of strings together, call join() as a method of the string you want to separate the values in the list (‘’ if
none), and pass the list as an argument. Yes, it’s weird.
words = [“this”, ‘is’, ‘a’, ‘list’, ‘of’, “strings”]
‘ ‘.join(words)! 
 returns “This is a list of strings”
‘ZOOL’.join(words)
 returns “ThisZOOLisZOOLaZOOLlistZOOLofZOOLstrings”
‘’.join(words)
 
 returns “Thisisalistofstrings”
String Formatting: similar to printf() in C, uses the % operator to add elements of a tuple into a string
this_string = “there”
print “Hello %s!”%this_string
 returns “Hello there!”
Python Tuples
A tuple consists of a number of values separated by commas. They are useful for ordered pairs and returning several
values from a function.
creation: emptyTuple = ()
singleItemTuple = (“spam”,) note the comma!
thistuple = 12, 89, ‘a’
thistuple = (12, 89, ‘a’)
accessing: thistuple[0] returns 12
Python Dictionaries
A dictionary is a set of key:value pairs. All keys in a dictionary must be unique.
creation: emptyDict = {}
thisdict = {‘a’:1, ‘b’:23, ‘c’:”eggs”}
accessing: thisdict[‘a’] returns 1
deleting: del thisdict[‘b’]
finding: thisdict.has_key(‘e’) returns False
thisdict.keys() returns [‘a’, ‘c’]
thisdict.items() returns [(‘a’, 1), (‘c’, ‘eggs’)]

 ‘c’ in thisdict returns True
‘paradimethylaminobenzaldehyde’ in thisdict returns False
Python List Manipulation
One of the most important data structures in Python is the list. Lists are very flexible and have many built-in control
functions.
creation: thelist = [5,3,‘p’,9,‘e’]
accessing: thelist[0] returns 5
slicing: thelist[1:3] returns [3, ‘p’]
thelist[2:] returns [‘p’, 9, ‘e’]
thelist[:2] returns [5, 3]
thelist[2:-1] returns [‘p’, 9]
length: len(thelist) returns 5
sort: thelist.sort() no return value
add: thelist.append(37)
return & thelist.pop() returns 37
remove: thelist.pop(1) returns 5
insert: thelist.insert(2, ‘z’)
remove: thelist.remove(‘e’)
del thelist[0]
concatenation: thelist + [0] returns [‘z’,9,’p’,0]
finding: 9 in thelist returns True
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[5,3,’p’,9,’e’]
[3,5,9,’e’,’p’]
[3,5,9,’e’,’p’,37]
[3,5,9,’e’,’p’]
[3,9,’e’,’p’]
[3,’z’,9,’e’,’p’]
[3,’z’,9,’p’]
[‘z’,9,’p’]
[‘z’,9,’p’]
[‘z’,9,’p’]
List Comprehension
A special expression enclosed in square brackets that returns a new list. The expression is of the form:
[expression for expr in sequence if condition] The condition is optional.
>>>[x*5 for x in range(5)]
[0, 5, 10, 15, 20]
>>>[x for x in range(5) if x%2 == 0]
[0, 2, 4]
Python Class and Function Definition
function: def myFunc(param1, param2):
! ! “””By putting this initial sentence in triple quotes, you can
! ! access it by calling myFunc.__doc___”””
#indented code block goes here
spam = param1 + param2
return spam
class:

 class Eggs(ClassWeAreOptionallyInheriting):
def __init__(self):
ClassWeAreOptionallyInheriting.__init__(self)
#initialization (constructor) code goes here
self.cookingStyle = ‘scrambled’
def anotherFunction(self, argument):
if argument == “just contradiction”:
return False
else:
return True
theseEggsInMyProgram = Eggs()
Files
open:
! thisfile = open(“datadirectory/file.txt”) note: forward slash, unlike Windows! This function
defaults to read-only
accessing:

 thisfile.read() 
 
 
 reads entire file into one string

 thisfile.readline() 
 
 reads one line of a file

 thisfile.readlines() 
 
 reads entire file into a list of strings, one per line

 for eachline in thisfile: 
 steps through lines in a file

More Related Content

What's hot (20)

ODP
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
PDF
Frege is a Haskell for the JVM
jwausle
 
PDF
Parsing Contexts for PetitParser
ESUG
 
PDF
Python Peculiarities
noamt
 
ODP
Introduction to Python - Training for Kids
Aimee Maree
 
PDF
Clustering com numpy e cython
Anderson Dantas
 
PPT
Phylogenetics in R
schamber
 
PPTX
PyCon 2011 talk - ngram assembly with Bloom filters
c.titus.brown
 
PDF
2015 11-17-programming inr.key
Yannick Wurm
 
PPTX
Pycon 2011 talk (may not be final, note)
c.titus.brown
 
PDF
ThouCount
Matt R
 
PDF
Learn 90% of Python in 90 Minutes
Matt Harrison
 
PPT
computer notes - Data Structures - 36
ecomputernotes
 
PPTX
Python 101++: Let's Get Down to Business!
Paige Bailey
 
PPTX
The groovy puzzlers (as Presented at JavaOne 2014)
GroovyPuzzlers
 
PDF
The groovy puzzlers (as Presented at Gr8Conf US 2014)
GroovyPuzzlers
 
PDF
AmI 2015 - Python basics
Luigi De Russis
 
PDF
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
akaptur
 
PPTX
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Baruch Sadogursky
 
KEY
Introduce RSpec's Matchers
Tomohiro Nishimura
 
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Frege is a Haskell for the JVM
jwausle
 
Parsing Contexts for PetitParser
ESUG
 
Python Peculiarities
noamt
 
Introduction to Python - Training for Kids
Aimee Maree
 
Clustering com numpy e cython
Anderson Dantas
 
Phylogenetics in R
schamber
 
PyCon 2011 talk - ngram assembly with Bloom filters
c.titus.brown
 
2015 11-17-programming inr.key
Yannick Wurm
 
Pycon 2011 talk (may not be final, note)
c.titus.brown
 
ThouCount
Matt R
 
Learn 90% of Python in 90 Minutes
Matt Harrison
 
computer notes - Data Structures - 36
ecomputernotes
 
Python 101++: Let's Get Down to Business!
Paige Bailey
 
The groovy puzzlers (as Presented at JavaOne 2014)
GroovyPuzzlers
 
The groovy puzzlers (as Presented at Gr8Conf US 2014)
GroovyPuzzlers
 
AmI 2015 - Python basics
Luigi De Russis
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
akaptur
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Baruch Sadogursky
 
Introduce RSpec's Matchers
Tomohiro Nishimura
 

Similar to Python Basic (20)

PPTX
第二讲 Python基礎
juzihua1102
 
PPTX
第二讲 预备-Python基礎
anzhong70
 
PDF
Python 101 1
Iccha Sethi
 
PDF
Python for High School Programmers
Siva Arunachalam
 
PPTX
cover every basics of python with this..
karkimanish411
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PPTX
python beginner talk slide
jonycse
 
PDF
Python revision tour II
Mr. Vikram Singh Slathia
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
PPTX
Perl6 a whistle stop tour
Simon Proctor
 
PDF
Perl6 a whistle stop tour
Simon Proctor
 
PPT
Python tutorial
AllsoftSolutions
 
PDF
Duralexsedregex
Wairton Abreu
 
PDF
Python
대갑 김
 
PPTX
Strings.pptxbfffffffffffffffffffffffffffffffffffffffffd
pawankamal3
 
PDF
Class 6: Lists & dictionaries
Marc Gouw
 
PDF
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
manikbuma
 
PPTX
Python basic
sewoo lee
 
PDF
Perl 6 in Context
lichtkind
 
PPTX
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
第二讲 Python基礎
juzihua1102
 
第二讲 预备-Python基礎
anzhong70
 
Python 101 1
Iccha Sethi
 
Python for High School Programmers
Siva Arunachalam
 
cover every basics of python with this..
karkimanish411
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
python beginner talk slide
jonycse
 
Python revision tour II
Mr. Vikram Singh Slathia
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Perl6 a whistle stop tour
Simon Proctor
 
Perl6 a whistle stop tour
Simon Proctor
 
Python tutorial
AllsoftSolutions
 
Duralexsedregex
Wairton Abreu
 
Python
대갑 김
 
Strings.pptxbfffffffffffffffffffffffffffffffffffffffffd
pawankamal3
 
Class 6: Lists & dictionaries
Marc Gouw
 
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
manikbuma
 
Python basic
sewoo lee
 
Perl 6 in Context
lichtkind
 
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Ad

Recently uploaded (20)

PPTX
Ground improvement techniques-DEWATERING
DivakarSai4
 
PDF
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
PPTX
cybersecurityandthe importance of the that
JayachanduHNJc
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
Ground improvement techniques-DEWATERING
DivakarSai4
 
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
cybersecurityandthe importance of the that
JayachanduHNJc
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
Zero Carbon Building Performance standard
BassemOsman1
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
Ad

Python Basic

  • 1. Python Basics Whitespace matters! Your code will not run correctly if you use improper indentation. #this is a comment Basic Python Logic if: if test: #do stuff if test is true elif test 2: #do stuff if test2 is true else: #do stuff if both tests are false while: while test: #keep doing stuff until #test is false for: for x in aSequence: #do stuff for each member of aSequence #for example, each item in a list, each #character in a string, etc. for x in range(10): #do stuff 10 times (0 through 9) for x in range(5,10): #do stuff 5 times (5 through 9) Python Strings A string is a sequence of characters, usually used to store text. creation: the_string = “Hello World!” the_string = ‘Hello World!’ accessing: the_string[4] returns ‘o’ splitting: the_string.split(‘ ‘) returns [‘Hello’, ‘World!’] the_string.split(‘r”) returns [‘Hello Wo’, ‘ld!’] To join a list of strings together, call join() as a method of the string you want to separate the values in the list (‘’ if none), and pass the list as an argument. Yes, it’s weird. words = [“this”, ‘is’, ‘a’, ‘list’, ‘of’, “strings”] ‘ ‘.join(words)! returns “This is a list of strings” ‘ZOOL’.join(words) returns “ThisZOOLisZOOLaZOOLlistZOOLofZOOLstrings” ‘’.join(words) returns “Thisisalistofstrings” String Formatting: similar to printf() in C, uses the % operator to add elements of a tuple into a string this_string = “there” print “Hello %s!”%this_string returns “Hello there!” Python Tuples A tuple consists of a number of values separated by commas. They are useful for ordered pairs and returning several values from a function. creation: emptyTuple = () singleItemTuple = (“spam”,) note the comma! thistuple = 12, 89, ‘a’ thistuple = (12, 89, ‘a’) accessing: thistuple[0] returns 12
  • 2. Python Dictionaries A dictionary is a set of key:value pairs. All keys in a dictionary must be unique. creation: emptyDict = {} thisdict = {‘a’:1, ‘b’:23, ‘c’:”eggs”} accessing: thisdict[‘a’] returns 1 deleting: del thisdict[‘b’] finding: thisdict.has_key(‘e’) returns False thisdict.keys() returns [‘a’, ‘c’] thisdict.items() returns [(‘a’, 1), (‘c’, ‘eggs’)] ‘c’ in thisdict returns True ‘paradimethylaminobenzaldehyde’ in thisdict returns False Python List Manipulation One of the most important data structures in Python is the list. Lists are very flexible and have many built-in control functions. creation: thelist = [5,3,‘p’,9,‘e’] accessing: thelist[0] returns 5 slicing: thelist[1:3] returns [3, ‘p’] thelist[2:] returns [‘p’, 9, ‘e’] thelist[:2] returns [5, 3] thelist[2:-1] returns [‘p’, 9] length: len(thelist) returns 5 sort: thelist.sort() no return value add: thelist.append(37) return & thelist.pop() returns 37 remove: thelist.pop(1) returns 5 insert: thelist.insert(2, ‘z’) remove: thelist.remove(‘e’) del thelist[0] concatenation: thelist + [0] returns [‘z’,9,’p’,0] finding: 9 in thelist returns True [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [5,3,’p’,9,’e’] [3,5,9,’e’,’p’] [3,5,9,’e’,’p’,37] [3,5,9,’e’,’p’] [3,9,’e’,’p’] [3,’z’,9,’e’,’p’] [3,’z’,9,’p’] [‘z’,9,’p’] [‘z’,9,’p’] [‘z’,9,’p’] List Comprehension A special expression enclosed in square brackets that returns a new list. The expression is of the form: [expression for expr in sequence if condition] The condition is optional. >>>[x*5 for x in range(5)] [0, 5, 10, 15, 20] >>>[x for x in range(5) if x%2 == 0] [0, 2, 4]
  • 3. Python Class and Function Definition function: def myFunc(param1, param2): ! ! “””By putting this initial sentence in triple quotes, you can ! ! access it by calling myFunc.__doc___””” #indented code block goes here spam = param1 + param2 return spam class: class Eggs(ClassWeAreOptionallyInheriting): def __init__(self): ClassWeAreOptionallyInheriting.__init__(self) #initialization (constructor) code goes here self.cookingStyle = ‘scrambled’ def anotherFunction(self, argument): if argument == “just contradiction”: return False else: return True theseEggsInMyProgram = Eggs() Files open: ! thisfile = open(“datadirectory/file.txt”) note: forward slash, unlike Windows! This function defaults to read-only accessing: thisfile.read() reads entire file into one string thisfile.readline() reads one line of a file thisfile.readlines() reads entire file into a list of strings, one per line for eachline in thisfile: steps through lines in a file