Import and more

--Originally published at Fundamentos de Programación

Like I mentioned in my previous post, pyhton has already build in functions that you can easily use without the need of importing modules like this ones:

build func

The output will be 25, 10 and -12.

But you may try to use some functions that aren’t in your file just yet, like the function sqrt()

sqrt

But then this will happen:

sqrt error

And you may feel like:

vmvnmam_700w_0

But don’t worry my sweet child, there is a solution for that.

By importing modules you will be able to use the functions that are contained in that module. You can import in different ways in python:

  1. import module.nameimport 1
  2. from math import sqrt import 2
  3. from math import sqrt as square_root import 3

 

In the first case you import the whole module and can call any function within using math.name_of_the_function

On the second and third case we only import a specific function, the difference is that in the third case we are able to change the name of the function using “as” and as a result we only need to write the name you assigned with no need to put “math.”

sqrt dif

Both of them work in the same way even thou they have different names!

pm0zodl_700wa_0

Also, to know what items are avaliable within a module you can just use “dir(module)” and this will show you the name of the functions:

math dir

omjmg5w_700wa_0

If you have no idea what those functions do you can use instead “help(module)” and this will display a help menu with the explanations of all the functions. SO COOL!

math help

brk4gd2_700wa_0

Mastery topics:

Calling funcions

Importing and using modules/libraries

If you want  the list of all python modules you can check them out at: https://docs.python.org/3/py-modindex.html

#import #tc101 #python

source: http://www.sololearn.com/Play/Python