CodeBlanks Logo Icon CodeBlanks

Summary - Modules

Combine import, from and the standard library to write a random number game.

Summary - Modules

In this group you learned five core concepts:

  • import — loads a module, accessed with a dot
  • from import — takes a specific item
  • as — gives a module a short name
  • __name__ == '__main__' — direct execution condition
  • Standard library — math, random, datetime, statistics

Now you will do two short tasks that combine them: one with import and from import together, one with a __name__ block and a function.

Practice import and from import together

Write import math. Then write from math import pi. Then write print(math.sqrt(16), pi).

Starter code

main.py
# load math with import
# take pi with from import
# print both together

Sample solution

main.py
import math
from math import pi
print(math.sqrt(16), pi)

Expected output

4.0 3.141592653589793

Practice Function with __name__ block

Define def topla(a, b): with return a + b in the body. Then inside an if __name__ == '__main__': block write print(topla(2, 3)).

Starter code

main.py
# define the topla function
# call and print inside the __name__ block

Sample solution

main.py
def topla(a, b):
    return a + b

if __name__ == '__main__':
    print(topla(2, 3))

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which statement is wrong?

  • import math as m keeps the math name Correct answer
  • from math import sqrt takes only sqrt
  • import math loads the math module
  • from math import * is dangerous

Explanation: import math as m replaces the math name with m; math is no longer available.

2 Match module concepts

Term Meaning
import Loads a module
from import Takes an item
as Gives an alias
__name__ Direct execution condition

All lessons in Beginner