SlideShare a Scribd company logo
1 of 14
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Sumitava Mukherjee [email_address]  /  [email_address]   URL: http://people.cognobytes.com/smukh CBCS, Jan 2009
Defining Functions >>> def fib(n):  # write Fibonacci series up to n   &quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot;   a, b = 0, 1   while b < n:   print b,   a, b = b, a+b >>> # Now call the function we just defined: fib(2000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 -------------------------------------------------------------------------- Keyword 'def' Documentation strings  [ fib.__doc__ ] Symbol table look ups Functions always return only one object/value/None  >>> print fib(0)‏ None
Playing around ... >>> fib <function fib at 10042ed0> >>> f = fib >>> f(100)‏ 1 1 2 3 5 8 13 21 34 55 89 [symbol table entry can be assigned as others] ---------------------------------------- >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> sqr <function sqr at 0x00C556F0> >>> a = [sqr, cube] >>> a[0](2)‏ 4 >>> a[1] (3)‏ 27 --------------------------------------------- Moral: Can manipulate functions as objects!
Playing around ..cont.. >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> def compose (f,g,x): return f(g(x))‏ >>> compose(sqr,cube,2)‏ 64 ....................................................................................................................... Next >  Function arguments
Arguments in Functions It is also possible to define functions with a variable number of arguments.  There are three forms, which can be combined. (1) Default Argument values (2) Keyword arguments (3) Arbitrary argument list
Arguments in Functions ..cont.. Default argument values : def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt)‏ if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint This function can be called either like this: ask_ok('Do you really want to quit?')  or like this: ask_ok('OK to overwrite the file?', 2)‏ ------------------------------------------------------------------------------------------------------------------- The default values are evaluated at the point of function definition in the defining scope and ONLY ONCE, so that i = 5 def f(arg=i): print arg i = 6 f()‏ will print 5.
Arguments in Functions ..cont.. Keyword arguments : Functions can also be called using keyword arguments of the form keyword = value.  For instance, the following function: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print &quot;-- This parrot wouldn't&quot;, action, print &quot;if you put&quot;, voltage, &quot;volts through it.&quot; print &quot;-- Lovely plumage, the&quot;, type print &quot;-- It's&quot;, state, &quot;!&quot; could be called in any of the following ways: parrot(1000)‏ parrot(action = 'VOOOOOM', voltage = 1000000)‏ parrot('a thousand', state = 'pushing up the daisies')‏ parrot('a million', 'bereft of life', 'jump')‏ ----------------------------------------------------------------------------------- In general, an argument list must have any positional arguments followed by any keyword arguments, where the keywords must be chosen from the formal parameter names.
Arguments in Functions ..cont.. Variable number of arguments : >>> def fool (*args): print len(args)‏ >>> fool(2,3,4)‏ 3 >>> fool(2,3,4,5,)‏ 4 >>> fool()‏ 0
Modules A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__ Say you have a file fibo.py >>> import fibo This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions: >>> fibo.fib(1000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 you can assign it to a local name: >>> fib = fibo.fib >>> fib(500)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Multiple Imports: >>> from fibo import fib, fib2 >>> from fibo import *
When you run a Python module with python fibo.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to &quot;__main__&quot;.  That means that by adding this code at the end of your module: if __name__ == &quot;__main__&quot;: import sys fib(int(sys.argv[1]))‏ you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the β€œmain” file: $ python fibo.py 50 1 1 2 3 5 8 13 21 34 If the module is imported, the code is not run: >>> import fibo >>> This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
Standard Modules Python comes with a library of standard modules. Some modules are built into the interpreter; these provide  access to operations that are not part of the core of the language  but are nevertheless built in,  either for efficiency  or to provide access to operating system primitives such as system calls.  The set of such modules is a configuration option which also depends on the underlying platform For example, the winreg module is only provided on Windows systems. Example : sys, __builtin__ >>> import __builtin__ >>> dir(__builtin__)‏ ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning',.....**many more**
Standard Exception handling Exceptions: >>> 10 * (1/0)‏ Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? ZeroDivisionError : integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? NameError : name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? TypeError : cannot concatenate 'str' and 'int' objects >>> a=[1,2,3] >>> print a[100] Traceback (most recent call last): File &quot;<pyshell#111>&quot;, line 1, in <module> print a[100] IndexError : list index out of range
>>> while True: ...  try: ...  x = int(raw_input(&quot;Please enter a number: &quot;))‏ ...  break ...  except ValueError: ...  print &quot;Oops!  That was no valid number.  Try again...&quot; ... The try statement works as follows: First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped.  Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message.
A try statement may have more than one except clause, to specify handlers for different exceptions.  try: simval=  (wordnet.N[something[i].strip()][0].path_similarity(wordnet.N[something[j].strip()][0]))‏ print 'For', something[i].strip(),' and ', something[j].strip(), ' similarity value is : ', simval score+=simval except KeyError: pass except ValueError: pass finally: pass

More Related Content

What's hot

Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)IoT Code Lab
Β 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
Β 
Pointers in C
Pointers in CPointers in C
Pointers in Cguestdc3f16
Β 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
Β 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
Β 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstackThierry Gayet
Β 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
Β 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehmanNauman Rehman
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
Β 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c languagegourav kottawar
Β 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
Β 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick offAndrea Gangemi
Β 
C Tutorials
C TutorialsC Tutorials
C TutorialsSudharsan S
Β 

