Python Language

From NovaOrdis Knowledge Base
Jump to: navigation, search

Internal

TODO

  • Variable scope.

Overview

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
def return
and or not
is
class from nonlocal
del global
as yield with
assert import pass lambda
raise finally

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.

Variables

Variables are memory locations used to store values, and have labels associated to them , the variable name. 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).

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

Variable Scope

TODO

Literals

Literals have a type.

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 can be used with the is or is not operators:

if x is 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

Single or double quotes sequence of characters.

x = 'abc'
type(x)
<class 'str'>

Strings can be concatenated with the + operator:

'a' + 'b'

To concatenate strings and numbers, use type conversion function str():

'a' + str(1)

List

Dictionary

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

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

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

Python Script

A Python program file is called a Python script - a stored set of instructions that can be handed over to the Python interpreter. Python scripts have the .py extensions.

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 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

try/except

try/except is a language-level mechanism to handle errors (traceback) that may be caused by a section of the code. This syntax eliminates tracebacks.

try:
  # do something
except:
  # execute if the previous block caused an error

Data Structures

Classes

Traceback

This means Python quit somewhere.

Organizatorium

Nesting