8.1. Builtin Functions
8.1.1. pow()
- Raise to the Power
pow()
- Raise number to the power of exponential (the same as**
)
>>> pow(2, 4)
16
>>>
>>> pow(16, 1/2)
4.0
Builtin function pow()
raises number to the n-th
power.
Note, that arithmetic operator **
also raises number to the power:
>>> pow(10, 2)
100
>>>
>>> pow(2, -1)
0.5
>>> pow(1.337, 3)
2.389979753
>>>
>>> pow(4, 0.5)
2.0
>>>
>>> pow(2, 0.5)
1.4142135623730951
Builtin function pow()
can be used to calculate roots of a number:
>>> pow(4, 1/2)
2.0
>>>
>>> pow(2, 1/2)
1.4142135623730951
>>>
>>> pow(27, 1/3)
3.0
>>> pow(4, -1/2)
0.5
>>>
>>> pow(2, -1/2)
0.7071067811865476
>>>
>>> pow(27, -1/3)
0.33333333333333337
>>> pow(-2, -1)
-0.5
>>>
>>> pow(-4, -1)
-0.25
Builtin function pow()
can return complex
numbers.
Note that Python has special complex()
numeric type.
>>> pow(-2, -1/2)
(4.329780281177467e-17-0.7071067811865476j)
>>>
>>> pow(-2, 1/2)
(8.659560562354934e-17+1.4142135623730951j)
>>>
>>> pow(-4, -1/2)
(3.061616997868383e-17-0.5j)
>>>
>>> pow(-4, 1/2)
(1.2246467991473532e-16+2j)
8.1.2. slice()
- Slice Function
Every
n
-th elementsequence[start:stop:step]
start
defaults to0
stop
defaults tolen(sequence)
step
defaults to1
>>> text = 'We choose to go to the Moon!'
>>>
>>> q = slice(23, 27)
>>> text[q]
'Moon'
>>>
>>> q = slice(None, 9)
>>> text[q]
'We choose'
>>>
>>> q = slice(23, None)
>>> text[q]
'Moon!'
>>>
>>> q = slice(23, None, 2)
>>> text[q]
'Mo!'
>>>
>>> q = slice(None, None, 2)
>>> text[q]
'W hoet ot h on'
8.1.3. abs()
- Absolute value
abs()
- Absolute value
>>> abs(1)
1
>>>
>>> abs(-1)
1
>>> abs(1.2)
1.2
>>>
>>> abs(-1.2)
1.2
>>> abs(+0)
0
>>> abs(-0)
0
8.1.4. 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]
8.1.5. 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
8.1.6. 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
8.1.7. issubclass()
8.1.8. any()
DATA = [1, 2, 'three', 4]
if any(isinstance(x, str) for x in DATA):
print(True)
else:
print(False)
# True
8.1.9. all()
DATA = [1, 2, 'three', 4]
if all(isinstance(x, int) for x in DATA):
print(True)
else:
print(False)
# False
8.1.10. sum()
sum(x for x in range(0, 100))
# 4950
8.1.11. len()
DATA = [1, 2, 3]
len(DATA)
# 3
8.1.12. 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!'
8.1.13. bin()
Konwertuje liczbę na binarną
Nie stosuje kodu uzupełnień do dwóch
0b101111 # 47
bin(3) # '0b11'
bin(-3) # '-0b11'
8.1.14. hex()
Konwertuje liczbę na heksadecymalną
Konwersja kolorów w HTML
Shellcode
hex(99) # '0x63'
8.1.15. oct()
Konwertuje liczbę na oktalną
Przydatne do uprawnień w systemie operacyjnym
oct(33261) # '0o100755'
8.1.16. ord()
Zwraca kod ASCII jedno-znakowego stringa.
ord('a') # 97
8.1.17. chr()
Z pozycji w tablicy ASCII konwertuje kod na znak Unicode.
chr(97) # 'a'
8.1.18. eval()
eval('name="José Jiménez"; print(name)')
# José Jiménez
8.1.19. 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 |
8.1.20. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Builtin Function Average
# - Difficulty: easy
# - Lines: 12
# - Minutes: 13
# %% 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
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> pprint(result) # doctest: +ELLIPSIS
{'petal_length': 3.6666...,
'petal_width': 1.1500...,
'sepal_length': 5.6666...,
'sepal_width': 3.0500...,
'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 = {}