Python Language
- Getting started with Python Language
- Awesome Book
- Awesome Community
- Awesome Course
- Awesome Tutorial
- Awesome YouTube
- *args and **kwargs
- 2to3 tool
- Abstract Base Classes (abc)
- Abstract syntax tree
- Accessing Python source code and bytecode
- Alternatives to switch statement from other languages
- ArcPy
- Arrays
- Asyncio Module
- Attribute Access
- Audio
- Basic Curses with Python
- Basic Input and Output
- Binary Data
- Bitwise Operators
- Boolean Operators
- Call Python from C#
- Checking Path Existence and Permissions
- ChemPy - python package
- Classes
- CLI subcommands with precise help output
- Code blocks, execution frames, and namespaces
- Collections module
- Comments and Documentation
- Common Pitfalls
- Commonwealth Exceptions
- Comparisons
- Complex math
- Conditionals
- configparser
- Connecting Python to SQL Server
- Context Managers (“with” Statement)
- Copying data
- Counting
- Create virtual environment with virtualenvwrapper in windows
- Creating a Windows service using Python
- Creating Python packages
- ctypes
- Data Serialization
- Data Visualization with Python
- Database Access
- Date and Time
- Date Formatting
- Debugging
- Decorators
- Defining functions with list arguments
- Deployment
- Deque Module
- Descriptor
- Design Patterns
- Dictionary
- Difference between Module and Package
- Distribution
- Django
- Dynamic code execution with `exec` and `eval`
- Enum
- Exceptions
- Exponentiation
- Files & Folders I/O
- Filter
- Flask
- Functional Programming in Python
- Functions
- Defining and calling simple functions
- Argument passing and mutability
- Closure
- Defining a function with an arbitrary number of arguments
- Defining a function with arguments
- Defining a function with multiple arguments
- Defining a function with optional arguments
- Defining a function with optional mutable arguments
- Forcing the use of named parameters
- Iterable and dictionary unpacking
- Lambda (Inline/Anonymous) Functions
- Nested functions
- Recursion limit
- Recursive functions
- Recursive Lambda using assigned variable
- Returning values from functions
- Functools Module
- Garbage Collection
- Generators
- getting start with GZip
- graph-tool
- groupby()
- hashlib
- Heapq
- Hidden Features
- HTML Parsing
- Idioms
- ijson
- Immutable datatypes(int, float, str, tuple and frozensets)
- Importing modules
- Incompatibilities moving from Python 2 to Python 3
- Indentation
- Indexing and Slicing
- Input, Subset and Output External Data Files using Pandas
- Introduction to RabbitMQ using AMQPStorm
- IoT Programming with Python and Raspberry PI
- Iterables and Iterators
- Itertools Module
- JSON Module
- kivy - Cross-platform Python Framework for NUI Development
- Linked List Node
- Linked lists
- List
- List comprehensions
- List Comprehensions
- List destructuring (aka packing and unpacking)
- List slicing (selecting parts of lists)
- Logging
- Loops
- Manipulating XML
- Map Function
- Math Module
- Metaclasses
- Method Overriding
- Mixins
- Multidimensional arrays
- Multiprocessing
- Multithreading
- Mutable vs Immutable (and Hashable) in Python
- Neo4j and Cypher using Py2Neo
- Non-official Python implementations
- Operator module
- Operator Precedence
- Optical Character Recognition
- os.path
- Overloading
- Pandas Transform: Preform operations on groups and concatenate the results
- Parallel computation
- Parsing Command Line arguments
- Partial functions
- Performance optimization
- Pickle data serialisation
- Pillow
- pip: PyPI Package Manager
- Plotting with Matplotlib
- Plugin and Extension Classes
- Polymorphism
- PostgreSQL
- Processes and Threads
- Profiling
- Property Objects
- py.test
- pyaudio
- pyautogui module
- pygame
- Pyglet
- PyInstaller - Distributing Python Code
- Python and Excel
- Python Anti-Patterns
- Python concurrency
- Python Data Types
- Python HTTP Server
- Python Lex-Yacc
- Python Networking
- Python Persistence
- Python Requests Post
- Python Serial Communication (pyserial)
- Python Server Sent Events
- Python speed of program
- Python Virtual Environment - virtualenv
- Queue Module
- Raise Custom Errors / Exceptions
- Random module
- Reading and Writing CSV
- Recursion
- Reduce
- Regular Expressions (Regex)
- Searching
- Secure Shell Connection in Python
- Security and Cryptography
- Set
- setup.py
- shelve
- Similarities in syntax, Differences in meaning: Python vs. JavaScript
- Simple Mathematical Operators
- Sockets
- Sockets And Message Encryption/Decryption Between Client and Server
- Sorting, Minimum and Maximum
- Sqlite3 Module
- Stack
- String Formatting
- String Methods
- String representations of class instances: __str__ and __repr__ methods
- Subprocess Library
- sys
- tempfile NamedTemporaryFile
- Templates in python
- The __name__ special variable
- The base64 Module
- The dis module
- The Interpreter (Command Line Console)
- The locale Module
- The os Module
- The pass statement
- The Print Function
- tkinter
- Tuple
- Turtle Graphics
- Type Hints
- Unicode
- Unicode and bytes
- Unit Testing
- Unzipping Files
- urllib
- Usage of "pip" module: PyPI Package Manager
- User-Defined Methods
- Using loops within functions
- Variable Scope and Binding
- virtual environment with virtualenvwrapper
- Virtual environments
- Web scraping with Python
- Web Server Gateway Interface (WSGI)
- Webbrowser Module
- Websockets
- Working around the Global Interpreter Lock (GIL)
- Working with ZIP archives
- Writing extensions
- Writing to CSV from String or List
Python Language Functions
Introduction
Functions in Python provide organized, reusable and modular code to perform a set of specific actions. Functions simplify the coding process, prevent redundant logic, and make the code easier to follow. This topic describes the declaration and utilization of functions in Python.
Python has many built-in functions like print(), input(), len(). Besides built-ins you can also create your own functions to do more specific jobs—these are called user-defined functions.
Syntax
- def function_name(arg1, ... argN, *args, kw1, kw2=default, ..., **kwargs): statements
- lambda arg1, ... argN, *args, kw1, kw2=default, ..., **kwargs: expression
Parameters
| Parameter | Details |
|---|---|
| arg1, ..., argN | Regular arguments |
| *args | Unnamed positional arguments |
| kw1, ..., kwN | Keyword-only arguments |
| **kwargs | The rest of keyword arguments |
Remarks
5 basic things you can do with functions:
-
Assign functions to variables
def f(): print(20) y = f y() # Output: 20 -
Define functions within other functions (Nested functions )
def f(a, b, y): def inner_add(a, b): # inner_add is hidden from outer code return a + b return inner_add(a, b)**y -
Functions can return other functions
def f(y): def nth_power(x): return x ** y return nth_power # returns a function squareOf = f(2) # function that returns the square of a number cubeOf = f(3) # function that returns the cube of a number squareOf(3) # Output: 9 cubeOf(2) # Output: 8 -
Functions can be passed as parameters to other functions
def a(x, y): print(x, y) def b(fun, str): # b has two arguments: a function and a string fun('Hello', str) b(a, 'Sophia') # Output: Hello Sophia -
Inner functions have access to the enclosing scope (Closure )
def outer_fun(name): def inner_fun(): # the variable name is available to the inner function return "Hello "+ name + "!" return inner_fun greet = outer_fun("Sophia") print(greet()) # Output: Hello Sophia!
Additional resources
- More on functions and decorators: https://www.thecodeship.com/patterns/guide-to-python-function-decorators/
Functions Related Examples
- Defining and calling simple functions
- Argument passing and mutability
- Closure
- Defining a function with an arbitrary number of arguments
- Defining a function with arguments
- Defining a function with multiple arguments
- Defining a function with optional arguments
- Defining a function with optional mutable arguments
- Forcing the use of named parameters
- Iterable and dictionary unpacking
- Lambda (Inline/Anonymous) Functions
- Nested functions
- Recursion limit
- Recursive functions
- Recursive Lambda using assigned variable
- Returning values from functions
Got any Python Language Question?
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0
This website is not affiliated with Stack Overflow
SUPPORT & PARTNERS