SlideShare a Scribd company logo
1 of 15
Download to read offline
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

More Related Content

What's hot (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
 

Similar to 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
 

Similar to 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)
 

Recently uploaded

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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