Python Language: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 105: Line 105:
Literals have a [[#Type|type]].
Literals have a [[#Type|type]].
==F-String==
==F-String==
{{External|[https://www.python.org/dev/peps/pep-0498/ PEP 498]}}
{{Internal|Python_Language_String#F-String|F-String}}
An f-string is a literal string, prefixed with "f", which contains expressions inside branches. The expressions are replaced with their values. Introduced by [https://www.python.org/dev/peps/pep-0498/ PEP 498]. Any kind of string (single-quote enclosed, double-quote enclosed and triple-quote enclosed) can be an f-string.
 
<syntaxhighlight lang='python'>
name = "long"
print(f'my name is {name}')
print(f"my name is {name}")
print(f"""
 
  my name is {name}
 
""")
</syntaxhighlight>
 
<font color=darkkhaki>
Indent to the right over 6 spaces:
<syntaxhighlight lang='python'>
i = 10
print(f"{i:>6}")
</syntaxhighlight>
</font>


=Type=
=Type=

Revision as of 22:52, 6 March 2022

External

Internal

TODO

  • Variable scope.

Overview

In Python, everything is an object. This includes numbers, strings, tuples, lists, dictionaries and functions.

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.

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 to other value.

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 memory locations used to store values. The variable name is a label associated with a variable. Variables are declared and assigned a value though an assignment statement. Variables have a type.

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

Variable Naming Rules

Variable names are case sensitive. Variable names can start with letters or underscore ('_') - but underscores should be generally avoided because Python tends to use underscores for its internal purposes. The rest of the variable name can be letters, numbers and underscores. No other characters are allowed. 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.

F-String

F-String

Type

The type of a variable or a constant can be obtained with the built-in function type()

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

x = True
type(x)
<class 'bool'>

Integers

Whole numbers, expressed as numeric constants that do not contain a decimal point.

x = -20
type(x)
<class 'int'>

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

Function

Functions

Type Conversions

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

  • float()
  • int(). int() can be called on a float or on a string.
  • str()

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.

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.
- Subtraction
* Multiplication
/ Division In Python 3 integer division converts to floating point (not the case in Python 2, which truncates).
** Power (exponentiation)
% Remainder (modulo)
= Assignment
< 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

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.

Identifiers

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

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

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

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__"): ...