Python Language: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 173: Line 173:
==Type Conversions==
==Type Conversions==
There are built-in function that can be used for type conversion:
There are built-in function that can be used for type conversion:
* <code>float()</code>
===<tt>float()</tt>===
* <code>int()</code>. <code>int()</code> can be called on a boolean, float or on a string. For a boolean, <code>int(True)</code> will return 1 and <code>int(False)</code> will return 0.
===<tt>int()</tt>===
* <code>str()</code>
<code>int()</code> can be called on a boolean, float or on a string. For a boolean, <code>int(True)</code> will return 1 and <code>int(False)</code> will return 0.
 
If the string <code>int()</code> is invoked on cannot be converted to an integer, the function invocation throws a <code>ValueException</code>.
===<tt>str()</tt>===


=Data Structures=
=Data Structures=

Revision as of 05:06, 18 June 2022

External

Internal

TODO

  • Variable scope.

Overview

Python is a general-purpose, high-level, dynamic language. Its design makes it very readable. Its relative tenseness makes it possible to write a program that is much smaller than the equivalent static language program. However, if the program is CPU-bound, a program written in C, C++ or Java will generally run faster than its Python equivalent.

Python programs can be executed in two modes: interactively via an interpreter, also called a shell, or stored into a file with the usual, but optional .py extension and run by typing python followed by the file name.

In Python, everything is an object. This includes numbers, strings, tuples, lists, dictionaries, functions and programs. The definition of an object is called class.

Printing done with print() function in Python 3 (it uses to be a statement in Python 2).

print('something')

In Python, spacing does matter, sequential blocks are indented at the same level, and they are known as indented blocks. Also see:

Printing to stdout in Python

Comments

# This is a comment

Reserved Words

Reserved words, or keywords, can only be used to mean the thing Python expects them to mean. They cannot be used as variable names, function names, class names, or identifiers.

False True None
if else elif
while for break continue in
try except finally raise assert
def return lambda
import from
pass
is
and or not
del
class
nonlocal global as yield with

Constants

Constants are fixed values, they do not change throughout the program. Constants can be boolean (True, False), numeric (integers or floating point numbers), or strings, which can be single quoted or double quoted, or even "the absence of a value" (None). Constants can be assigned to variables, can be arguments of functions. Constants have a type.

Constant Variable

Python does not have anything equivalent to final in Java, so any variable can be modified after assignment. You can use:

CONST_NAME = "Name"

for clarity, but nothing prevents CONST_NAME to be assigned other value later in the program.

Single Quoted, Double Quoted, Triple Single Quoted, Triple Double Quoted

TODO

Multi-Line Strings

TODO, see Python Language Functions#Docstring

Triple Double-Quoted Strings

Triple double-quoted strings is the recommended style for docstrings.

s = """
This is a
  multi-line
  string
"""

Variables

Variables are names associated with memory locations used to store values. Variables are declared and assigned a value though an assignment statement. The assignment does not copy a value, it just attaches a name to the object that contains the data. A variable may be associated with an object that has a type, and the same variable may be assigned later an object of a different type. A useful mental representation of a variable is a sticky note that can be attached to an object, and then re-attached to a different object, not necessarily of the same type.

a = 1
b = 'something'
print(a)
print(b)
a = 'something else'
print(a)

Variable Naming Rules

Variable names are case sensitive. Variable names can start with letters or underscore ('_') - but underscores should be generally avoided because Python treats names that begin with an underscore in special ways, and tends to use them for its internal purposes. The rest of the variable name can be lowercase letters (a through z), uppercase letters (A through Z), digits (0 through 9) and underscores. No other characters are allowed. Python has a set of words, called reserved words, that cannot be used as variable names. Variable names should be sensible (mnemonic). Function name follow the same rules.

Variables declared in functions should be lowercase. For more details see:

Python Style Guide

Variable Scope

TODO

Global Variable

Variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside. If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Literals

Literals have a type.

