Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. The list of built in functions in alphabetical order is available at docs.python.org/3/library/functions.

let’s list the data that we will use to learn the function

N1 = 12
N2 = 3.01
N3 = -1
W1 = "Agnieszka"
T1 = (1,2,3,5,4,7,6,9)
L1 = [1,4,3,2,0,6,5,7,8,9]
S1 = {"Ford", "Toyota", "Opel", "Suzuki"}
D1 = {"one":1, "two":2, "three":3}
class MakeUp:
    name = "Mascara"
    serial_number = int("0123456789")
    exp_year = 2027
    color = ["black", "green", "blue"]

A

# ABS
# -  absolute value of a number

print(abs(N1)) #output: 12
print(abs(N3)) #output: 1

# ALL
# - returns True if all items in an iterable are true, 
# otherwise:False.

print(all(L1)) #output: False
print(all(T1)) #output: True
print(all(S1)) #output: True
print(all(D1)) #output: True

# ANY
# - returns True if any item in an iterable are true, 
# otherwise it returns False.

print(any(L1)) #output: False
print(any(T1)) #output: True
print(any(S1)) #output: True
print(any(D1)) #output: True

B

# BIN
# - Convert an integer number to a binary string prefixed with “0b”

print(bin(N1)) #output: 0b1100
print(bin(L1)) #TypeError

# breakpoint
# this function drops you into the debugger at the call site. 
# Specifically, it calls

print(L1) #output: [1, 4, 3, 2, 0, 6, 5, 7, 8, 9]
print(T1) #output: (1, 2, 3, 5, 4, 7, 6, 9)
print(S1) #output: {'Suzuki', 'Opel', 'Ford', 'Toyota'}
print(D1) #output: {'one': 1, 'two': 2, 'three': 3}

print(L1) #output: [1, 4, 3, 2, 0, 6, 5, 7, 8, 9]
breakpoint()
print(D1) #output:
# > c:\users\agnieszka\pycharmprojects\eitca\
#python_functions.py(160)<module>()
# -> print(D1) #output: True
# (Pdb)

C

# CALLABLE
# - Return True if the object argument appears c able, False if not

print(callable(N1)) #output: False
print(callable(L1)) #output: False
print(callable(T1)) #output: False

def clbl(item):
    return (item)

x = clbl
print(callable(x)) #output: True

# CHR
# - Return the string representing a character whose 
# Unicode code point is the integer
print(chr(79))  #output: O
print(chr(101)) #output: e
print(chr(299)) #output: ī

D

# DICT
# - Create a new dictionary. 

D2 = dict(one=1,two=2,three=3)
print(D2) #output: {'one': 1, 'two': 2, 'three': 3}

# DIR
# - returns   properties and methods of the specified object, 
# without the values.

print(MakeUp.name) #output: Mascara
print(MakeUp.color) #output: ['black', 'green', 'blue']
print(MakeUp.exp_year) #output:2027
print(dir(MakeUp))
'''output: ['__class__', '__delattr__', '__dict__', '__dir__',
[...]'__weakref__', 'color', 'exp_year', 'name', 
'serial_number']

DIVMOD
 - returns a tuple containing the quotient
and the remainder when argument1 (dividend) is divided 
by argument2 (divisor)'''

print(divmod(10, 3)) #output: (3, 1)
print(divmod(8, 2)) #output: (4, 0)
print(divmod(191, 4)) #output: (47, 3)

E

# ENUMERATE
# - Return an enumerate object. iterable must be 
# a sequence, an iterator, or some other object 
# which supports iteration.

for l in enumerate(L1):
    print(l)

for t in enumerate(T1):
    print(t)

for d in enumerate(D1):
    print(d)

''' 
EVAL
- (source, /, globals=None, locals=None)
The expression argument is parsed and evaluated as 
a Python expression

EXEC
(source, /, globals=None, locals=None, *, closure=None)
This function supports dynamic execution of Python code

COMPILE
- function returns the specified source as a code object, 
ready to be executed.'''

x = 'print(35)'
eval(x)

x = 10
eval('print(35+10)')

x = 'print("The sum of 35 and 10 is", (35+10))'
exec(x)


exec("print(factorial(5))", {"factorial":factorial})
#or
exec('print(fact(5))', {'fact': factorial})
exec("print(dir())", {"built" : __builtins__}, 
     {"sum": sum, "iter": iter})

x = compile('print(55)\nprint(88)', 'test', 'exec')
exec(x)

