Python Tutorial: a few built-in basic functions

jonathan-borba-xRDuEeG1TVI-unsplash-scaled.jpg Photo by Jonathan Borba on Unsplash functions or procedures are python code executed using the familiar mathematical syntax
launch_rocket(300000,"Moon")
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 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

print

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 float and accepts an optional second argument with the number of decimal digit, if this argument is omitted it returns an integer print(round(3.1419)) print(round(3.1419, 3))

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)

marco.p.v.vezzoli

Self taught assembler programming at 11 on my C64 (1983). Never stopped since then -- always looking up for curious things in the software development, data science and AI. Linux and FOSS user since 1994. MSc in physics in 1996. Working in large semiconductor companies since 1997 (STM, Micron) developing analytics and full stack web infrastructures, microservices, ML solutions

You may also like...