0

Currently I am learning Python (not programming) and I am trying to solve my first problem with this language.

First of all I have checked what is the difference between import X and from X import Y. I know that the first load into the namespace the package but not the methods of this package, so you need to write X.Y, on the other hand the second import way load into the namespace the function and the reference to the package. Despite this I do not understand why import math.sqrt fails. I get this error: math is not a package.

Does anybody knows what happens?

Then I am trying how is write this statement:

sum([
     pow(dic1[elem]–dic2[elem], 2)
     for elem in dic1 if elem in dic2 
    ])

As I told before I know programming and I understand what it is doing, but it seems a bit illogical for me because seems that python reads the script in different direction than the "typical" languages.

If I am not wrong this statement sum all the differences between elements in both dictionaries (powered 2) but only do the sum if it does the for statement which is conditioned that in dic2 exists elem.

Is this correct?

Thank you!

mrc
  • 2,845
  • 8
  • 39
  • 73
  • See http://stackoverflow.com/q/16341775/476. If you'd be asking one question at a time as you should be, we could be crossing that off as a duplicate already. – deceze Mar 03 '17 at 16:41
  • Try `import math; math.__file__` vs. `import xml; xml.__file__`. `math` is implemented in C, not Python, and may have different import behavior because of this. – Scott Colby Mar 03 '17 at 17:27

1 Answers1

1

For your first question, try:

from math import sqrt

Onto your second question, yes, python does seem to do things in an odd order if you are coming from other languages. For example:

x=1 if a=2 else 0

this is the same as saying:

if a=2:
    x=1
else:
    x=0

and if you do this:

x=[i*2 for i in [1,2,3,4]]

it means make a variable i for every element in the list [1,2,3,4], multiply it by 2 and create a new list form the results. So in the above example x would be:

[2,4,6,8]

Basically, you'll get used to it.

heroworkshop
  • 365
  • 2
  • 6
  • Thanks for your answer. The first works, but I would like to understand the reason what import math fails. Your second answer is perfect! Thank you! – mrc Mar 03 '17 at 18:24