Python Tutorial: a few built-in basic functions
Photo by Jonathan Borba on Unsplash
functions or procedures are python code executed using the familiar mathematical syntax
Python comes with many predefined function, we just will list a few of them because they are so useful and we will use them in next chapters (try them!)
Some of them like
print
launch_rocket(300000,"Moon")
help
or dir
are quite curious – I’d suggest you to peruse them to explore python from within python CLI itself
We will also dedicate a more comprehensive chapter on this topic later
this is the first and most useful function we meet; in its basic usage will print one or more value into our output, different
print("get ready…♥")
print(5,3,2,1,0,"rocket launch")
input
the input function will print its argument and collect your typing until you hit return
answer = input("how went the launch?")
print("I see,", answer)
it always returns a string
len
this function will return the size of a container e.g.
crate = ["beer","beer","beer"]
print("the crate contains",len(crate),"bottles of beer")
As some of you may already have imagined it also works for strings
poppins_magic = "supercalifragilisticespiralidosus"
print("always wanted to check if this word is",len(poppins_magic),"letters long")
sorted and reversed
these functions are quite self-explanative and makes sense with lists
ugly = ["words", "in", "alphabetical", "order"]
print(sorted(ugly))
print(list(reversed(ugly)))
the
list
function is needed to transform a “reversed” value object generated by the reversed function into a regular list – we will see this usage many times and I promise to reveal the arcane reason behind it
round
this function is useful with
print(round(3.1419))
print(round(3.1419, 3))
float
and accepts an optional second argument with the number of decimal digit, if this argument is omitted it returns an integer
min and max
if a container has a list of sortable objects these functions use the most appropriate possible rule
nlist = [3,2,5,1]
wlist = ["Long", "life", "and", "prosper"]
print(max(nlist),min(nlist))
print(max(wlist),min(wlist))
dir
this function can be applied to any python object and returns a list of its attribute names.
We will use it several times to explore python objects
print(dir(1))
print(dir(dir))
help
python has a built-in portable documentation available directly from the command line!
help(dir)