SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
PYTHON
Agenda
Introduction
Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e.
you don't have to declare variables), case sensitive (i.e. abc and ABC are two different
variables) and object-oriented (i.e. everything is an object).
Introduction
● No mandatory termination mark
● Blocks are specified by indentation. Indent to begin a block, dedent to end
one.
● Statements that expect an indentation level end in a colon (:).
● Comments start with the pound (#) sign and are single-line, multi-line
strings are used for multi-line comments.
● Values are assigned with the _equals_ sign ("="), and equality testing is
done using two _equals_ signs ("==").
● You can increment/decrement values using the += and -= operators
respectively by the right-hand amount.
>>> a = 3
>>> a += 2
>>> a
5
>>> str = "Hello"
Syntax
Swap values
>>> a, str = str, a
>>> a
'Hello World'
>>> str
5
>>> """This is multiline comment.
... Comment continued."""
'This is multiline comment.nComment continued.'
Syntax Contd...
● The data structures available in python are lists, tuples and dictionaries.
● Lists are like one-dimensional arrays (but you can also have lists of other
lists)
● Dictionaries are associative arrays (like hash tables)
● Tuples are immutable one-dimensional arrays
● Python "arrays" can be of any type, so you can mix integers, strings, etc in
lists/dictionaries/tuples.
● The index of the first item in all array types is 0. Negative numbers count
from the end towards the beginning, -1 is the last item.
● Variables can point to functions.
Datatypes
>>> mylist = ["abcd jkl", 12, 3.24]
>>> mylist[0]
'abcd jkl'
>>> mylist[-1]
3.24
>>> mydict = {"key":"value", "abc":123, "pi":3.141}
>>> mydict["abc"]
123
>>> mytuple = (1,2,3)
>>> myfunc = len
>>> print myfunc(mylist)
3
>>> print mylist[:]
['abcd jkl', 12, 3.24]
>>> print mylist[0:2]
['abcd jkl', 12]
>>> print mylist[-2:-1]
Datatypes Example
● Strings can use either single or double quotation marks, and you can have
quotation marks of one kind inside a string that uses the other kind (i.e.
"He said 'hello'." is valid).
● Multiline strings are enclosed in _triple double (or single) quotes_ (""").
Python supports Unicode out of the box, using the syntax u"This is a
unicode string".
● To fill a string with values, you use the % (modulo) operator and a tuple.
Each %s gets replaced with an item from the tuple, left to right, and you
can also use dictionary substitutions.
>>> print "Name: %s, Number: %s, String: %s" % ("Jayant", 3, 10 * "-")
Name: Jayant, Number: 3, String: ----------
String
>>> rangelist = range(10)
>>>
>>> if rangelist[2] == 2:
... print "The second item is 2"
... elif rangelist[1] == 3:
... print "The second item is 3"
... else:
... print "Unknown"
...
The second item is 2
Flow Control
● Functions are declared with the "def" keyword.
● Optional arguments are set in the function declaration after the mandatory
arguments by being assigned a default value.
● For named arguments, the name of the argument is assigned a value.
Functions can return a tuple (and using tuple unpacking you can
effectively return multiple values).
● Lambda functions are ad hoc functions that are comprised of a single
statement.
● Parameters are passed by reference, but immutable types (tuples, ints,
strings, etc) *cannot be changed*. This is because only the memory
location of the item is passed, and binding another object to a variable
discards the old one, so immutable types are replaced.
Functions
Python supports a limited form of multiple inheritance in classes.
Private variables and methods can be declared (by convention, this is not
enforced by the language) by adding at least two leading underscores and at
most one trailing one (e.g. "__spam").
We can also bind arbitrary names to class instances.
>>> class MyClass(object):
... var = 10
... def __init__(self):
... self.myvar = 3
... def myfunction(self, arg1, arg2):
... return self.myvar
...
>>> # This is the class instantiation
... classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
Classes
>>> classinstance2 = MyClass()
>>> classinstance.var
10
>>> classinstance2.var
10
>>> # Note how we use the class name instead of the instance.
... MyClass.var = 30
>>> classinstance.var
30
>>> classinstance2.var
30
>>> # This will not update the variable on the class, instead it will bind a new
object to the old variable name.
... classinstance.var = 10
>>> classinstance.var
10
>>> classinstance2.var
Classes Contd...
>>> class OtherClass(MyClass):
... # The "self" argument is passed automatically
... # and refers to the class instance, so you can set
... # instance variables as above, but from inside the class.
... def __init__(self, arg1):
... self.myvariable = 3
... print arg1
...
>>> classinstance = OtherClass("test")
test
>>> classinstance.test = 10
>>> classinstance.test
10
Classes Inheritance
Exceptions in Python are handled with try-except [exceptionname] blocks.
[jayant@localhost Python]$ cat function.py
#!/usr/bin/python
def some_func():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Invalid division."
else:
# Exception didn't occur.
print "Valid division."
finally:
print "Division done."
Exceptions
External libraries are used with the import [libname] keyword.
You can also use from [libname] import [funcname] for individual functions.
>>> import random
>>> randomint = random.randint(1, 100)
>>> print randomint
28
>>> randomint = random.randint(1, 100)
>>> print randomint
56
>>> randomint = random.randint(1, 100)
>>> print randomint
84
Importing

Contenu connexe

Tendances (20)

The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Java essence part 1
Java essence part 1Java essence part 1
Java essence part 1
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Scala
ScalaScala
Scala
 
Lec2+lec3
Lec2+lec3Lec2+lec3
Lec2+lec3
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Google06
Google06Google06
Google06
 
Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
 
python
pythonpython
python
 
Python Course for Beginners
Python Course for BeginnersPython Course for Beginners
Python Course for Beginners
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Similaire à Quick python reference

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxfaithxdunce63732
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 

Similaire à Quick python reference (20)

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 

Dernier

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Dernier (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Quick python reference

  • 3. Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don't have to declare variables), case sensitive (i.e. abc and ABC are two different variables) and object-oriented (i.e. everything is an object). Introduction
  • 4. ● No mandatory termination mark ● Blocks are specified by indentation. Indent to begin a block, dedent to end one. ● Statements that expect an indentation level end in a colon (:). ● Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. ● Values are assigned with the _equals_ sign ("="), and equality testing is done using two _equals_ signs ("=="). ● You can increment/decrement values using the += and -= operators respectively by the right-hand amount. >>> a = 3 >>> a += 2 >>> a 5 >>> str = "Hello" Syntax
  • 5. Swap values >>> a, str = str, a >>> a 'Hello World' >>> str 5 >>> """This is multiline comment. ... Comment continued.""" 'This is multiline comment.nComment continued.' Syntax Contd...
  • 6. ● The data structures available in python are lists, tuples and dictionaries. ● Lists are like one-dimensional arrays (but you can also have lists of other lists) ● Dictionaries are associative arrays (like hash tables) ● Tuples are immutable one-dimensional arrays ● Python "arrays" can be of any type, so you can mix integers, strings, etc in lists/dictionaries/tuples. ● The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. ● Variables can point to functions. Datatypes
  • 7. >>> mylist = ["abcd jkl", 12, 3.24] >>> mylist[0] 'abcd jkl' >>> mylist[-1] 3.24 >>> mydict = {"key":"value", "abc":123, "pi":3.141} >>> mydict["abc"] 123 >>> mytuple = (1,2,3) >>> myfunc = len >>> print myfunc(mylist) 3 >>> print mylist[:] ['abcd jkl', 12, 3.24] >>> print mylist[0:2] ['abcd jkl', 12] >>> print mylist[-2:-1] Datatypes Example
  • 8. ● Strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. "He said 'hello'." is valid). ● Multiline strings are enclosed in _triple double (or single) quotes_ ("""). Python supports Unicode out of the box, using the syntax u"This is a unicode string". ● To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions. >>> print "Name: %s, Number: %s, String: %s" % ("Jayant", 3, 10 * "-") Name: Jayant, Number: 3, String: ---------- String
  • 9. >>> rangelist = range(10) >>> >>> if rangelist[2] == 2: ... print "The second item is 2" ... elif rangelist[1] == 3: ... print "The second item is 3" ... else: ... print "Unknown" ... The second item is 2 Flow Control
  • 10. ● Functions are declared with the "def" keyword. ● Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. ● For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). ● Lambda functions are ad hoc functions that are comprised of a single statement. ● Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) *cannot be changed*. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. Functions
  • 11. Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. "__spam"). We can also bind arbitrary names to class instances. >>> class MyClass(object): ... var = 10 ... def __init__(self): ... self.myvar = 3 ... def myfunction(self, arg1, arg2): ... return self.myvar ... >>> # This is the class instantiation ... classinstance = MyClass() >>> classinstance.myfunction(1, 2) 3 Classes
  • 12. >>> classinstance2 = MyClass() >>> classinstance.var 10 >>> classinstance2.var 10 >>> # Note how we use the class name instead of the instance. ... MyClass.var = 30 >>> classinstance.var 30 >>> classinstance2.var 30 >>> # This will not update the variable on the class, instead it will bind a new object to the old variable name. ... classinstance.var = 10 >>> classinstance.var 10 >>> classinstance2.var Classes Contd...
  • 13. >>> class OtherClass(MyClass): ... # The "self" argument is passed automatically ... # and refers to the class instance, so you can set ... # instance variables as above, but from inside the class. ... def __init__(self, arg1): ... self.myvariable = 3 ... print arg1 ... >>> classinstance = OtherClass("test") test >>> classinstance.test = 10 >>> classinstance.test 10 Classes Inheritance
  • 14. Exceptions in Python are handled with try-except [exceptionname] blocks. [jayant@localhost Python]$ cat function.py #!/usr/bin/python def some_func(): try: # Division by zero raises an exception 10 / 0 except ZeroDivisionError: print "Invalid division." else: # Exception didn't occur. print "Valid division." finally: print "Division done." Exceptions
  • 15. External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. >>> import random >>> randomint = random.randint(1, 100) >>> print randomint 28 >>> randomint = random.randint(1, 100) >>> print randomint 56 >>> randomint = random.randint(1, 100) >>> print randomint 84 Importing
  • 16. Python has a wide array of libraries built in for file handling. >>> import pickle >>> mylist = ["This", "is my file", 123, 456] >>> myfile = open(r"test.txt", "w") >>> pickle.dump(mylist, myfile) >>> myfile.close() >>> myfile = open(r"newfile.txt", "w") >>> myfile.write("This is a sample string") >>> myfile.close() >>> myfile = open(r"newfile.txt") >>> print myfile.read() This is a sample string >>> myfile.close() >>> myfile = open(r"test.txt") >>> loadedlist = pickle.load(myfile) >>> myfile.close() File Handling