What's hot (20)

Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Β 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
Β 
Python basic
Python basicPython basic
Python basic
Β 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
Β 
Pointers in C
Pointers in CPointers in C
Pointers in C
Β 
Python Presentation
Python PresentationPython Presentation
Python Presentation
Β 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
Β 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Β 
Functions in python
Functions in pythonFunctions in python
Functions in python
Β 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
Β 
Programming in Python
Programming in Python Programming in Python
Programming in Python
Β 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Β 
Ponters
PontersPonters
Ponters
Β 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
Β 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
Β 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
Β 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Β 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Β 
C pointers
C pointersC pointers
C pointers
Β 

Viewers also liked

Re-thinking about the brain [based on the case of Nico-with half a brain]
Re-thinking about the brain [based on the case of Nico-with half a brain]Re-thinking about the brain [based on the case of Nico-with half a brain]
Re-thinking about the brain [based on the case of Nico-with half a brain]Sumitava Mukherjee
Β 
Issus with the definition of Unconscious Thought in Unconscious Thought Theory
Issus with the definition of Unconscious Thought in Unconscious Thought TheoryIssus with the definition of Unconscious Thought in Unconscious Thought Theory
Issus with the definition of Unconscious Thought in Unconscious Thought TheorySumitava Mukherjee
Β 
Introduction to decision making
Introduction to decision making Introduction to decision making
Introduction to decision making Sumitava Mukherjee
Β 
Cognitive Architectures Comparision based on perceptual processing
Cognitive Architectures Comparision based on perceptual processingCognitive Architectures Comparision based on perceptual processing
Cognitive Architectures Comparision based on perceptual processingSumitava Mukherjee
Β 
Neuroplasticity presentation
Neuroplasticity presentationNeuroplasticity presentation
Neuroplasticity presentationneandergal
Β 

Viewers also liked (6)

Re-thinking about the brain [based on the case of Nico-with half a brain]
Re-thinking about the brain [based on the case of Nico-with half a brain]Re-thinking about the brain [based on the case of Nico-with half a brain]
Re-thinking about the brain [based on the case of Nico-with half a brain]
Β 
Issus with the definition of Unconscious Thought in Unconscious Thought Theory
Issus with the definition of Unconscious Thought in Unconscious Thought TheoryIssus with the definition of Unconscious Thought in Unconscious Thought Theory
Issus with the definition of Unconscious Thought in Unconscious Thought Theory
Β 
Introduction to decision making
Introduction to decision making Introduction to decision making
Introduction to decision making
Β 
Cognitive Architectures Comparision based on perceptual processing
Cognitive Architectures Comparision based on perceptual processingCognitive Architectures Comparision based on perceptual processing
Cognitive Architectures Comparision based on perceptual processing
Β 
Emotion Introduction
Emotion IntroductionEmotion Introduction
Emotion Introduction
Β 
Neuroplasticity presentation
Neuroplasticity presentationNeuroplasticity presentation
Neuroplasticity presentation
Β 

Similar to Python Intro-Functions

ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
Β 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
Β 
Python Evolution
Python EvolutionPython Evolution
Python EvolutionQuintagroup
Β 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
Β 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxSheetalMavi2
Β 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentalsnatnaelmamuye
Β 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapaloozaJenniferBall44
Β 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
Β 
08 -functions
08  -functions08  -functions
08 -functionsHector Garzo
Β 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2Giovanni Della Lunga
Β 
matmultHomework3.pdfNames of Files to Submit matmult..docx
matmultHomework3.pdfNames of Files to Submit  matmult..docxmatmultHomework3.pdfNames of Files to Submit  matmult..docx
matmultHomework3.pdfNames of Files to Submit matmult..docxandreecapon
Β 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functionsAlisha Korpal
Β 

Similar to Python Intro-Functions (20)

Python 3000
Python 3000Python 3000
Python 3000
Β 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
Β 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Β 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
Β 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Β 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
Β 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
Β 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
Β 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
Β 
Functions
FunctionsFunctions
Functions
Β 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Β 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
Β 
02basics
02basics02basics
02basics
Β 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Β 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
Β 
08 -functions
08  -functions08  -functions
08 -functions
Β 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2
Β 
matmultHomework3.pdfNames of Files to Submit matmult..docx
matmultHomework3.pdfNames of Files to Submit  matmult..docxmatmultHomework3.pdfNames of Files to Submit  matmult..docx
matmultHomework3.pdfNames of Files to Submit matmult..docx
Β 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
Β 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
Β 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
Β 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
Β 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
Β 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
Β 
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈcall girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ9953056974 Low Rate Call Girls In Saket, Delhi NCR
Β 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
Β 
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
Β 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
Β 
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdfssuser54595a
Β 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
Β 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
Β 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
Β 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
Β 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
Β 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
Β 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
Β 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
Β 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
Β 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
Β 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
Β 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
Β 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
Β 
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈcall girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
Β 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
Β 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
Β 
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
β€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
Β 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Β 
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAΠ‘Y_INDEX-DM_23-1-final-eng.pdf
Β 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
Β 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
Β 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
Β 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
Β 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Β 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
Β 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
Β 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
Β 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
Β 
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Β 