codeAsString = ('x = 10\ny=7\nratio=x*y\nprint("value =",'
                'ratio)')
codeAsObject = compile(codeAsString, 'sumstring', 
                       'exec')

exec(codeAsObject)# Output: 15

F

# FILTER
# -Construct an iterator from those elements 
# of iterable for which function is true.

def even(x):
  if x  % 2 == 0:
    return True
  else:
    return False

even_numbers = filter(even, L1)

for x in even_numbers:
  print(x) #output: 4 2 0 6 8

# FORMAT
# Convert a value to a “formatted” representation,
# as controlled by format_spec.

s1 = "This tree is {size} feet toll!"
print(s1.format(size = 6))

s2 = "This dress is for only {price:.2f} $!"
print(s2.format(price = 19.99))

s3 = "My name is {}, I'm {} years old".format("Agnieszka",36)
print(s3)

I

# ID
# function returns a unique id for the specified object.

print(id(N1))
print(id(N2))
print(id(N3))
print(id(W1))
print(id(L1))
print(id(S1))
print(id(D1))
#INPUT
# function allows user input.

# Example 1
# print the already define values (N1-D1)

x = input("Enter a value: ")
x = eval(x)
print(x, id(x))


# Example 2
# with the class elements

class MakeUp:

    def __init__(self, name, serial_number, 
                 exp_year, color):
        self.name = name
        self.serial_number = serial_number
        self.exp_year = exp_year
        self.color = color


Mascara = MakeUp("Maybelline", 
                 "1234567890", 
                 "2027", 
                 "extra black")
Lipstick = MakeUp("Joanna", 
                  "000120aa890", 
                  "2026", 
                  "red")

toiletry_bag = input("What is in  your toiletry_bag? ")
try:
    print("From " + eval(toiletry_bag).name + 
          " ,which is in an " + eval(toiletry_bag).color 
          + " color.")
except NameError:
    print(toiletry_bag + " is not an element "
                         "of MakeUp class")
# ITER
# function returns a reversed iterator object.

i = iter(T1)
print(next(i))
print(next(i))
print(next(i))
#output: 1 2 3

i = iter(L1)
print(next(i))
print(next(i))
print(next(i))
#output: 1 4 3

i = iter(D1)
print(next(i))
print(next(i))
print(next(i))
#output: one two three

Operations on values

# operations on values

print(float(N1)) #12.0

print(int(N2)) #3

print(len(L1)) #10
print(list(T1)) #[1, 2, 3, 5, 4, 7, 6, 9]

print(max(T1), max(L1)) #9 9
print(min(T1), min(L1))#1 0 

print(round(N2)) #3
print(round(2.5678901234,3)) #2.568

print(str(N2)) #3.01 (as text)
print(sum(T1)) #37
print(sum(L1)) #45

M

# MAP
#executes a specified function for each item in an iterable.

def add_func(a, b):
  return a + b

m = map(add_func, T1 , L1)
print(m) #output: <map object at 0x0000026800531E40>
print(list(m)) #output: [2, 6, 6, 7, 4, 13, 11, 16]

R

# RANGE
# class range(stop)
# class range(start, stop, step=1)

R1 = range(6)
R2 = range(0,15,3)
print(R1) #output: range(0, 6)
print(R2) #output: range(0, 15, 3)

for r1 in R1:
  print(r1)

r2 = [r for r in R2]
print(r2)

r3 = [r for r in range(10) if r % 2 == 0]
print(r3)

lst = ["8", "6", "4", "2", "0","-2"]
r4 = [int(r) for r in lst]
print(r4)
#REPR
#Return a string

x = repr(10)
print(type(x)) #output: <class 'str'>
y = repr("A")
print(y) #output: 'A'

# REVERSED
# returns a reversed iterator object

Rev = reversed(sorted(T1))
for r in Rev:
  print(r)

L = L1.sort()
Rev = reversed(sorted(L1))
for r in Rev:
  print(r)

RevName = reversed("Agnieszka")
print([i for i in RevName])
#output: ['a', 'k', 'z', 's', 'e', 'i', 'n', 'g', 'A']

S

# SLICE
# returns a slice object.
# can specify where to start the slicing, and where to end.

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])
#output: ('a', 'b')

x = slice(4)
print(a[x])
#output: ('a', 'b', 'c', 'd')

x = slice(3, 7)
print(a[x])
#output: ('d', 'e', 'f', 'g')

Z

# ZIP
# returns a zip object, which is an iterator of tuples

z = zip(T1,L1)
print(tuple(z))