Functions in Python

Functions in Python

Introducing functions in Python with an example and seeing the result in Iteros Academy. Each of the following has different functions that you need to kno


If you have any questions, ask!

Introducing functions in Python with an example and seeing the result in Iteros Academy. Each of the following has different functions that you need to know to work with the Python programming language.

You don't need to memorize all the functions, you just need to remember what each one does so that you can use them when necessary. All the functions are explained with examples, but you can use the Python online editor to see the result .

abs ()

abs() returns the absolute value of a number

x = abs(-7.25)
print (x)

all ()

all () Returns true if all items in an iterable object are true

mylist = [True, True, True]
x = all(mylist)
print (x)

any ()

any() Returns true if an instance of an iterable object is true

mylist = [False, True, False]
x = any(mylist)
print (x)

ascii ()

ascii() returns the readable version of an object. Replaces the none-ascii character with the escape character

x = ascii("My name is Ståle")
print(x)

bin ()

bin() returns the binary version of a number

x = thousand(36)
print (x)

bool ()

bool() Returns the boolean value of the specified object

x = bool(1)
print(x)

bytearray()

bytearray() returns an array of bytes

x = bytearray(4)
print(x)

bytes ()

bytes() returns a bytes object

x = bytes(4)
print(x)

callable ()

callable () True if the specified object is callable, otherwise False

def x():
  a = 5
print(callable(x))

chr ()

chr() returns a character from the specified Unicode code.

x = chr(97)
print(x)

classmethod ()

classmethod() converts a method to a class method

 

compile ()

compile() returns the specified resource as an object, ready for execution

x = compile('print(55)', 'test', 'eval')
exec(x)

complex ()

complex() returns a complex number

x = complex(3, 5)
print(x)

delattr ()

delattr() deletes the specified attribute (property or method) from the specified object

class Person:
  name = "John"
  age = 36
  country = "Norway"

delattr(Person, 'age')

dict ()

dict() returns dictionary(array)

x = dict(name = "John", age = 36, country = "Norway")
print(x)

you ()

dir() returns a list of properties and methods of the specified object

class Person:
  name = "John"
  age = 36
  country = "Norway"

print(dir(Person))

divmod()

divmod() returns the quotient and remainder when arg1 and arg1 are divided

x = divmod(5, 2)
print(x)

enumerate ()

enumerate() takes a collection (eg tuple) and returns it as an enumerate object

x = ('apple', 'banana', 'cherry')
y = enumerate(x)

print(list(y))

eval ()

eval() evaluates and executes an expression

x = 'print(55)'
eval(x)

exec ()

exec() executes the specified code (or object).

x = 'name = "John"\nprint(name)'
exec(x)

filter ()

filter() Use a filter function to remove items from an iterable object

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
  if x < 18:
    return False
  else:
    return True

adults = filter(myFunc, ages)

for x in adults:
  print(x)

float ()

float() returns a floating point number

x = float(3)
print(x)

format ()

format() formats a specified value

x = format(0.5, '%')
print(x)

frozenset ()

frozenset() returns a frozenset object

mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
print(x)

getattr ()

getattr() returns the value of the specified attribute (property or method).

class Person:
  name = "John"
  age = 36
  country = "Norway"

x = getattr(Person, 'age')

print(x)

globals ()

globals() Returns the current global symbol table as a dictionary

x = globals()
print(x)

hasattr ()

hasattr() returns the specified attribute (attribute/method) if the specified object is specified

class Person:
  name = "John"
  age = 36
  country = "Norway"

x = hasattr(Person, 'age')

print(x)

hash ()

hash() Returns the hash value of a given object

help ()

help() implements the built-in help system

 

hex ()

hex() converts a number to a hexadecimal value

x = hex(255)
print(x)

id ()

id() returns the ID of an object

x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)

input ()

input () Allow user input

print("Enter your name:")
x = input()
print("Hello, " + x)

int ()

int() returns an integer

x = int(3.5)
print(x)

isinstance ()

isinstance() Returns true if the specified object is an instance of the specified object

x = isinstance(5, int)
print(x)

Issubclass ()

Issubclass() Returns true if the specified class is a subclass of the specified object