Python Intro-Functions

  • 1.
  • 2. Defining Functions >>> def fib(n): # write Fibonacci series up to n &quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot; a, b = 0, 1 while b < n: print b, a, b = b, a+b >>> # Now call the function we just defined: fib(2000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 -------------------------------------------------------------------------- Keyword 'def' Documentation strings [ fib.__doc__ ] Symbol table look ups Functions always return only one object/value/None >>> print fib(0)‏ None
  • 3. Playing around ... >>> fib <function fib at 10042ed0> >>> f = fib >>> f(100)‏ 1 1 2 3 5 8 13 21 34 55 89 [symbol table entry can be assigned as others] ---------------------------------------- >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> sqr <function sqr at 0x00C556F0> >>> a = [sqr, cube] >>> a[0](2)‏ 4 >>> a[1] (3)‏ 27 --------------------------------------------- Moral: Can manipulate functions as objects!
  • 4. Playing around ..cont.. >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> def compose (f,g,x): return f(g(x))‏ >>> compose(sqr,cube,2)‏ 64 ....................................................................................................................... Next > Function arguments
  • 5. Arguments in Functions It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined. (1) Default Argument values (2) Keyword arguments (3) Arbitrary argument list
  • 6. Arguments in Functions ..cont.. Default argument values : def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt)‏ if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint This function can be called either like this: ask_ok('Do you really want to quit?') or like this: ask_ok('OK to overwrite the file?', 2)‏ ------------------------------------------------------------------------------------------------------------------- The default values are evaluated at the point of function definition in the defining scope and ONLY ONCE, so that i = 5 def f(arg=i): print arg i = 6 f()‏ will print 5.
  • 7. Arguments in Functions ..cont.. Keyword arguments : Functions can also be called using keyword arguments of the form keyword = value. For instance, the following function: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print &quot;-- This parrot wouldn't&quot;, action, print &quot;if you put&quot;, voltage, &quot;volts through it.&quot; print &quot;-- Lovely plumage, the&quot;, type print &quot;-- It's&quot;, state, &quot;!&quot; could be called in any of the following ways: parrot(1000)‏ parrot(action = 'VOOOOOM', voltage = 1000000)‏ parrot('a thousand', state = 'pushing up the daisies')‏ parrot('a million', 'bereft of life', 'jump')‏ ----------------------------------------------------------------------------------- In general, an argument list must have any positional arguments followed by any keyword arguments, where the keywords must be chosen from the formal parameter names.
  • 8. Arguments in Functions ..cont.. Variable number of arguments : >>> def fool (*args): print len(args)‏ >>> fool(2,3,4)‏ 3 >>> fool(2,3,4,5,)‏ 4 >>> fool()‏ 0
  • 9. Modules A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__ Say you have a file fibo.py >>> import fibo This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions: >>> fibo.fib(1000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 you can assign it to a local name: >>> fib = fibo.fib >>> fib(500)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Multiple Imports: >>> from fibo import fib, fib2 >>> from fibo import *
  • 10. When you run a Python module with python fibo.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to &quot;__main__&quot;. That means that by adding this code at the end of your module: if __name__ == &quot;__main__&quot;: import sys fib(int(sys.argv[1]))‏ you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the β€œmain” file: $ python fibo.py 50 1 1 2 3 5 8 13 21 34 If the module is imported, the code is not run: >>> import fibo >>> This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
  • 11. Standard Modules Python comes with a library of standard modules. Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform For example, the winreg module is only provided on Windows systems. Example : sys, __builtin__ >>> import __builtin__ >>> dir(__builtin__)‏ ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning',.....**many more**
  • 12. Standard Exception handling Exceptions: >>> 10 * (1/0)‏ Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? ZeroDivisionError : integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? NameError : name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? TypeError : cannot concatenate 'str' and 'int' objects >>> a=[1,2,3] >>> print a[100] Traceback (most recent call last): File &quot;<pyshell#111>&quot;, line 1, in <module> print a[100] IndexError : list index out of range
  • 13. >>> while True: ... try: ... x = int(raw_input(&quot;Please enter a number: &quot;))‏ ... break ... except ValueError: ... print &quot;Oops! That was no valid number. Try again...&quot; ... The try statement works as follows: First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message.
  • 14. A try statement may have more than one except clause, to specify handlers for different exceptions. try: simval= (wordnet.N[something[i].strip()][0].path_similarity(wordnet.N[something[j].strip()][0]))‏ print 'For', something[i].strip(),' and ', something[j].strip(), ' similarity value is : ', simval score+=simval except KeyError: pass except ValueError: pass finally: pass