| Aug | SEP | Oct |
| 19 | ||
| 2019 | 2020 | 2021 |
COLLECTED BY
Collection: Common Crawl
Python Function Tutorial – Type of Functions in Python(With Example)
Learn: Range Function in Python – Range() in Python
>>> def hello():
print("Hello")
The contents inside the body of the function must be equally indented.
As we had discussed in our article on Python syntax, you may use a docstring right under the first line of a function declaration. This is a documentation string, and it explains what the function does.
>>> def hello():
"""
This Python function simply prints hello to the screen
"""
print("Hello")
You can access this docstring using the __doc__ attribute of the function.
>>> def func1():
"""
This is the docstring
"""
print("Hello")>>> func1.__doc__ '\n\tThis is the docstring\n\t'However, if you apply the attribute to a function without a docstring, this happens.
>>> sum.__doc__ >>> type(sum.__doc__) <class 'NoneType'> >>> bool(sum.__doc__)False If you don’t yet know what to put in the function, then you should put the pass statement in its body. If you leave its body empty, you get an error “Expected an indented block”.
>>> def hello1():
pass
>>> hello1()
You can even reassign a function by defining it again.
Learn Methods in Python – Classes, Objects and Functions in Python
>>> def sum(a,b):
print(f"{a}+{b}={a+b}")>>> sum(2,3)2+3=5 Here, the function sum() takes two parameters- a and b. When we call the function, we pass numbers 2 and 3. These are the arguments that fit a and b respectively. We will describe calling a function in point f. A function in Python may contain any number of parameters, or none. In the next example, we try adding an int and a float.
>>> def sum2(a,b):
print(f"{a}+{b}={a+b}")
>>> sum2(3.0,2)
3.0+2=5.0
However, you can’t add incompatible types.
>>> sum2('Hello',2)
Traceback (most recent call last):
File “<pyshell#39>”, line 1, in <module>
sum2(‘Hello’,2)
File “<pyshell#38>”, line 2, in sum2
print(f”{a}+{b}={a+b}”)
TypeError: must be str, not int
Learn Python Strings with String Functions and String Operations
>>> def func1(a): if a%2==0: return 0 else: return 1 >>> func1(7)1 As soon as a return statement is reached in a function, the function stops executing. Then, the next statement after the function call is executed. Let’s try returning an expression.
>>> def sum(a,b):
return a+b
>>> sum(2,3)
5
>>> c=sum(2,3)This was the Python Return Function
>>> hello()Hello We already saw how to call python function with arguments in section e. Learn: Python Operators with Syntax and Examples
>>> def func3():
x=7
print(x)
>>> func3()
7
If you then try to access the variable x outside the function, you cannot.
>>>x
Traceback (most recent call last):
File “<pyshell#96>”, line 1, in <module>
x
NameError: name ‘x’ is not defined
●Global Scope- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program.
>>> y=7
>>> def func4():
print(y)
>>> func4()
7
However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the ‘global’ keyword.
>>> def func4():
global y
y+=1
print(y)
>>> func4()
8
>>>y
8
As you can see, y has been changed to 8.
Learn: Python Variables and Data Types with Syntax and Examples
2. Lifetime
A variable’s lifetime is the period of time for which it resides in the memory.
A variable that’s declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable.
>>> def func1():
counter=0
counter+=1
print(counter)
>>> func1()
1
>>> func1()1 As you can see here, the function func1() doesn’t print 2 the second time.
>>> def func7():
print("7")
>>> func7()
7
>>> del func7 >>> func7()Traceback (most recent call last): File “<pyshell#137>”, line 1, in <module> func7() NameError: name ‘func7’ is not defined When deleting a function, you don’t need to put parentheses after its name. Different Python Function Explained Below. Learn: Python Installation Tutorial – Steps to Install Python on Windows
>>> myvar=lambda a,b:(a*b)+2 >>> myvar(3,5)17 This code takes the numbers 3 and 5 as arguments a and b respectively, and puts them in the expression (a*b)+2. This makes it (3*5)+2, which is 17. Finally, it returns 17. Actually, the function object is assigned to the identifier myvar. Learn: Python Arguments with Types, Syntax and Examples Any Doubt yet in Python Function? Please Comment.
>>> def facto(n): if n==1: return 1 return n*facto(n-1) >>> facto(5)120
>>> facto(1)
1
>>> facto(2)
2
>>> facto(3)
6
This was all about recursion function in Python
Isn’t this handy? Tell us where else would you use recursion. However, remember that if you don’t mention the base case (the case which converges the condition), it can result in an infinite execution.
Learn: Learn Python Closure – Nested Functions and Nonlocal Variables
This was all about the Python Function
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Python Tutorials ●Python – Introduction ●Python – Features ●Python – Pros and Cons ●Python – Master Guide ●Python – Best Practices ●Python – Reasons to Learn ●Python – Tools ●Python 3.8 Features ●Python – Install on Windows ●Python – Advantages over Java ●Python – Syntax ●Python – Comments, Indentations and Statements ●Python – Random Number ●Python – Variables and Data Types ●Python – Variable Scope ●Python – Identifiers ●Python – Number Types ●Python – Strings ●Python – Interpreter ●Python – Operators ●Python – Bitwise Operators ●Python – Comparison Operators ●Python – Operator Overloading ●Python – Ternary Operator ●Python – Operator Precedence ●Python – Namespaces ●Python – Decision Making ●Python – Implement Switch Case ●Python – Data Structures ●Python – Lists ●Python – Tuples ●Python – Sets & Booleans ●Python – List Comprehension ●Python – Loops in Python ●Python – Functions ●Python – Function Arguments ●Python – Built-in Functions ●Python – Range() Function ●Python – Zip Function ●Python – Eval Function ●Python – exec Function ●Python – repr Function ●Python – Collections Module ●Python – Counters ●Python – Namedtuples ●Python – Dictionaries ●Python – DefaultDict ●Python – OrderedDict ●Python – DateTime ●Python – Modules ●Python – Serialization ●Python – Packages ●Python – Python OS Module ●Python – Python pprint Module ●Python – Virtual Environment ●Python – Date and Time ●Python – Calendar Module ●Python – Recursion ●Python – Lambda Expression ●Python – Decorators ●Python – Generators ●Python – Iterators ●Python – Closures ●Python – Classes ●Python – Methods ●Python – Constructors ●Python – Object ●Python – Inheritance ●Python – Multiple Inheritance ●Python – Compilers & Interpreters ●Python – ZipFile ●Python – File I/O ●Python – File Handling ●Python – Copy A File ●Python – Shallow & Deep Copy ●Python – Rename A File ●Python – Errors and Exceptions ●Python – Exception Handling ●Python – Assert Statements ●Python – Directories ●Python – Iterables ●Python – Itertool ●Python – Property ●Python – Sequences and Collections ●Python – Multithreading ●Python – Regular Expressions ●Python – Debugger ●Python – Multi Processing ●Python – XML Processing ●Python – CGI Programming ●Python – Library ●Python – Math Libraries ●Python – SciPy ●Python – NumPy ●Python – Pandas ●Python – PyQT ●Python – Array Module ●Python – Database Access ●Python – Programming with C ●Python – Frameworks ●Python – Flask ●Python – Django ●Python – Forensics ●Python – Network Programming ●Python – Image Processing ●Python – Sending Email ●Python – GUI Programming ●Python – Unittest ●Python – Logging ●Python – Slice ●Python – Subprocess Module ●Python – sys Module ●Python – Terminologies Part 1 ●Python – Terminologies Part 2 ●Python – OpenCV & Computer Vision ●Python – OpenCV Features ●Python – OpenCV Environment Setup ●Python – Read, Display & Save Image in OpenCV ●Python – Computer Vision Techniques ●Python – Reasons Why Learn Python ●Python – Best Python Books ●Python – Applications ●Python – Healthcare ●Python – Stock Market ●Python – Case Studies ●Case Study – Python at Netflix ●Python – Tuples vs Lists ●Python – Modules vs Packages ●Python – Generators vs Iterators ●Python – Methods vs Functions ●Python vs Scala ●Python vs Java ●Python vs R ●Python For Beginners – Infographic ●Python Features – Infographic Python for Data Science ●Learn Python for Data Science ●Python – Data Science Tutorial ●Mastering Python for Data Science ●Python – Data Science Installation ●Python – Data Cleansing & Operations ●Python – Data File Formats ●Python – Relational Database ●Python – NoSQL Database ●Python – Stemming & Lemmatization ●Python – Aggregation & Data Wrangling ●Python – Statistics ●Python – Descriptive Statistics ●Python – Probability Distributions ●Python Anaconda Tutorial ●Python – Matplotlib ●Python – Scatter & Box Plots ●Python – Bubble & 3D Charts ●Python – Heatmap & Word Cloud ●Python – Histogram & Bar Plot ●Python – Geographical Map & Graph ●Python – Time Series ●Python – Linear Regression ●Python – Importance for ML ●Python ML – Tutorial ●Python ML – Environment Setup ●Python ML – Data Pre-Processing ●Python ML – Train and Test Set ●Python ML – Techniques ●Python ML – Application ●Python ML – Algorithms ●Python Deep Learning Tutorial ●Python DL – Environment Setup ●Python DL – Application ●Python DL – Python Libraries ●Python DL – Deep Neural Networks ●Python DL – Computational Graphs ●Python AI Tutorial ●Python AI – NLTK ●Python AI – Speech Recognition ●Python AI – NLP Tutorial ●Python AI – Heuristic Search ●Python AI – Genetic Algorithms ●Python AI – Computer Vision ●Python AI – Logic Programming Python Career Guides ●Python – Interesting Facts ●Python – Demand ●Python – Future ●Python – Career Opportunities ●Python – How Fresher Gets Job ●Python – Create Resume ●Python – Career Path ●Python – Become Developer ●Python Career – Infographic Python Projects ●Top Python Projects with source code Python Interview Questions ●Python – Beginners Interview Questions ●Python – Intermediates Interview Questions ●Python – Experts Interview Questions Python Quiz ●Python Quiz- Part 1 ●Python Quiz- Part 2 ●Python Quiz- Part 3 Home About us Contact us Terms and Conditions Privacy Policy Disclaimer Write For Us Success Stories Popular Courses
Hadoop + Spark Course
Big Data Hadoop Course
Spark Scala Course
Python Course
Popular Tutorials
Hadoop Tutorials
Spark Tutorials
Flink Tutorials
Tableau Tutorials
Power BI Tutorials
Popular Tutorials
Data Science Tutorials
Machine Learning Tutorials
Python Tutorials
R Tutorials
SAS Tutorials
DataFlair © 2020. All Rights Reserved.