8.1 Libraries


Libraries are collections of methods that you can use when you're programming. Libraries are Python code that serves a certain function. For example, let's say you want a random number generator. You import the random module, and then you can use it to get random numbers by calling methods from it:
  • First, import the random module: import random
  • Then, call a method from the random module: random.randrange(1, 10)
  • This gives us a random number between 1 and 10 (exclusive), as those are the arguments we passed in
# import the random module import random # returns a random number between 1 and 10 (exclusive) number = random.randrange(1, 10) print(number)
View code on GitHub.
random.randint(a, b) is the same as random.randrange(a, b), except that b is inclusive for randint

Different Ways to Import

# import the entire module import module_name # import the module and refer to it as a different name # in your code # (typically, it's a shortened name) # this is called aliasing a module import module_name as shortened_name # from a certain module, import only a certain class, # variable, or method from module_name import thing_in_module # wildcard (*) import - imports everything in that module from module_name import *
When importing using the syntax from module_name import thing_in_module, you can simply access the imported thing with the syntax thing_in_module, instead of module_name.thing_in_module. However, you must access the imported thing with module_name.thing_in_module for the 1st and 2nd way of importing shown above.
View code on GitHub.



Import the random module. Store a random secret number in a variable called secret_number (use randrange or randint). The secret number should be from 1 to 20 (inclusive). Ask the user to keep guessing the number until they get it right. You might want to print messages to tell the user if they guessed right or wrong

Previous Level


Next Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.