class myAge:
  age = 36

class myObj(myAge):
  name = "John"
  age = myAge

x = issubclass(myObj, myAge)

print(x)

iter ()

iter() returns an iterator object

x = iter(["apple", "banana", "cherry"])
print(next(x))
print(next(x))
print(next(x))

only ()

len() returns the length of an object

mylist = ["apple", "orange", "cherry"]
x = len(mylist)
print(x)

list ()

list() returns a list

x = list(('apple', 'banana', 'cherry'))
print(x)

locals ()

locals() returns the updated dictionary of the current local symbol table

x = locals()
print(x)

map ()

map() returns the specified iteration with the specified function for each item

def myfunc(a):
  return len(a)

x = map(myfunc, ('apple', 'banana', 'cherry'))

print(x)

print(list(x))

max ()

max() returns the largest item in an iterable

x = max(5, 10)
print(x)

memoryview ()

memoryview() returns a memory view object

x = memoryview(b"Hello")

print(x)

print(x[0])

print(x[1])

min ()

min() returns the smallest item in iterative mode

x = min(5, 10)
print(x)

next ()

next() returns the next item as an iterable

mylist = iter(["apple", "banana", "cherry"])
x = next(mylist)
print(x)
x = next(mylist)
print(x)
x = next(mylist)
print(x)

object ()

object() returns a new object

x = object()
print(dir(x))

oct ()

oct() converts a number to an eighth

x = oct(12)
print(x)

open ()

open() opens a file and returns a file object of the file

f = open("demofile.txt", "r")
print(f.read())

word ()

ord() Convert an integer to the Unicode representation of the specified character

x = ord("h")
print(x)

pow ()

pow() returns the value of x to the power of y

x = pow(4, 3)
print(x)

print ()

print() prints to the standard output device

print("Hello World")

Property ()

attribute() Gets, sets, or removes an attribute

 

range ()

range() returns a sequence of numbers, starting at 0 and increasing by 1 (by default)

x = range(6)

for n in x:
  print(n)

repr ()

repr() returns the readable version of an object

 

reversed ()

reversed() returns a reversed iterator

alph = ["a", "b", "c", "d"]

ralph = reversed(alph)

for x in ralph:
  print(x)

round ()

round() rounds a number

x = round(5.76543, 2)
print(x)

set ()

set() returns a new object

x = set(("apple", "banana", "cherry"))
print(x)

setattr ()

setattr() sets the attribute (property/method) of an object

class Person:
  name = "John"
  age = 36
  country = "Norway"

setattr(Person, 'age', 40)

x = getattr(Person, 'age')

print(x)

slice ()

slice() returns a slice object

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

sorted ()

sorted() returns the sorted list

a = ("b", "g", "a", "d", "f", "c", "h", "e")

x = sorted(a)

print(x)

staticmethod ()

staticmethod() converts a method to a static method

 

str ()

str() returns a string st object

x = str(3.5)

print(x)

sum ()

sum() sums the items of an iterator

a = (1, 2, 3, 4, 5)
x = sum(a)
print(x)

super ()

super() returns an object that represents the parent class

class Parent:
  def __init__(self, txt):
    self.message = txt

  def printmessage(self):
    print(self.message)

class Child(Parent):
  def __init__(self, txt):
    super().__init__(txt)

x = Child("Hello, and welcome!")

x.printmessage()

tuple ()

tuple() returns a tuple

x = tuple(("apple", "banana", "cherry"))
print(x)

type ()

type() returns the type of an object

a = ('apple', 'banana', 'cherry')
b = "Hello World"
c = 33

x = type(a)
y = type(b)
z = type(c)

print(x)
print(y)
print(z)

whose ()

vars() returns the __dict__ property of an object

class Person:
  name = "John"
  age = 36
  country = "norway"

x = vars(Person)

print(x)

zip ()

zip() returns an iterator from two or more iterators

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")

x = zip(a, b)

print(tuple(x))

Source » Itroz Academy

Related articles


Array/List methods in Python
Functions in Python
Class definition in Python
Basic concepts of introductory Python programming

Comments (0)

You need to login to post a comment.