0

What is the difference between import math and from math import if the two resolve the same problem?

from math import sqrt 
    
    x=4
    a=4
    b=4
    
    if x==1:
        c=a+b 
    elif x==2:
        c=a*b
    elif x==3:
        c=pow(a,2)
    elif x==4:
        c=sqrt(b)
    else:    
        print('Error')

Or

import math

x=3
a=4
b=4

if x==1:
    c=a+b 
elif x==2:
    c=a*b
elif x==3:
    c=pow(a,2)
elif x==4:
    c= math.sqrt(b)
else:    
    print('Error')

My teacher told me use the first example, that's always the way to do it.

I see in the second example we are importing the class math I know is a class because I need to call the class first math.sqrt(), in the first example is not a necessity to call it, I suppose is not a class or is sort of a static class thing.

1 Answers1

0

The only difference is convenience and nothing else.

Import aliases/unrolling is just namespace thing. There's no difference in performance or footprint.

What's working for your code style – the better

Slam
  • 8,112
  • 1
  • 36
  • 44