Literal Integers

F-String

F-String

Identifiers

Type

Everything in Python is implemented as an object, and any object has a type. The type determines whether the data value of the object is mutable or immutable (constant). Python is strongly typed, which means that the type of an object does not change, even if the value is mutable.

The type of an object can be obtained with the built-in function type() applied to the variable or a constant the object is assigned to. In Python, "class" and "type" mean pretty much the same thing.

Data Types

None

x = None
type(x)
<class 'NoneType'>

None is a special Python value that holds a place when there is nothing to say. It is not the same as False, although it looks false when it is evaluated as a boolean. None can be used with the is or is not operators:

if x is None:
  ...
if x is not None:
  ...

None is returned by a function that does not contain the return statement. None is useful to distinguish a missing value from an empty value. Zero-value integers or floats, empty strings (''), empty lists [], empty tuples (,), dictionaries {} and sets set() are all False but are not equal to None.

Booleans

Python Boolean

Numbers

Integers

Python Integers

Floating Point Numbers

Numbers with a decimal point.

x = 98.6
type(x)
<class 'float'>

String

String

Sequence Types

There are two kinds of sequence types: tuples and lists. Both contain zero or more elements, in both cases elements can be of different types. Tuples are immutable. Lists are mutable. Mutability matters when the objects are stored in sets or as dictionary keys, because the collections are hashed in that case. If hashing a collection is not a concern, the rule of thumb is that fixed-size records of different objects are best represented as tuples, while variable-size collections of similar objects are best represented as lists.

List

List

Tuple

Tuple

Dictionary

Dictionary

Set

Set

Function

Functions

Type Conversions

There are built-in function that can be used for type conversion:

float()

int()

int() can be called on a boolean, float or on a string. For a boolean, int(True) will return 1 and int(False) will return 0.

If the string int() is invoked on cannot be converted to an integer, the function invocation throws a ValueException.

str()

Data Structures

A Python data structure is, for example, what you get when you parse a JSON-serialized text and you recreate the lists and the maps in memory.

Collections

Organizatorium: Python Module collections

Iterable Types

Iterable types: list, tuple, set.

Iterator

https://docs.python.org/3/glossary.html#term-iterator

Comprehensions

A comprehension is a compact way of creating a data structure from one or more iterators.

List Comprehensions

Statements

In Python 2, print used to be a statement, while in Python 3, print() is a function.

Assignment Statement

The assignment statement assigns a value to a variable. The assignment does not copy the value, it just attaches the variable name to the object that contains the data.

x = 1

The assignment statement accepts expressions:

x = x + 1

Statement that Does Nothing

pass is a statement that indicates a function does nothing:

def do_nothing():
  pass

Expressions

Numeric expressions. Order of evaluation takes into account operator precedence.

Operators

+ Addition For numbers, adds them together, for strings, it concatenates. + can be combined with the assignment operator: +=
- Subtraction - can be combined with the assignment operator: -=
* Multiplication * can be combined with the assignment operator: *=
/ Floating Point Division In Python 3 integer division converts to floating point (not the case in Python 2, which truncates). / can be combined with the assignment operator: /=
// Integer (truncating) Division
** Power (exponentiation)
% Remainder (modulo)
= Assignment Expression on the right side of = is calculated first, then assigned to the variable on the left side. See Assignment Statement.
< Less than
<= Less than or Equal to
== Equal to Applies to strings, also. It is the mathematical equality. Also see is, is not.
>= Greater than or Equal to
> Greater than
!= Not equal
is "is the same as" Returns a True or a False. Can be used in logical expression, implies "is the same as". It is similar but a stronger equality than "==". You should not use "is" when you should be using "==". "is" usually applies to True, False or None
is not "is not the same as" Returns a True or a False

Boolean (Logical) Operators

and

or

not

Ternary Operator

https://book.pythontips.com/en/latest/ternary_operators.html
value_if_true if condition else value_if_false

Operator Precedence

