7.1. Builtin Functions¶
7.1.1. range()
¶
Tworzy iterator, który zwraca liczby w sekwencji.
for liczba in range(0, 5):
print(liczba)
# 0
# 1
# 2
# 3
# 4
for liczba in range(0, 5, 2):
print(liczba)
# 0
# 2
# 4
numbers_generator = range(0, 5)
print(numbers_generator)
# range(0, 5)
numbers_generator = range(0, 5)
numbers = list(numbers_generator)
print(numbers)
# [0, 1, 2, 3, 4]
7.1.2. type()
¶
type(1) # <class 'int'>
type(1.2) # <class 'float'>
type('hello') # <class 'str'>
type(True) # <class 'bool'>
type(False) # <class 'bool'>
type(None) # <class 'NoneType'>
type([1, 2]) # <class 'list'>
type((1, 2)) # <class 'tuple'>
type({1, 2}) # <class 'set'>
type({1: 2}) # <class 'dict'>
type(1) == int # True
type(1.2) == float # True
type(True) == bool # True
type(False) == bool # True
type(True) == int # False
type(False) == int # False
type(None) == int # False
type(None) == bool # False
type(None) == None # False
7.1.3. isinstance()
¶
Sprawdza czy dany obiekt jest instancją danej klasy
Jeżeli jest więcej niż jeden typ to musi być
tuple
a nielist
lubset
isinstance(10, int) # True
isinstance(10, float) # False
isinstance(10, (int, float)) # True
isinstance(True, float) # False
isinstance(True, int) # True
isinstance(True, bool) # True
isinstance(False, float) # False
isinstance(False, int) # True
isinstance(False, bool) # True
isinstance(None, int) # False
isinstance(None, bool) # False
isinstance(None, float) # False
7.1.4. issubclass()
¶
7.1.5. any()
¶
DATA = [1, 2, 'three', 4]
if any(isinstance(x, str) for x in DATA):
print(True)
else:
print(False)
# True
7.1.6. all()
¶
DATA = [1, 2, 'three', 4]
if all(isinstance(x, int) for x in DATA):
print(True)
else:
print(False)
# False
7.1.7. sum()
¶
sum(x for x in range(0, 100))
# 4950
7.1.8. len()
¶
DATA = [1, 2, 3]
len(DATA)
# 3
7.1.9. slice()
¶
slice()
arguments must beint
(positive, negative or zero)start (inclusive), default: 0
stop (exclusive), default: len(...)
step, default: 1
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
get = slice(1)
data[get]
# ['a']
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
get = slice(2, 7)
data[get]
# ['c', 'd', 'e', 'f', 'g']
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
get = slice(2, 7, 2)
data[get]
# ['c', 'e', 'g']
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
get = slice(1)
data[get]
# [0]
get = slice(2, 7)
data[get]
# [2, 3, 4, 5, 6]
get = slice(2, 7, 2)
data[get]
# [2, 4, 6]
text = 'We choose to go to the Moon!'
get = slice(23, 28)
text[get]
# 'Moon!'
7.1.10. bin()
¶
Konwertuje liczbę na binarną
Nie stosuje kodu uzupełnień do dwóch
0b101111 # 47
bin(3) # '0b11'
bin(-3) # '-0b11'
7.1.11. hex()
¶
Konwertuje liczbę na heksadecymalną
Konwersja kolorów w HTML
Shellcode
hex(99) # '0x63'
7.1.12. oct()
¶
Konwertuje liczbę na oktalną
Przydatne do uprawnień w systemie operacyjnym
oct(33261) # '0o100755'
7.1.13. ord()
¶
Zwraca kod ASCII jedno-znakowego stringa.
ord('a') # 97
7.1.14. chr()
¶
Z pozycji w tablicy ASCII konwertuje kod na znak Unicode.
chr(97) # 'a'
7.1.15. eval()
¶
eval('name="José Jiménez"; print(name)')
# José Jiménez
7.1.16. Other builtin functions¶
Name |
Description |
---|---|
|
Return the absolute value of the argument. |
|
Return True if bool(x) is True for all values x in the iterable. |
|
Return True if bool(x) is True for any x in the iterable. |
|
Return an ASCII-only representation of an object. |
|
Return the binary representation of an integer. |
|
bool(x) -> bool |
|
bytearray(iterable_of_ints) -> bytearray |
|
bytes(iterable_of_ints) -> bytes |
|
Return whether the object is callable (i.e., some kind of function). |
|
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. |
|
classmethod(function) -> method |
|
Compile source into a code object that can be executed by exec() or eval(). |
|
Create a complex number from a real part and an optional imaginary part. |
|
Deletes the named attribute from the given object. |
|
dict() -> new empty dictionary |
|
dir([object]) -> list of strings |
|
Return the tuple (x//y, x%y). Invariant: div*y + mod == x. |
|
Return an enumerate object. |
|
Evaluate the given source in the context of globals and locals. |
|
Execute the given source in the context of globals and locals. |
|
filter(function or None, iterable) --> filter object |
|
Convert a string or number to a floating point number, if possible. |
|
Return value.__format__(format_spec) |
|
frozenset() -> empty frozenset object |
|
getattr(object, name[, default]) -> value |
|
Return the dictionary containing the current scope's global variables. |
|
Return whether the object has an attribute with the given name. |
|
Return the hash value for the given object. |
|
Define the builtin 'help'. |
|
Return the hexadecimal representation of an integer. |
|
Return the identity of an object. |
|
Read a string from standard input. The trailing newline is stripped. |
|
int([x]) -> integer |
|
Return whether an object is an instance of a class or of a subclass thereof. |
|
Return whether 'cls' is a derived from another class or is the same class. |
|
iter(iterable) -> iterator |
|
Return the number of items in a container. |
|
Built-in mutable sequence. |
|
Return a dictionary containing the current scope's local variables. |
|
map(func, *iterables) --> map object |
|
max(iterable, *[, default=obj, key=func]) -> value |
|
Create a new memoryview object which references the given object. |
|
min(iterable, *[, default=obj, key=func]) -> value |
|
next(iterator[, default]) |
|
The most base type |
|
Return the octal representation of an integer. |
|
Open file and return a stream. Raise OSError upon failure. |
|
Return the Unicode code point for a one-character string. |
|
Equivalent to x**y (with two arguments) or x**y % z (with three arguments) |
|
print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False) |
|
Property attribute. |
|
range(stop) -> range object |
|
Return the canonical string representation of the object. |
|
Return a reverse iterator over the values of the given sequence. |
|
Round a number to a given precision in decimal digits. |
|
set() -> new empty set object |
|
Sets the named attribute on the given object to the specified value. |
|
slice(stop) |
|
Return a new list containing all items from the iterable in ascending order. |
|
staticmethod(function) -> method |
|
str(object='') -> str |
|
Return the sum of a 'start' value (default: 0) plus an iterable of numbers |
|
super() -> same as super(__class__, <first argument>) |
|
Built-in immutable sequence. |
|
type(object_or_name, bases, dict) |
|
vars([object]) -> dictionary |
|
zip(iter1 [,iter2 [...]]) --> zip object |
7.1.17. Assignments¶
"""
* Assignment: Builtin Function Average
* Complexity: easy
* Lines of code: 12 lines
* Time: 13 min
English:
1. Separate header and rows
2. Define dict `result: dict[str, list]`, keys are column names from header
3. For each row, add values to proper lists in `result`
4. Define function `mean()`, calculating mean for arbitrary number of arguments
5. Return `None` if any argument to the function is not `float` or `int`
6. To calculate mean use built-in functions
7. Iterating over `result` print column name and calculated average
8. Run doctests - all must succeed
Polish:
1. Odseparuj nagłówek od wierszy danych
2. Zdefiniuj słownik `result: dict[str, list]`, klucze to nazwy kolumn z nagłówka
3. Dla każdego wiersza, dodawaj wartości do odpowiednich list w `result`
4. Zdefiniuj funkcję `mean()`, liczącą średnią dla dowolnej ilości argumentów
5. Zwróć `None` jeżeli którykolwiek z argumentów do funkcji nie jest `float` lub `int`
6. Do wyliczenia średniej wykorzystaj wbudowane funkcje
7. Iterując po `result` wypisz nazwę kolumny oraz wyliczoną średnią
8. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> result # doctest: +NORMALIZE_WHITESPACE
{'Sepal length': 5.666666666666667,
'Sepal width': 3.0500000000000003,
'Petal length': 3.6666666666666665,
'Petal width': 1.1500000000000001,
'Species': None}
"""
DATA = [
('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'),
(5.8, 2.7, 5.1, 1.9, 'virginica'),
(5.1, 3.5, 1.4, 0.2, 'setosa'),
(5.7, 2.8, 4.1, 1.3, 'versicolor'),
(6.3, 2.9, 5.6, 1.8, 'virginica'),
(6.4, 3.2, 4.5, 1.5, 'versicolor'),
(4.7, 3.2, 1.3, 0.2, 'setosa'),]
result = {}