SlideShare une entreprise Scribd logo
1  sur  3
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVMjwausle
 
Parsing Contexts for PetitParser
Parsing Contexts for PetitParserParsing Contexts for PetitParser
Parsing Contexts for PetitParserESUG
 
Python Peculiarities
Python PeculiaritiesPython Peculiarities
Python Peculiaritiesnoamt
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in Rschamber
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersc.titus.brown
 
2015 11-17-programming inr.key
2015 11-17-programming inr.key2015 11-17-programming inr.key
2015 11-17-programming inr.keyYannick Wurm
 
Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)c.titus.brown
 
ThouCount
ThouCountThouCount
ThouCountMatt R
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
computer notes - Data Structures - 36
computer notes - Data Structures - 36computer notes - Data Structures - 36
computer notes - Data Structures - 36ecomputernotes
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)GroovyPuzzlers
 
The groovy puzzlers (as Presented at Gr8Conf US 2014)
The groovy puzzlers (as Presented at Gr8Conf US 2014)The groovy puzzlers (as Presented at Gr8Conf US 2014)
The groovy puzzlers (as Presented at Gr8Conf US 2014)GroovyPuzzlers
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basicsLuigi De Russis
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 

Tendances (20)

Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Frege is a Haskell for the JVM
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
 
Parsing Contexts for PetitParser
Parsing Contexts for PetitParserParsing Contexts for PetitParser
Parsing Contexts for PetitParser
 
Python Peculiarities
Python PeculiaritiesPython Peculiarities
Python Peculiarities
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in R
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filters
 
2015 11-17-programming inr.key
2015 11-17-programming inr.key2015 11-17-programming inr.key
2015 11-17-programming inr.key
 
Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)Pycon 2011 talk (may not be final, note)
Pycon 2011 talk (may not be final, note)
 
ThouCount
ThouCountThouCount
ThouCount
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
computer notes - Data Structures - 36
computer notes - Data Structures - 36computer notes - Data Structures - 36
computer notes - Data Structures - 36
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)
 
The groovy puzzlers (as Presented at Gr8Conf US 2014)
The groovy puzzlers (as Presented at Gr8Conf US 2014)The groovy puzzlers (as Presented at Gr8Conf US 2014)
The groovy puzzlers (as Presented at Gr8Conf US 2014)
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Introduce RSpec's Matchers
Introduce RSpec's MatchersIntroduce RSpec's Matchers
Introduce RSpec's Matchers
 

Similaire à Python Basic

第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionariesMarc Gouw
 
Python basic
Python basic Python basic
Python basic sewoo lee
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Contextlichtkind
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Ziyauddin Shaik
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonMoses Boudourides
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
 
Data Type In Python.pptx
Data Type In Python.pptxData Type In Python.pptx
Data Type In Python.pptxhothyfa
 

Similaire à Python Basic (20)

第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Duralexsedregex
DuralexsedregexDuralexsedregex
Duralexsedregex
 
Python
PythonPython
Python
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 
Python basic
Python basic Python basic
Python basic
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την Python
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
Data Type In Python.pptx
Data Type In Python.pptxData Type In Python.pptx
Data Type In Python.pptx
 

Dernier

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 

Dernier (20)

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 

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