In a nutshell — Python is an interpreted, interactive, object-oriented, general-purpose programming language.
Design philosophy & Features
- The Python language's core philosophy is summarized in PEP 20, titled "The Zen of Python".
- Python is a multi-paradigm programming language where Object-oriented programming, procedural programming and functional programming are fully supported. Many of Python's features support aspect-oriented programming, including metaprogramming and metaobjects (also called magic methods). Many other paradigms like design by contract and logic programming are also supported via extensions.
- Python's extensive standard library is commonly cited as one of its greatest strengths and provides tools suited to many tasks. Rather than having all of this functionality built into its core, Python was designed to be highly extensible with modules.
- Python features dynamic name resolution during runtime.
- Python is a strongly-typed language, meaning you can't perform operations inappropriate to the type of the object (e.g. adding numbers to strings). Python is also a dynamically-typed language, meaning a variable is simply a value bound to a name with no associated data type.
- Python uses duck typing, a concept related to dynamic typing — Python don't check types, it checks for the presence of a given method or attribute.
- Since Python 3.5, type annotations can be used for possible static analysis, refactoring, runtime type checking and code generation. An optional static type checker named mypy supports compile-time type checking.
- Python allows you to assign a value to a variable without first declaring it, but it will not let you reference a variable that has never been assigned a value.
- Python doesn't support tail call optimization and first-class continuations. However, Python has better support for coroutine-like functionality by extending Python's generator functions.
- Python developers should strive to avoid premature optimization since it can reduce readability and add code that only exists to improve performance. This may complicate programs, making them harder to maintain and debug. When speed is important, you can move time-critical functions to extension modules written in languages such as C/C++. You can also use PyPy or Cython.
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. — Donald Knuth
Statements & Control flow
- Python uses a carriage return to separate statements.
- Code blocks are defined by their indentation. Python use whitespace indentation, there are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. Four spaces are the preferred indentation method, avoid using tabs.
- Python uses
ifalong withelseandelif(a contraction of else-if) statements for conditional execution of a code block. - Since Python 3.10, the
matchandcasestatements can be used for pattern matching. Thematchstatement is similar to the switch statement of other languages. - Python uses the
forstatement to iterate over an iterable object and thewhilestatement to execute a code block as long as its condition is true. - Python uses the
breakstatement to exit the loop containing it, after which the program flow continues immediately after the loop body. - The
continuestatement, skips this iteration and continues with the next statement. - A function or method can be defined with the
defstatement. - Python defines a class with the
classstatement. - A colon
:is used to start a code block in the case ofif,elif,while,for,def, andclassstatements. It is also used to fetch data and index ranges, slicing, and to identify keys in dictionaries. - All names in Python are case-sensitive: i.e. names of variables, functions, classes, modules, and exceptions.
- The
delstatement is used to delete variables and objects from existence. - In Python, the
passstatement serves as a NULL statement. The interpreter parses it to a NOP instruction, meaning no operation in machine language. It is syntactically needed to create an empty code block. - Python uses
try...exceptcode blocks to handle exceptions, andraisestatements to generate them. - In Python, the
assertstatement can be used during debugging to check conditions that should always be true. If the condition is not satisfied, the program stop and gives anAssertionErroralong with an optional message. - The
returnstatement is used to return a value from functions. - The
yieldstatement returns a value from generator functions. - Python uses these
=,+=,-=,*=,/=,%=,//=,**=assignment operators. In Python assignment is a statement and not an expression. Consequently, Python does not support in-line assignment. - Python features sequence unpacking which means to assign elements of an iterable object into multiple variables, it's written as
as many variables as elements in sequence = sequence. - The
importstatement is used to import modules. Importing a python module, runs all of its contents. Use anif __name__ == "__main__":code block to allow or prevent parts of code from being run when modules are imported.
Built-in types
- Python's native types are numbers, sequences, classes, instances and exceptions.
| Type | Mutability | Description | Example |
|---|---|---|---|
bool |
immutable | boolean value |
True or False
|
int |
immutable | integer value | 2 |
float |
immutable | double-precision floating-point value | 3.14159 |
complex |
immutable | complex number with real and imaginary parts | 1+2j |
str |
immutable | sequence of Unicode characters | 'Python' |
bytes |
immutable | sequence of bytes | b'Python' |
bytearray |
mutable | sequence of bytes | bytearray(b'Python') |
list |
mutable | ordered sequence of values | [3, True, 'Python'] |
tuple |
immutable | ordered sequence of values | ('Python', 5, False) |
dict |
mutable | associative array of key and value pairs | {'name': 'Adam', 7: 'apple'} |
set |
mutable | unordered sequence of values with no duplicates | {True, 11, 'Python'} |
The table list the most commonly used types, but there are more types.
Expressions
- Python follows mathematical rules of precedence for mathematical operations: parentheses, exponentiation, multiplication & division, addition & subtraction, and operators with the same precedence are evaluated from left to right.
- Python uses the
+,-,*,%,**arithmetic operators. There are two types of division in Python called floor division (or integer division)//and floating-point division/. - Python uses the
==,>,<,!=,>=,<=comparison operators. Comparisons may even be chained (e.g.a <= b <= c). - Since Python 3.8, the walrus operator
:=can be used to assign values to variables as part of an expression. - Python uses the words
and,or,notfor Boolean (or logic) operators instead of the symbolic equivalent&&,||and!. - Python uses the
isandis notidentity operators to check if two values refer to the same object or not. - Python uses the
inandnot inmembership operators to test whether or not a sequence contains a value. Theinkeyword is also used to iterate through a sequence in aforloop. - Python makes a distinction between lists (mutable) written as
[2, 3, 5]and tuples (immutable) written as(7, 11, 13). - In Python strings can be concatenated by adding them, using the arithmetic operator for addition.
-
Anonymous functions are implemented using lambda expressions that is written as
lambda [parameters]: expression. - In Python, a List comprehension is written as
[expression for item in list]. List comprehensions are a more elegant and concise way to create lists. It can also be used when working with strings or tuples. - A Python generator expression is written as
(expression for item in list). These anonymous generator functions create a single element on request, and therefore more memory efficient than an equivalent list comprehension. -
Conditional expressions are written as
X if condition else Y. Theconditionis evaluated first. IfconditionisTrue,Xis evaluated and its value is returned, and ifconditionisFalse,Yis evaluated and its value is returned.
Uses
- Python can serve as a scripting language for automation.
- Python is often used for web development and web applications.
- Python competes against Fortran and C/C++ in scientific computing and data science.
- Python is commonly used in data analysis, artificial intelligence and machine learning.
- Python is often used in natural language processing.
- Python can be used in game development.
- Python is embedded in many software products as a scripting language.
- Many operating systems include Python as a standard component.
- Python is used extensively in information security and exploit development.
Top comments (0)