The following rules apply, and they are specified in the order of their descending precedence:

  • Parentheses are always respected.
  • Exponentiation.
  • Multiplication, division and remainder.
  • Addition and subtraction.
  • For operators with the same precedence, proceed left to right.

Control Flow

We can solve problems in a way far more easily with clever data structures than with clever control flow. Control flow is obvious and data structures are subtle. So by making clever data structures, your control flow is simplified Dr. Charles Severance.

Sequential Steps

Sequential steps have the same indentation level. A block with the same indentation level (recommended 4 spaces) designates a set of steps that execute sequentially.

Conditional Steps

if expression:
  ...

if x < 10:
  print('something')
if a == 1:
  print('something')
else:
  print('something else')

In the following case, once one of the alternative is triggered, the corresponding block is the only one that is executed, and the control gets out of the if statement. else is optional.

if a < 0:
  print('m')
elif a < 10:
  print('n')
elif a < 20:
  print('p')
else:
  print('q')

Loops and Iterations

Indefinite Loops

while

while <condition>:
  code-block
n = 5
while n > 0:
  print(n)
  n = n - 1
while x < 5:
  x = x + 1
  print

Loops have iteration variables, which are initialized, checked and changed within the loop. If the iteration variable that matters does not change within the loop, the loop will run forever - an infinite loop.

for i in range(5):
  print(i)

Definite Loops

for

for var_name in <collection>:
  code-block
for i in [1, 2, 3, 4, 5]:
  print(i)
collection = ['a', 'b', 'c']
for i in collection:
    print(i)

A for loop is finite, it goes through all elements of a collection: all the lines in a file, all the items in a list, all the characters in a string, etc.

As part of the for syntax, the iteration variable follows the reserved word for, which is followed by the reserved word in, which is then followed by a collection, which can be declared in-line or using a previously declared variable. The iteration variable iterates through the sequence (ordered set) and takes, in order, each value in the sequence. The statements to be executed in the loop are part of an indented block. The body is executed once for each value in the sequence.

Other Loop Statements

break

break is a reserved word that indicates a statement which breaks out of the loop. When encountered, the execution goes to the first statement after the loop.

continue

continue is a reserved word that indicates a statement which skips the current iteration and starts the next iteration. The control goes to the top of the loop.

Loop Idioms

enumerate()

The enumerate() function gives access to the elements of the list and their index at the same time.

l = ['a', 'b', 'c']
for i, e in enumerate(l):
    print(f'index: {i}, element: {e}')

Adding a Comma after All but Last Element

l = ['a', 'b', 'c']
s = ''
for i, e in enumerate(l):
    s += e
    if i < len(l) - 1:
        s += ', '

assert 'a, b, c' == s

reversed()

Iterate over a list in reverse order.

l = ['a', 'b', 'c']
for i in reversed(l):
  ...

Functions

Functions

Exceptions (try/except)

Exceptions

Traceback

This means Python quit somewhere.

Modularization

Discusses standalone programs, scripts, modules, packages, importing, package metadata, Python Standard Library, PyPI:

Modularization

Object-Oriented Programming

Classes and Objects

Virtual Environment

A virtual environment is a mechanism to isolate a set of installed dependencies. Virtual environments can be managed with virtualenv, venv, etc. A virtual environment can be created manually as follows:

python3 -m venv venv
venv/bin/pip install -r requirements.txt

To upgrade pip within an already initialized virtual environment:

venv/bin/python3 -m pip install --upgrade pip

The dependencies installed in a virtual environment are used automatically if the interpreter is ./venv/bin/python.

Also see pip and requirements.txt.

It is a good practice to avoid storing the content of venv or equivalent in source control. The content is populated locally on the developers' machines.

Activated Virtual Environment Shell

TODO.

Python Enhancement Proposals (PEPs)

Code Examples

Python Code Examples

Organizatorium

  • Nesting
  • __name__ (if __name__ == "__main__"): ...