Syntax#
Syntax is set of rules that define the structure and format of valid statements and expressions in a programming language. It dictates how symbols, keywords, and operators must be arranged to create meaningful instructions for the computer.
Operators#
Operators are used to perform operations on objects. Below is a list of operators in Python:
Category |
Operator |
Description |
---|---|---|
Arithmetic |
|
Addition |
|
Subtraction |
|
|
Multiplication |
|
|
Division |
|
|
Modulus |
|
|
Exponentiation |
|
|
Floor Division |
|
Comparison |
|
Equal to |
|
Not equal to |
|
|
Greater than |
|
|
Less than |
|
|
Greater than or equal to |
|
|
Less than or equal to |
|
Assignment |
|
Assign |
|
Add and assign |
|
|
Subtract and assign |
|
|
Multiply and assign |
|
|
Divide and assign |
|
|
Modulus and assign |
|
|
Exponentiate and assign |
|
|
Floor divide and assign |
|
Logical |
|
Logical AND |
|
Logical OR |
|
|
Logical NOT |
|
Bitwise |
|
Bitwise AND |
` |
` |
|
|
Bitwise XOR |
|
|
Bitwise NOT |
|
|
Left shift |
|
|
Right shift |
|
Membership |
|
Membership test |
|
Non-membership test |
|
Identity |
|
Identity test |
|
Negated identity test |
|
Conditional |
|
Conditional expression |
For a more detailed description of each operator, refer to the specific page.
Keywords#
A keyword is a special word used by Python as part of the language syntax. You can list all the valid keywords by using the kwlist
attribute of the keyword
module.
import keyword
keyword.kwlist
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
Here is table with brief description to each keyword.
Keyword |
Description |
---|---|
False |
Represents the boolean value False. |
None |
Represents the absence of a value or a null value. |
True |
Represents the boolean value True. |
and |
Logical AND operator. Returns True if both operands are true. |
as |
Used to create an alias while importing a module or in exception handling. |
assert |
Used for debugging purposes to test if a condition is true. |
async |
Declares an asynchronous function or method. |
await |
Pauses the execution of an async function until the result is available. |
break |
Exits a loop prematurely. |
class |
Used to define a new class. |
continue |
Skips the rest of the code inside a loop for the current iteration and proceeds to the next iteration. |
def |
Used to define a function. |
del |
Deletes objects. |
elif |
Used in conditional statements, stands for “else if”. |
else |
Used in conditional statements, provides an alternative block of code if conditions are not met. |
except |
Used in exception handling to catch exceptions. |
finally |
Used in exception handling to execute code regardless of whether an exception was raised or not. |
for |
Used to create a for loop for iterating over sequences. |
from |
Used to import specific parts of a module. |
global |
Declares a variable to be global. |
if |
Used to start a conditional statement. |
import |
Used to include modules into the current namespace. |
in |
Checks for membership in a sequence or container. |
is |
Tests for object identity, checking if two variables point to the same object. |
lambda |
Creates an anonymous function. |
nonlocal |
Used to declare a variable that refers to a variable in an enclosing scope, but not global. |
not |
Logical NOT operator. Returns True if the operand is false. |
or |
Logical OR operator. Returns True if at least one operand is true. |
pass |
A null statement used as a placeholder. |
raise |
Used to raise exceptions. |
return |
Exits a function and optionally returns a value. |
try |
Starts a block of code to be tested for exceptions. |
while |
Starts a while loop that continues as long as the condition is true. |
with |
Used to simplify exception handling by encapsulating setup and cleanup code. |
yield |
Used to produce a generator in a function. |
Check more details in the special page.
Exceptions#
The separate section is for cases of using try/except
operators. With try you can create block that’ll monitor specific types of errors and transfer control to the execpt unit if necessary. For more details check specific page.
The following code wraps the 10/0
command, which would normally lead to an error, inside a try
block. The except ZeroDivisionError
block is used to define the code that will be executed if the error occurs.
try:
10/0
except ZeroDivisionError:
print("I'm an exception")
I'm an exception
With#
Python allows you to define a context in which certain objects are accessible and specific setup and cleanup operations are automatically performed before and after the context is executed.
For more information, see:
The
with
statement section on the “Compound statements” page of the official documentation.With Statement Context Managers section on the “Data model” page.
The typical syntax for the with
statement is:
with EXPRESSION as TARGET:
SUITE
Here:
EXPRESSION
is a call that returns a context manager.TARGET
is the object created by the context manager to interact with the context.SUITE
is the block of code that will be executed within the context.
The most common use of the with
statement is probably in conjunction with the open
function. In this case, the target would be an object representing a file, which will definitely be closed at the end of the context.
The following cell demonstrates opening and closing a file without the with
statement.
file = open("/tmp/some_file", "wb")
print(type(file))
print(file.closed)
file.close()
print(file.closed)
<class '_io.BufferedWriter'>
False
True
Special attention is given to the type of object that the open
function returns. Also, attention is given to the state of the closed
attribute of the file before and after the call to file.close
.
The same idea, but using with
statement.
with open("/tmp/some_file", "wb") as file:
print(type(file))
print(file.closed)
print(file.closed)
<class '_io.BufferedWriter'>
False
True
The target has the same type as the one returned by open
in regular conditions. The values of the file.closed
attribute inside and outside the with
statement show that the file is opened in the context created by the with
statement and closed immediately after the context ends.
Several managers#
You can use multiple managers in one with
statement. Simply separate all expressions produsing context managers with commas:
with (
expression1 as target1,
expression2 as target2
):
pass
For me, the typical usage of the described approach for me was the mocking with the unittest
package. It’s common to alter the behavior of the several functions called in the code being tested.
The following cell shows the case with fun1
and fun2
, whose behavior in the consider
is changed due to the with
statement containing several context managers.
from unittest.mock import patch
def fun1() -> str:
return "fun1 original"
def fun2() -> str:
return "fun2 original"
def consider() -> str:
return fun1() + " and " + fun2()
with (
patch('__main__.fun1') as mock_fun1,
patch('__main__.fun2') as mock_fun2
):
mock_fun1.return_value = "modified fun1"
mock_fun2.return_value = "modified fun2"
print(consider())
modified fun1 and modified fun2
Decorators#
It’s a sugar that allows to modify behaviour of the functions or classes. Find out more in the specific page.
The following cell defines a decorator, which is a function that takes another function as an argument and returns a modified version of that function. During the creation of the new function, it prints Functionality during function modification.
Additionally, it prints Functionality to be added.
each time the modified function is called.
def wrapper_function(modified_function):
print("Functionality during function modification.")
def inner_function():
print("Functionality to be added.")
modified_function()
return inner_function
The standard way to apply a decorator to a function is by using the @
operator. In the following cell, the wrapper_function
decorator, which was created earlier, is applied to the function_to_decorate
function.
@wrapper_function
def function_to_decoration():
print("Original functionality")
Functionality during function modification.
You can realise some logic during decorator creation. So Functionality during function modification.
was printed.
The following cell calls decorated function.
function_to_decoration()
Functionality to be added.
Original functionality
In addition to the function’s original functionality, the decorator adds extra behavior.