Valdemar W. Setzer
www.ime.usp.br/~vwsetzer (section
Educational resources)
Version 2.13 12/31/2024. Partial automatic translation from the original
in Portuguese: Eduardo Furlan; revision: V.W. Setzer
Concerning types of variables, Python is considered a dynamic and strongly
typed language: 1. Strongly Typed: Python does not allow implicit
operations between different types without explicit conversion. For example,
adding a string to a number, such as A+G (see values attributed in last section,
subsection 4), will generate an error unless the string is explicitly converted
to a number. Thus, addding a string of characters (see below) to a number will
gerate an error, unless the string is converted into a number through a type
conversion function. But numbers of different types are allowed, such as A+D.
Dynamically Typed: The type of a variable is determined at runtime and
can change as new values are assigned to it, meaning that a variable x adopts
the type of the value assigned to it. For example, when executing the assignment
satement x = 1, x will be of type integer. If the assignment x = 1.5 is then
executed, x will become of type floating point.
Variables function as references (or pointers) to objects. When a value is assigned
to a variable, it does not directly store the value, but rather a reference
to the object that contains the value.
2.2 Numeric types
Integer (int): precisão ilimitada.
E.g.: 1234567890123456789012345
Constants. Bynary. Ex.: 0b101 or 0B101 (decimal value 5); octal:
0o127 or 0O127 (87); hexadecimal: 0xA5B or oXA5B (2651). Hexadecimal
constants are commonly used to represent binary numbers in an easier-to-read
notation.
Floating point: usually implemented using the double type in the C language.
E.g.: .12345678901234567890 → 0.12345678901234568
(note the rounding off).
Complexo: contém uma parte real, e uma imaginária indicada
por um j. Exs.: constante (1+2j) ou (1+2J); variável (A+D*1j)
Complex: contains a real part and an imaginary part indicated by a j.
E.g.: constant (1+2j) or (1+2J); variable (A+D*1j)
To convert any type to integer use the functions int(), to floating point float(),
to complex complex(). These functions should be used especially in data input,
input() which always gives a string type (str).
The NumPy module (see references), which must be installed, allows for the use
of a wide variety of numeric types. To define a 32-bit floating point variable,
simply give, for example,
x = numpy.float32(1.0)
Example: 'tuv5xyz: ' → 'tuv5xyz:
'; "tuv5xyz: " → 'tuv5xyz: '; 'tuv5x"yz: ' → 'tuv5x"yz:
'; If the command STR = 'This is a string' is executed, then STR → 'This
is a string'
Empty string: '' (two apostrophes) or " " or ""
"" → (one blank space).
Indexing: the 1st index indicates the initial element, starting
at 0; the 2nd the final one, starting at 1. For the STR string above, STR[0]
→ 'T'; STR[5:9] → 'is a']; STR[5:] → 'is a string'. To address
the last elements of the list, use negative numbers: STR[-1] → g; STR[-3]
→ i
Locating a list elemet: string elements
are separated by spaces x = STR.index('is'); x → 2
Concatenation of strings: 'tuv5xyz: ' + STR → tuv5xyz: This
is a string; 2*STR → This is a stringThis is a string
Example: Tup = (A, 5, 3.14, 'blah');
Tup → (1, 5, 3.14, 'blah'). `For the value of A, see section 3 of the notes.)
Empty tuple: ()
Indexing: Tup[0] → 1;
Tup[1:3] → (5, 3.14); Tup[2:] → (3.14, 'blah'); 2*Tup → (1, 5,
3.14, 'blah', 1, 5, 3.14, 'blah').
Assigning a value to an element of a tuple is not valid:: Tup[1] = 10
Locating a tuple element and tuple concatenation:
as in 2.3
Example: L = [A, 5, 1.2, 'blah']
Empty list: []
Indexing: L[2] → 1.2; L[1:4] → [5, 1.2, 'blah']. Note
that indices of elements range from 0 to, say, n. L[i:j] indicates the
elements starting at the element with index i and ending at the element with
index j1. L[5] → gives an error because there is no element with
index 5. L[4] = 9 → gives the same error. Adding one more element (always
at the end of the list): L = L + [9]; L → [1, 5, 1.2, 'bla', 9]; L = L
+ [] does not change L.
Assignment to an element: the following is valid: L[3]=10; L →
[1, 5, 1.2, 10].
Deleting an element from a list: use the statement del.
E.g. del L[2]; L → [1, 5, 10];
Locating a list element and list concatenation:
as in 2.3
Example: Dic = {5:10, 3:'blah',
'bleh':'A', 'A':'8'}; Dic →{5: 10, 3: 'blah', 'bleh': 'A', 'A': 8}
Note that each element of a dictionary is of the form x:y, where x is the index
and y is the value associated with that index. Indexes or values that
are alphabetic must be enclosed in apostrophes or quotation marks.
Indexing: Dic[5] → 10; Dic[3] → blah; Dic['bleh'] →
A; Dic[3] → 'blah'; DIC['A'] → 8
Getting all indices (keys): Dic.keys() → dict_keys([5, 3,
'bleh', 'A'])
Getting all values: Dic.values() → dict_values(10, 'blah',
'A', '8'])
dict_keys and dict_values cannot be indexed. To work with all indices or values,
one may transform them into lists and then work with them {MDG}:
L = [x for x in Dic.keys()]; L → [5, 3, 'bleh',
1]
L = [x for x in Dic.values()]; L → [10, 'blah',
A, 8]
Example S = {1, 'two', 3, 'four'};
S → {3 , 1, 'two', 'four'} (it seems that printed order is arbitrary)
Sets are unordered, cannot be indexed, and the system eliminates duplicates.
E.g. print({1, 2, 1, 3} → {1, 2, 3}
Empty set: {}
Usage. Number of elements (cardinality): len(S)
→ 4. Membership: 'two' in S → True. Union: S
| {5} → {1, 3, 5, 'four', 'two'} (apparently in alphabetic order). Intersection:
S & {1, 'two'} → {1, 'two'}. Complementation: S {1, 'two'}
→ {3, 'four'}. Tests for proper superset: S > {1, 'four'} →
True. Superset: >=; Proper subset: <. Subset: <=.
Exclusive union (eliminates common elements): S ^ {'two', 5} → {1,
3, 5, 'four'}
There are two types of sets: set, in which its elements can be changed,
and frozenset, which cannot be changed. The construction of a set is
automatic. Ex.: x = frozenset(({1, 2}); x.pop() → error. Declared subsets
of sets must be of type frozenset. The values True and 1 are considered
the same value in sets, and are treated as duplicate.
Specification: range(m,
n, k), with optional n and k or optional k only,
generating the integers of a list r such that r[i] = m
+ k*i, where i >= 0 and i < abs(n)
Examples: list(range(5)) → [0, 1, 2, 3, 4]; list(range(0, 8, 2)) →
[0, 2, 4, 6]; list(range(-1, -10, -2)) → [-1, -3, -5, -7, -9]
Usage in for statements: see the statements in section 13 below and in
2.5 above.
Unlike almost all other programming languages, Python does not have an array
type, since variable values can be of different sizes. Arrays are represented
by lists, since they can be indexed as if they were arrays. In other languages,
declaring an array produces the initialization of its values, that is, declaring
the array causes all its elements to exist. However, this does not happen with
Python lists; therefore, each new element must be added in the proper ordering.
The NumPy module allows the use of vectors and
arrays as in traditional languages. Assuming it is installed, to activate it
and give it the internal name of np, give
import NumPy as np. See the references for details on how to use it.
Examples
1. To define a vector of 5 elements, initializing with 0 values (it could be
any other value, such as the value of I or an expression): V=[I for I in range(4)];
V → [0, 1, 2, 3]; note that V[4] does not exist and cannot receive a value,
such as V[4]=5. To define it: V=V+[5]. To scan an entire vector of variable
size, use len(V) → 4. Note that indeces of a list begin at value 0.
2. To define a two-dimensional array (a matrix), construct a list of sublists,
each sublist with the same length: M=[[1, 2], [3, 4]]; M → [[1, 2], [3,
4]]; M[1][1] → 4; M[0][1] → 2; len(M[1]) → 2
Initialization, with several values, of an array with 3 rows and 4 columns:
M=[[0,0,0],[0,0,0]]; for I in range(2):; for J in range(3): M[I][J] = I+J+2
→ [[2, 3, 4], [3, 4, 5]]; M[2][1] → 3
For larger dimensions, simply extend the recipe.
3. To loop through all elements and display their values: 4. Getting lines: 5. Getting columns: |
6. Generateing a vector with increasing values: 7. Generating a two-dimensional array with increasing values 8. Constroying a vector applying a function, e.g. sqrt, to all
its elements: |
In Python, an iterable is an object capable of returning its members one at a time, allowing it to be looped over in a for-loop. Common examples of iterables include lists, tuples, dictionaries, and sets.
Op |
Meaning and types of operands |
Examples |
+ |
Binary operator (with two arguments): sum of int, float, or complex; concatenation of strings, lists and tuples |
A+B → 3, D+E → 3.5; A+D → 2.2; (A+D*1j)+(E+C*1j) →
(3.3+4.2j); |
+
|
Unary operator (with one argument): no effect | +A → 1 |
– |
Binary subtraction operatorfor int, float or complex types; set complementation |
C–B → 1; F–D → 2.2; F–A → 2.4 |
–
|
OUnary sign change operator | –A → –1 |
* |
Int, float or complex multiplication |
B*C → 6; D*E → 2.76; B*D → 2.4; (A+D*1j)+(E+C*1j) → (3.3+4.2j) |
/ |
Int, float or complex division |
C/B → 1.5; F/E → 1.4782608695652175; C/D → 2.5; |
// |
Division of int results in int; float by int gives integer part of result in float |
C//B → 1; F//D → 2.0; F//B → 1.0; |
% |
Int remainder from division of ints, integer part if division of floats |
C%B → 1; F//D → 2.0; F//B → 1.0 |
** |
** |
B**C → 8; B**D → 2.2973967099940698; D**B → 1.44; D**E → 1.5209567545525315; (1+1j)**2 → 2j; 27**(1/3) → 3 (raiz cúbica) |
== |
Tests for equality of int, float, complex or string, resulting True (true) or False (see the table of logical operators); with several == in a single command gives True only if each one of consecutive pairs is equal |
B==A*2 → True; A==B → False; A==D → False; A==int(D) → True; (A+B*1j)==(1+2j) → True; G=='abc’ → True; G==H → False; 1==1==1 → True; 1==1==2 → False; |
!= |
Different, ditto |
A!=B → True; A!=D → True; A!=int(D) → False; (1+2j)!=(2+2j)
→ True; |
> |
Greater than, ditto, but without complex; tests for proper superset |
B>A → True; A>B → False; D>A → True; E>D → True; H>G → True; 3>2>1 → True; 3>2>3 → False; |
< |
Less than, ditto; proper subset |
A<B → True; B<A → False; etc. |
>= |
Greater than or equal, ditto; test for superset |
B>=A → True; B>=D → True; H>=G True; etc. |
<= |
Less than or equal, ditto; test for subset |
B<=A → False; etc. |
&
|
Bitwise "and" of binary values; intersection of sets | 0b0101 & 0b0001 → 1; bin(0b1100 & 0b1010) → '0b1010' (left 0s are not displayed) |
|
|
Bitwise inclusive "or "; union of sets | bin(0b1100 | 0b1010) → '0b1110' |
^
|
bitwise "and" of binary values, decimal result in IDLE; intersection of sets | bin(0b0110 ^ 0b1010) → '0b1100' |
>>
|
Bitwise shift to the right, inserting 0s to the left | J = 10; bin(J) → '0b1010'; bin(J>>1) → '0b101' (left 0s are not displayed) |
<<
|
Bitwise shift to the left, inserting 0s to the right (equivalent to division by pow(2,n) | J = 10; bin(J) → '0b1010'; bin(J<<2) → '0b101000' |
is
|
Identity test of obejcts. Determines whether two variables point to the same object in memory. | x = y = 0; x is y → True |
is not | Tests non-identity of objetos. Determines if two variables point to different objects in memory. | x = y = 0; x is not y → False |
= |
Single or multiple assignment, right side int, float, complex or string; both sides can be an tuple without "(" and ")" |
A=1; A → 1; A=D; A → 1.2 (A changed from int to float); |
+= |
x += y equivalent to x = x + y |
J=1; J=+2; J → 3; J=(1+2j); J+=(2+3j); J → (3+5j) |
–= |
x -= y equivalent to x = x – y, inclusive de conjuntos |
J=3; J–=2; J → 1 |
*= |
x *= y equivalent to x = x |
J=2; J*=3; J → 6 |
/= |
x /= y equivalent to x = x /y |
J=6; J/=3; J → 2.0 |
//=
|
x // y equivalent to x = x // y | J=15; J//=4; J → 3; J=15.5; J//=3.7; J → 4.0 |
%= |
x %= y equivalent to x = x%y |
J=6; J%=4; J → 2.0; J=6; J%=2; J → 0 |
**=
|
x **= y equivalent to x = x**y | J=2; J**=3; J→ 8 |
>>=
|
x >>= y equivalent to x = x>>y | J=0b1010; J>>=2; bin(J) → '0b10' (left zeroes are not displayed) |
<<=
|
x <<= y equivalent to x = x<<y | J=0b1010; J<<=2; bin(J) → '0b101000' |
&=
|
x &= y equivalent to x = x&y, inclusive for sets | J=0b1100; K=0b1010; J&=K; bin(J) → '0b1000' |
^=
|
x ^= y equivalent to x = x^y, inclusive for sets | J=0b1100; K=0b0110; J^=K; bin(J) → '0b1010' |
|=
|
x |= y equivalent to x = x|y, inclusive for sets | J=0b1100; K=0b1010; J|=K; bin(J) → '0b1110' |
if
|
Condition |
J = 1 if 4>3 else 2 → 1 J = 5 * (1 if B<A else 3*A); → 15 |
Op |
Meaning |
Examples |
In what follows, the prior execution of L1T = True is assumed; L2T = True ; L1F = False ; L2F = False | ||
True | Constant indicating "true" | The identifier "true" is accepted as a variable name, but thereafter it will not be considered tlogical constant anymore: true = False; print(true) → False |
False | Constant indicating "false" | Ditto for false. Considered as False : None , 0, 0.0, 0j, ' ', (), [], {}; other values as True |
not | Negation: changes True to False and vice versa | not L1T → False; not L1F → True |
x or y | "Inclusive or"; gives False only if x and
y are false, True otherwise. |
L1T or L2T → True; L1T or L1F → True; L1F or L1T → True; L1F or L2F → False |
x and y | "and"; gives True only if x and y are true, False otherwise | L1T and L2T → True; L1T and L1F → False; L1F and L1T → False; L1F and L2F → False |
x in y | if x is in string, tuple, list or set y gives True, else False | 'a' in 'false' → True; 5 in (2, 5, 3) → True; 3 in [2, 5, 3] → True; 4 in [2, 5, 3] → False |
x not in y | Contrary to in | 'a' not in 'false' → False; 5 not in (2, 5, 3) →
False; 3 not in [2, 5, 3] → False; 4 not in [2, 5, 3] → True |
is |
Object identity test. Determines whether two variables point to the same object. |
x = y = 0; x is y → True |
is not | Object non-identity test. Determines whether two variables
point to different objects. |
x = y = 0; x is not y → False; x = 0; y = 1; print(x is not 1) → True |
5. NATIVE FUNCTIONS/METHODS (To be complemented; source. Examples were tested using IDLE or with IDLE's Editor. In the latter, displaying of results was done with print().)
Função |
Significado |
Exemplos |
abs() |
Modulus, also of a complex number |
abs(-1) → 1; abs (2) → 2; abs((1+2j)) → 2.23606797749979 |
S.add(x) | Inserts x into the S set | S = {1, 2, 'four'}; S.add('three');
S → {1, 2, 'three', 'four'} Apparently, sets are displayed in alphabetic order |
aiter() | Creates an asynchronous iterable. Used in asynchronous programs (permits concurrent execution, without waiting for completion of operations. A normal program is synchronous, one operation executed at each time, sequentially | Requires the import of specific modules, such as asyncio for input/output. See examples. |
all(x) |
Returns True if all elements of iterable (cf. 2.10) x have value True or x is empty, and False if any element of x has value False |
a = [True, True, True]; b = [True, True, False]; c = []; all(a), all(b), all(c) → (True, False, True) |
anext() | Used in an asynchrohous program (see aiter()). Permits access to the next item of an ansynchrohous iterable. | Part of asyncio. See example. |
any(x) |
Returns True if any element of the iterable x is true, and False if no element of x is True, or x is empty. |
a = [True, True, True]; b = [True, True, False]; c = []; any(a), any(b), any(c) ? (True, True, False) |
ascii(x) | Returns x as a string, skipping characters that are not of type ASCII {EF} | numb = 123; list = [1, 2, "Olá"];
tuple = ("a", "b", "c") print(ascii(numb), ascii(list), ascii(tuple)) → 123 [1, 2, 'Ol\xe1'] ('a', 'b', 'c') |
breakpoint() | Ativa o depurador (debugger) pdb, dando os valores das variáveis e expressões naquele ponto | a = 2; b = 3 if (a+b == 5): breakpoint() print('soma é 5') → print('soma é 5); (Pdb) +a; 2; (Pdb) +b; (Pdb) +b; 3; (Pdb) a+b; (Pdb) +a+b; 5; (Pdb) |
bin() |
Converts an int to bynary |
bin(B) → '0b10'; bin(20) → '0b10100' |
x.bit_length() | Significant bit length of binary x (left 0s are ignored) | 0b101010.bit_length() → 6; 0b001010.bit_length() → 4 |
bool(x) |
Returns True if the argumenthas value True, False if it has value False or it is empty |
bool(B>A) → True; bool(C>D) → False; bool() → False |
bytearray(x) |
Returns a bytearray object which is an array of the bytes in the iterable (cf. 2.10) x |
numbers = [2, 3, 11, 30]; byte = bytearray(numbers); print(byte) → bytearray(b'\x02\x03\x0b\x1e') |
bytes(x,c,er) | The same as bytearraym but the result is an object that cannot be modified. | x = bytes(5); print(x) → b'\x00\x00\x00\x00\x00' |
bytearray(x,c,er) |
Returns a bytearray object which is an array of the bytes in the iterable (cf. 2.10) x using code type; the default is utf-8 in hexadecimal; er is a message string issued if a character in x is not encodable |
numbers = [2, 3, 11, 30]; byte = bytearray(numbers); print(byte) → bytearray(b'\x02\x03\x0b\x1e') |
callable(x) |
Returns True if x is a callable function or method, False otherwise |
x = 10; print(callable(x)) → False |
chr(x) |
Character corresponding to the ASCII code of the argument (between 0 and 255) |
chr(97) → 'a'; chr(150) &rarr ? [the
character was not found] |
classmethod() |
Permits directly calling a method of a classe, without having to instantiate the class {EF} |
class CM: |
x.clear() | Removes all elements from the iterable (cf. 2.10) x | x = {1, 2, 'três'}; x.clear(); x → set() [indica conjunto vazio ou [] se for cadeia] |
compile(s,file,mo) |
Permits compiling and executing an object (e.g. a string), returning the result if the mode mo is 'exec', or 'eval' if s is an expression, or 'single" if s is an iterable object; file obtains s form a file {EF} |
string = 'a=8;b=7;soma=a+b\nprint(soma)' # a=8;b=7;print(a+b) |
complex(re,im) |
Converts to a complex with real part re and imag. im |
complex(1) → (1+0j); complex(2,5) → (2+5j) |
x.conjugate() | Gives the conjugate of the complex x | x = (1+2j); x.conjugate() → (1-2j) [Not working on 3.13.1] |
delattr(cl,attr) |
Deletes atribute attr from class cl {EF} |
class A: |
dict() |
Creates a dictionary {EF} |
|
dir() |
Lists the names of all session variables {EF} |
n = [10]; print(dir()) → [..., n] |
x.discard(y) | Removes element y from the set x, if y is in x; does nothing if y is not in x. | x = {1, 2, 'three'}; x.discard('three'); x → {1, 2} |
divmod(x,y) |
Gives the ordinate duble (x // y, x % y) |
divmod (C,B) → (1,1) divmod (C,D) → (2.0, 0.6000000000000001) |
x.encode(c) | Encodes x using the encoding type c, utf-8 is the default | |
enumerate(x) |
Returns iterable x enumerating each of its elements |
lis = ['a', 'b', 'c']; print(list(enumerate(lis))) → [(0, 'a'), (1, 'b'), (2, 'c')] |
eval(x) |
Runs the string x and returns its value. x maybe te result of input(). x cannot be a compound statement. |
eval('2*3') → 6 eval("'abc'[1]") → 'b' |
exec('c',gl,loc) | Immediately executs code c; gl and loc are dictionaries allowing for the specification of global and local variables to be used, guaranteeing safety |
exec('print("The sum of 5 and 10 is", (5+10))') &rarr The sum
of 5 and 10 is 15 |
exit() | Ends execution of the program. | Requires sys module, incorporated with import sys. Usage: sys.exit() |
filter(f, L) |
Apply the function f to each element of the iterable L, and results in the elements of L for which f is True |
See example in section "Lambda notation" |
float(x) |
Converts x to float |
float(B) → 2.0; |
float.as_integer_ratio() | Returns a pair of integers whose ratio is the argument | float.as_integer_ratio(1.5) → (3,2) |
float.is_integer() | Returns True if the argument is integer, False otherwise | float.is_integer(1.5) → False; float.is_integer(3.0) → True |
format(x,f) |
Returns the value of x in the format f. See the large types of formats {EF} |
a = 123; print(format(a, 'x')); print(format(a, 'b')) → 7b 1111011 |
frozenset() |
Builds a set that cannot be changed |
x = frozenset({1, 2}); x → {1, 2}; x.pop() gives an error message |
getattr(obj,attr,defa) |
Returns the value of an attribute attr of object obj. If the attribut does not exist in obj, returns default defa |
class Cla: |
globals() |
Returns a dictionary with names and values of all global variables {EF} |
a = 1; b = 2; print(globals()) &rarr {..., 'a': 1, 'b': 2} |
hasattr(clobj,attr) |
Returns True if the class or object clobj has attribute attr {EF} |
class A: |
hash(x) |
Retorna a unique integer representing x, which can only be a string, a number or a tuple. The result may vary depending on the session. |
hash('Python') → 402769285147184097 hash((1,2,3)) → 529344067295497451 |
help() |
In interactive mode (IDLE, W3 compiler, see section 1-3), gives documentation of the argument |
help(int) |
hex() |
Converts an int to a hexadecimal |
hex (8) → '0x8'; hex (50) → '0x32'; hex(C) → '0x3' |
id(x) |
When an object x is created, a unique number (address) is associated to it; id returns this number {EF} |
a = 5; b = 6; c = a + b; print('a', id(a), 'b' id(b), 'c' id(c)) → |
__import__() |
Import of modules. Same as the import command. |
|
input("mensagem") |
Waits for the user to enter input, followed by Enter. Returns the input data in the form of a string; may display a message when running. Did not work on W3 on-line compiler. |
day=input('Enter the value of the day:');
→ "Enter the value of the day" 20 Enter dia →
'20' (as a string); |
int() |
Converts to int |
int(D) → 1; int('123') → 123 |
x.isdisjoint(y) | True if the set x is disjoint from the set y, False otherwise | {1, 2, 'três'}.isdisjoint({4,
'cinco'}) → True {1, 2, 'três'}.isdisjoint({2, 'cinco'}) → False |
isinstance(clobj,t) |
Returns True if the class or object of clobj is of the same type as t; if t is a tuple, returns True if obj is of any of the types of t {EF} |
print (isinstance("Hello", (float, int, str, list, dict, tuple))) → True |
issubclass(c1,c2) |
Returns true if class c1 is a subclass of class c2, False otherwise {EF} |
class A: |
iter(x) |
Returns an index to the elements of iterable x {EF} |
x = iter(["a", "b", "c"]) |
s.join(x) | Method in class string. Concatenates the parts of the iterable x, separating them with the string s. | S = ','.join(['a', 'b', 'c']); S → 'a,b,c' |
len(x) |
Returns the number of elements in iterable (cf. 2.10) x |
len(G) → 3; len((1,2,3,4)) →
4; len((A,B,G)) → 3; len([1,B,5,7]) → 4 |
list() |
Converts the elements of an iterable into a list; without argument gives the empty list |
list(G) → ['a', 'b', 'c']; list((1, 2, 3)) → [1, 2, 3]; list({1,2,3}) → [1, 2, 3] |
locals() |
Returns a dictionary with names and values of local variables of a function or program |
def f(x): |
lower() | Converts letters in a string to lowercase | 'BLAH3#'.lower() → 'blah3#'; name = input('Enter your name:').lower(); print(name) |
map(f,L) |
Applies the function f to each element of one or more iterables (cf. 2.10) L |
list (map (abs, [2,-3,4,-5])) → [2, 3, 4, 5] |
max(x) |
Returns the largest of the elements of the argumentor iterable x |
max (1,2,3) → 3; max (['a', 'b', 'c'])
→ 'c'; max ('a', 'aa', 'aaa') → aaa; |
memoryview(x) |
Returns an object with the internal representation of x {EF} |
a = bytearray('ABC', 'utf-8'); m = memoryview(a); print(list(m[1:3]))
→ |
min() |
As max, but for the least element |
min (1,2,3) → 1; min (['a', 'b', 'c'])
→ 'a'; min ('a', 'aa', 'aaa') → a; |
next(x) |
Returns the next value of iterable (cf. 2.10) x {EF} |
a = [5, 6, 7]; b = iter(a); print(next(b), next(b)) → 5 6 |
object() |
Returns the class that is the base of all classes; it is not possicle to define attributes to it, but it contains all attributes common to all classes. e.g __init__, __strint__, etc. {EF} |
obj = object(); print(dir(obj)) → |
oct() |
Converts to octal |
oct(15) → '0o17' |
open(fi,m) |
Opens file with path and name fi in mode m, as an object. m may be r (reading only), w (writing, creates arq if non existent), a (appends a string to arq, creats if non existent, ), x (creates fi, error if it exists), b (binary file, e.g. with image), t (text file, standard). arq becomes a class with attributes. |
f = open('name', 'w'); f.write('Text'); f = open('name', 'r') |
ord() |
Contrary to chr |
ord ('a') → 97 |
x.pop() | Removes the last element of the iterable (cf. 2.10) x | x = {1, 2, 'três'}; x.pop(); x → {1, 2} |
pow(x.y) |
Equivalente a x**y |
pow(2,3) → 8; pow(4,0.5) → 2.0; pow (4,-2) → 0.625 |
print() |
Data output. x may contain various objects and expressions, separated by commas, as well as strings to be exhibited as constants, and line control parameters (\...) |
print(A,D) → 1 1.2; print ('A =',A)
→ A = 1; print ('A*3 =',A*3,'\nD =',D) → |
property(cl) |
Used inside a class cl, permits altering the values of attributes of cl {EF} |
See examples here |
random |
A class. Requires importing the random
module. Some functions of this class: |
The results obtained with IDLE
may be different, depending on the "seed": 1. import random; random.randint(10, 100) → 12; random.randint(10, 100) → 67 2. random.random() → 0.05462293624556047; random.random() → 0.36903357168070205 3. random.uniform(2,5) → 3.983840861586745 4. random.choice([1,2,3,4,5])) → 3; random.choice([1,2,3,4,5])) → 4 5. x=[1,2,3,4]; random.shuffle(x); x → [3, 1, 4, 2]; random.shuffle(x); x → [4, 1, 2, 3] |
range() |
Creates a virtual list, to be used in a for statement. first indicates the order of the first element, end the order of the last, and step (if omitted, it is 1) the increments in the order. |
range(C): equivalent to [0, 1, 2]; range(1,
5) to [1, 2, 3, 4, 5]; |
reduce(fu,li) |
This function is part of the module "operator". It applies the funcion fu to all elements of list li. It requires loading the module "functools", allowing operators (sections 3 and 4 above) to be specified as functions. Another possibility is using the lambda notation (section 10) defining a function with an operator. |
import functools |
reload() |
Reloads a function x defined in a present module |
|
repr(x) |
Returns the value of x in the form of a string. x may be a class object, recriating it. Useful for debuggin. (Look for examples with class objects.) |
x = "abc"; y= [1, 2, 3]; print(repr(x, repr(z)) → ("'abc'", '[1, 2, 3]') |
reversed(x) | Returns iterable (cf. 2.10) x in its reverse order. Not applicable to sets {EF} | print(list((reversed('abc')))); print(list((reversed(('d','e','f')))))
→ ['c', 'b', 'a'] ['f', 'e', 'd'] |
round(x,n) |
x rounded to the nth decimal place; without n rounds to the integer |
round(3.5566,3) → 3.557; round(4.5555,3)
→ 4.555; |
s.rstrip(c) | As lstrip, deletes string c to the left of string s | print("example!!!".rstrip("!"), "example!!! ".rstrip("!")) → exemple exemple!!! {EF} |
set(x) |
Converts iterable (cf. 2.10) x to a set; if x is empty, creates the empty set |
set([1, 2, 'three']) → {1, 2, 'three'}; set() → set() |
setattr(clobj,'attr',val) |
Assigns value val to the string attribute attr of class or object clobj {EF} |
class Person: |
|
Defines indeces of an iterable (cf. 2.10) x to be used later on with the iterable to extract part of itl; start, end step as in funtion range() |
T= ("a", "b", "c", "d", "e",
"f"); y = slice(2); T[y] →
('a', 'b') |
staticmethod(cl,m) |
Converts method m of class cl into a static method, which can be used wothout having to instantiate cl into an object {EF} |
class Cl: |
str(x) |
Converts int or float x to string |
str(C) → '3'; str(D) → '1.2' |
sum() |
Sums the elements of an iterable (cf. 2.10) |
sum([A,B,C, 4, D]) → 11.2; sum((1,2,3)) → 6; sum ({1, 2, 3}) → 6 |
super() |
Permits that a child class C2 which inherits the properties of a parent class C1 uses the attributes of C1 |
class C1: #Example taken from W3 Schools |
time.sleep(n) | Interrupts the execution of
a program for n seconds. Requires loading the time module: import
time |
import time; print(10);
time.sleep(5); print(20) → 10 [pause] 20 [Does not work on the W3 on-line compiler; works in IDLE] |
tuple() |
Converts an iterable (cf. 2.10) to a tuple |
tuple('abc') → ('a', 'b', 'c'); tuple([1,
2, 3]) → (1, 2, 3); |
type() |
If the argument is a variable,returns its type; if it is an object, its type |
type (A) → <class 'int'>; type (D) → <class 'float'>; type (G) → <class 'str'> |
upper() | Converts letters in a string to upper case | 'bla3#'.upper() → 'BLA3#' |
vars(obj) |
Returns the __dict__ attribute of object obj. Pemits seeing the attributes in a dictionary form. Other atributes used by the system also appear. |
class Ex: |
zip(x) |
x must be a number of parallel iterables, in principle with the same number of elements in each iterable. The result will be doubles, triples, etc., by joining corresponding elements of the iterables. It is as if transforming rows into columns. |
for I in zip([1, 2, 3], ['a',
'b', 'c']): |
To use these functions, it is necessary to execute the import math command
in IDLE or the W3 School on-line compiler, or insert it into a program, which
activates the math module. Functions must be preceded by math, e.g. math.sqrt(4),
math.e etc; results are always of type float, unless otherwise noted. For calculations
with complex numbers, import cmath .
Function |
Meaning |
Examples |
atan(x) | Arctangent, x and result in radians | math.atan(2) → 1.1071487177940904; |
ceil(x) | The less integer >= x | math.ceil(4.7) → 5 |
cos(x) | Cosine, x and result in radians |
math.cos(math.pi/2) → 6.123233995736766e-17 [should be zero; due to approximation of pi]; math.cos(math.pi) → -1.0 |
degrees(x) | Convert x in degrees to radians | math.degrees(math.pi) → 180.0 |
e | The constant e | math.e → 2.718281828459045 |
exp(x) | e**x | math.exp(1) → 2.718281828459045; math.exp(2) → 7.38905609893065 |
factorial(x) | Factorial of x of type int, result in int | math.factorial(5) → 120 |
floor(x) | Bigger int <= x | math.floor(4.7) → 4 |
fsum | Summation | Like sum() of the Native Functions section, but with rounding-off |
inf | The constant infinite (biggest representable float) | math.inf → inf |
log(x, b) | Logarithm of x to the base b (optional); without base gives the log in base e | math.log(10) → 2.302585092994046; math.log(100,10) → 2.0 |
log10() | Logarithm in base 10 | math.log10(100) → 2.0; em geral mais precisa que math.log(x,10) |
log2() | Logarithm in base 2 | math.log2(8) → 3.0 |
modf(x) | Returns in float the decimal and integer parts of x | math.modf(1.25) → (0.25, 1.0) |
pi | The number pi | math.pi → 3.141592653589793 (see examples in, cos and tan) |
radians(x) | Converts x in radians to degrees | math.radians(180) → 3.141592653589793 |
sin(x) | Sin, x and result in radians | math.sin(math.pi/2) → 1.0; math.sin(math.pi) → 1.2246467991473532e-16 (devia ser zero; não é devido à aproximação) |
sqrt() | Square root | math.sqrt(4) → 2.0; math.sqrt(5.6) → 2.3664319132398464 |
tan(x) | Tangent, x in radianos |
math.tan(math.pi) → 1.2246467991473532e-16 (devia ser zero); |
trunc(x) | Integer part of x | math.trunc(3.5) → 3 |
Functions |
Results
|
Examples
|
append() | Adds an element at the end of the list | L=[1, 2, 3, 4]; L=L+[5] → [1, 2, 3, 4, 5]; L=L+'#' → [1, 2, 3, 4, 5, '#'] |
clear() | Clears string or set | L = [1, 2, 'three']; L.clear(); print('d',x) →
[] L= {1, 2, 'three}; L.clear(); print('c',x); → set(); |
copy() | Returns a copy of the list as a new object | L = [1, 2, 'three']; Lnew= L.copy(); print(Lnew) → [1, 2, 'three'] |
count(v) | Returns the number of elements with value v |
L=[1, 2, 3, 2, 4, 2]; Conta_L = L.count(2); print(Conta_L) → 3 |
extend(s) | Add the elements s of a list (or any iterable), to the end of the list | L=[1,2,3,4]; L.extend([5,6]); print(L) &rar;r [1, 2, 3, 4, 5, 6] |
index(v,s,e) | Returns the índex of the first element
com o valor v starting at s and endint at e |
L = [1,2,'three']; i1 = L.index(1); i2 = L.index('three');
print(i1,i2) → 0 2 L = [1, 2, 3, 4, 1, 1, 1, 4, 5]; i1 = L.index(1, 4, 8); i2= L.index(1, 2, 8); print(i1,i2) → 4 4 |
L.insert(p,e) | Adds an element e at position p of list L | L = [1, 2, 3, 4]; L.insert(2, 10); print(L) → [1, 2, 10, 3, 4] |
lstrip() | Removes blank spaces or specified characters at the begining of a string | Same as strip(), but from the begining |
pop(e,p) | Removes the element e at position p; if p is not given, removes the last element in the list | L = [1, 2, 3, 2, 4]; L.pop(3); print(L) → [1, 2, 3, 4];
print(L.pop()); → [1, 2, 3] pop() may be used to pop-up the topmost element of a stack |
remove() | Removes the first item with the specified value |
L = [1, 2, 3, 2, 2]; L.remove(2); print(L) → [1, 3, 2, 2] |
replace('a','b') | Replace ocurrences of 'a' by 'b' | OLA = 'He?llo, g?oo?d mot?ning!?!'; OLALimpo =
OLA.replace('?', '') print(OLALimpo) → Hello, good morning!! |
reverse() | Reverses the order of the list | L = [1, 2, 3, 4]; L.reverse(); print(L) → [4, 3, 2, 1] |
sort() | Sorts the list | L = [1, 3, 4, 2]; L.sort(); print(L) → [1, 2, 3, 4] |
s.split(sep) | Method of class string. Generates a list with the elements of string s separated by the string sep; if sep is omitted, it uses blank space as separator | s='a,b,3'; s.split(') → ['a', 'b', '3']; s='x#y#z'; s.split('#') → ['x', 'y', 'z'] |
strip() | Removes blank spaces os specified characters at the beginning and end of a string | OLA = " Hello, good morning!!"; OLALimpo
= OLA.strip(); print(OLALimpo) → Hello, good morning!!!! OLA = ",,##?? Hello, good morning!!,,##?? "; OLALimpo = OLA.strip(',#? '); print(OLALimpo) → Hello, good morning!! [The blank at the end of the string is essential; stops stripping characters from both end once it encounters a character that is not in the specified characters.] |
rstrip() | Removes blank spaces os specified characters at the end of a string | Same as strip(), but from the end |
translate() | Remove a sbustring using None | OLA = 'He?llo, g?o?od mor?ning!?!'; OLALimpo = OLA.translate({ord('?'):
None}); print (OLALimpo) → Hello, good morning!! |
8. PRECEDENCE (EXECUTION ORDER)
Order |
Operator/function |
Examples |
1
|
( ... ) | (... ignored by the interpreter {EF}) |
2
|
function() | abs(-5)+2 → 7 |
3
|
unary + and - | -5-2 → -7; -(+5-2) → -3 |
4
|
*, /, % and// | |
5
|
binary + e - (addition and subtraction) | |
6
|
& ("and", bit bybit) | |
7
|
| and ^ | |
8
|
<=, <, >, >= | |
9
|
=, %=, /=, //= e –= | |
10
|
+=, *= e **= | |
11
|
in, not in | |
12
|
not, or, and |
Syntax |
Examples on IDLE |
# Declaration (attention to vertical alignment) # Activation |
>>> def sum(a,b): # declaration When typing in IDLE, it is necessary to insert a blank line to end a function declaration (about IDLE, see section 16 below). |
In a program sequence, the declaration of a function
must always come before its activation.
This notation allows for the declaration of
a function without giving it a name, placing it anywhere a function can be called.
Syntax |
Examples on IDLE |
lambda paramenter_list: functon of these paramenters |
>>> y = lambda x: x**2 #Hit Enter >>> min = lambda x,y: x if x < y
else y >>> items = [1, 2, 3, 4, 5]; >>> number_list = range(-5, 10) |
An identifier declared within a function is only local to it (valid within it); declared outside the function, before or ater it in a scope (i.e., validity space) directly encompassing the function, it is global, it can be used both outside and inside the function. Using a local identifier avoids many errors, as only the function where it is declared can modify its value; this identifier has been "encapsulated" into the function. In this sense, the correct thing to do is to pass argument values to the function and obtain them from it through parameters in its declaration (arguments in its activation).
>>> def F(): |
Converting a local identifier into a global: >>> def F(): |
An F2 function can be declared inside another
F1 function. In this case, F2 becomes local to F1 and cannot be activated outside
of F1:
>>> def F1(): |
>>> def F1(): ... def F2(): #Local to F1! ... LocF2 = 13 ... print (LocF2) >>> F2() F2() NameError: name 'F2' is not defined |
If function F2 is declared inside F1, the nonlocal declaration causes a variable V declared in F2 to become the scope of F1, but is not valid outside of F1. V must have a value assigned to it in F1 before the nonlocal declaration:
>>> def F1(): LocF1 = 13 # Local a F1 necessária! print ("Na F1:", LocF1) def F2(): nonlocal LocF1 # Global a F2 LocF1 = "26" print ("Passou pela F2:", LocF1) F2() # Na F2 ... ... >>> F1() Na F1: 13 Passou pela F2: 26 >>> F1(); In F1: 1 In F2: LocF2 |
>>> def F1(): >>> def F2(): >>> Local =1 >>> print(Local) ... ... >>> F2 NameError: name 'F2' is not defined |
Classes can be conceptually viewed as an extension of types and functions, and are used to achieve further encapsulation. Unlike functions, classes do not contain parameters in the declaration of their name; to be used with arguments in their activation ("calling"), the latter have to be declared in the class body as a first attribute; one can change the name of the class, but the common use is to call it "self" (see example below). The native function __initi__() declares the initial attributes of the class, and is activated every time an object is created for that class (see below). In its body, a class can contain variable and function declarations, which become local to them. Each element declared in a class is called an "attribute" or, more generally, "property", thus encompassing functions. A property is declared using the class name, a period, and the attribute or property name. Like functions, classes must be defined before they can be used. A functions declared within a class is called a method. One can assign values to elements of a class outside of it. A class can be assigned to a variable V; in this case V receives an instance of the class, an object, with all the properties of the class. One may declare any number of objects. A class C2 can be declared as a subclass of a class C1. In this case, C2 "inherits" all properties of C1, but it may have its own, local properties, inacessible by C1. A class can be created dynamically using the function type(N,B,dic), where N will be the name of the class, B a tuple which works as a base class, from which the created class N inherits the attributes (i.e., N will be a subclass of B), and dic is a dictionary containing the names of the attributes and values that N will contain (see example below). To eliminate an object p, use del p. Se other functions applied to classes in section 5 above.
12.2 Polymorphism
Polymorphism is the ability of the same operator, function, or
object of a class to operate with arguments of different types. For example,
the operator + can indicate the sum of integers, the concatenation of strings
or tuples, etc. The function len(x) accepts, as the argument x, strings (giving
the number of characters), or a list, tuple or set (giving their number of
elements). All of this is predefined. The polymorphism of functions or methods
of classes is something defined by the programmer. The same function f can
occur in different classes. In this case, f can be applied to several instances
(objects) of these classes, as exemplified below. This helps to implement
and use a personal "program library" there are already those
of available modules and of many contributors, permitting the reutilization
of parts of programs.
class C: |
# Dynamic creation of a new class C2 If C2 is declared as a subclass of a class C1, use C1 instead of "object"; C2 inherits all attributes of C1 |
class person: |
class Person: Age = 84 p1 = Person # Creation of object p1 print(p1.Age) p1.Age = 48 # Modifying the value of object attribute print(p1.Age) → 84 48 |
12.3 Inheritance
The concept of inheritance is quite old in programming languages. It emerged with the Algol language, which had its final definition in 1960, with Agol-60. In this language, a block was declared with commands between begin ... end. It was possible to declare a block B2 inside a block B1. In this case, all variables and procedures (called "functions" in the later C language) declared in B1 were accessible in B2 (called global to B2), but those declared in B2 were not accessible inside B1 (they were local to B2). It was conventional to say that B2 inherited the properties declared in B1. In Algol, a special function was a type of procedure that returned a value, like a function in Python. In the C language, it was not possible to declare a function inside another: all functions had only one lexical level (the outermost), which was imposed by questions of efficency f the machine (PDP-11) for which the language was developed. That is, instead of changing the structure of the machine, programming was distorted. Python allows one to declare a function F2 inside another F1, which is called nested functions; all the variables and functions ("properties") declared in F1 are available inside F2 (global to F2). The term inheritance of F2 in relation to F1 was established, that is, F2 inherits the attributes and functions declared in F1, which are global to F2, and those declared in F2, which are not available in F2 outside F1, that is, are local to F1. The properties of F1 have a scope that encompasses the whole of F2; the scope of the properties of F2 only has the scope of F2 (see diagram below).
The notion of inheritance also applies to classes: it is possible to declare a class C2 as being a subclass of another superclass C1. The C++ language introduced the notion of classes in C, and since in C there was no function declaration within a function, this syntax was passed on to C++ in relation to classes. Python preserved this structure. In order for C2 to inherit all the properties of C1, it is necessary to declare them as in the following schema:
def F1(): # propriedades próprias de F1; as de F2 não estão disponíveis def F2(): # propriedades próprias de F2; as de F1 estão disponíveis |
class C1: # Superclasse
de C2 # propriedades próprias de C1; as de C2 não estão disponíveis class C2(C1): # Subclasse de C1 # propriedades próprias de C2; as de C1 estão disponíveis |
Finally, a philosophical observation: the notion of inheritance is yet another misnomer in computing, which is full of misleading anthropomorphisms: minerals and plants do not inherit; only animals and human beings inherit. Machines are on a lower level than minerals.
Syntax |
Examples (testados no Azure, V. Ambientes abaixo) |
|||
13.1 Block of statements All in the same line: Statement; Statement;... ; Statement; Multiple lines. Have to be vertically aligned to the left margin or a column, if the block is immersed in some statement: Statement |
J=2 |
13.2 if - Logical choice statement # Attention to the vertical alignement |
J = 2; K = 3; L= 4 # válido para todos os exemplos seguintes |
|||
if J < K: print(J); print(K)→
if K > J : """ O
":" pode estar em {PC} corrected (5, 7) if K < J: N=5 |
if K < J: N=5
|
13.3 while statement for repeating the execution (loop) of a statement or block of statements while Logical Expression: # a single statement; or a
block of statements aligned vertically to the right
of the w The else command is executed when the Logical Expression results
is False |
Warning: when using a while command
in IDLE, it is executed until the end (until Logical Expression results
in False) before the next command can be given. Suppose |
|||
M = 1 M = 1 |
M = 1 i = 0; L = [] |
# Example of a loop I = 1 |
13.4 for repetition tatement (loop)
The continue statement may be used inside a for, as with
the while statemente |
for I in range(3): #starts with
0! for
I in range(2,4): #starts with2 Fruits = ['apple','peach','mango'] for I in range(3): |
for letter in 'xyz':
|
for using iterables (cf. 2.10) | ||
for i in [1, 2, 3]: print (i) → |
for car in "123": print (car) → |
for index in {'one':1,
'two':2}: print (index) → two one |
13.5 match...case of multiple logical choices | ||
match Expression:
If Expression1,..., ExpressionN all have values other than Expression,
then statemt is executed; this last case_ is optional
|
Suppose that variiable Color has a value 'blue', green', or 'red', or neither one of these, and one wants to exhibit the value of each one: match Color: The match statement replaces with many advantages a chain of if's when testing the value of a single condition if <Expressiono> = ... : |
13.6 import statement Includes a module into a program, or just some of its functionalities. E.g., to use a mathematical funcion like sqrt it is necessary to import the math module. But if the program uses only the sqrt function, it may be imported isolatedly using the from statement: from module import function To use another name for a module: |
import math; math.sqrt (4) → from math import pi; pi → import math; math.e →
|
|
13.7 try statement Exception (error) detection This statement checks if something in statement1 is undefined or produces
an error, so statement1 cannot be executed. Then statement2 and statement3
(there could be just one or more except statements) are executed.
If statement1 can be executed (no error) the else optional statement
is executed. The finally optional statement executes statement5
regardless of whether there was an error in statement1. As the name
try says, it is also used to test whether there will be an error
in statement1, before the error occurs and execution stops. One may embed a try inside a try |
try: Suppose the existence of a list named L. This command can be used to
check whether the element L[j] is not in the list L , in which case
the value of j is greater than the index of the last element of L, or
negative, cf. item 2.5 above: try: |
|
13.8 pass This command, which is not composed, inserted into another one causes the system to ignore this other one. It is very practical when creating a program. See the example. See many examples of pass .
|
def OneFuntion(x): The body of OneFunction has not yet been programmed, but it is already
known that it will exist and the function will remain in this part of
the program. This ensures that the entire program will be executed;
without the pass it wouldn't be, there would be a syntax error. try: L[j] |
|
13.9 raise executes an exception handling class raise SystemExit("Message") This command, which is not composed, forces an error to occur, and
terminates execution. |
a = 5 In the example below, the program tests whether a type conversion is
valid; ValueError is a class that prints its name and argument: s = 'apple'' |
|
13.10 yield x This statement must be used within a function, generating a result
for it. It does not interrupt the execution of the function, unlike
return, which returns a single value (eventually, an iterable)
and ends the execution of the function. Yield can be placed in
several places within a function, and will generate the function's value
every time it is executed. return can also occur in several places,
but if executed it ends the execution of the function. |
def EvenOrOdd(x): |
Module is a name given in Python to a program M that can be inserted into
a program P.For this, it is necessary that P "imports" M, using
in P the statement import M. On import, one can locally rename a module
M to MM using import M as MM. To create a module M, one must
create a program for M and then store it with some name, for example M, and
the necessary extension .py, i.e., M.py . In this way, one can create and
use program libraries, reusing tested programs. A module M can contain its
own variables and functions, which are used as if M were a class. If a variable
V and f are a variable and a function declared within M, when referring to
them in program P one uses M.V and M.f().
Below are some very useful modules. To use them, one needs to examine the corresponding documentation, which can be found seraching the internet with Python and the module name.
The following words cannot be used as identifier names (variables, functions
and classes):
assert and as break class continue def del elif else except False finally for from global if import in lambda match None nonlocal not or pass is raise return True try while with yield |