Unit 3 Sections 14 and 15
Hacks on sections 14 and 15
- In your own words, what is a library?
- A library is a collection of pre-written code that provides commonly-used functionality that can be easily incorporated into a program.
-
Why are libraries useful when writing a program?
- Libraries are useful when writing a program because they provide pre-written code that can be easily incorporated into your own program, which saves time and effort.
-
What keyword is used to add a pre-made library?
- key word: import
import random
def main():
# Generate a random integer between 1 and 100
random_number = random.randint(1, 100)
# Print the random number
print(random_number)
if __name__ == '__main__':
main()
Hacks for lesson 3.15.1
-
Write a few lines of code that implements the import function
-
Define what an import random function do
- the import random function defines a series of functions for generating or manipulating random integers
- List a few other things that we can import other than random
- math
- flask
- os
- sys
- datetime
import math
# Use the sqrt function from the math module
result = math.sqrt(300)
print(result)
I am using the import statement to access the math module, which provides us with functions for doing math. Then, we use the math.sqrt() function to find the square root of 16 and print the result to the console.
Hacks 3.15.2
-
For your hacks you need to create a random number generator that will simulate this situation:
-
There is a spinner divided into eight equal parts. 3 parts of the spinner are green, two parts are blue, one part is purple, one part is red, and one part is orange. How can you simulate this situation using a random number generator.
import random
# create a list of colors and their probabilities
colors = ["green", "green", "green", "blue", "blue", "purple", "red", "orange"]
# use the random.choices() function to generate a random color
color = random.choices(colors, weights=None, cum_weights=None, k=1)
# print the selected color
print(color)
- Also answer this question: What numbers can be outputted from RANDOM(12,20) and what numbers are excluded?
- The RANDOM function is a function in some programming languages (such as Excel and Google Sheets) that generates a random number between a given range of values. In the case of RANDOM(12, 20), the function will generate a random number between 12 and 20, inclusive.
Answer: The RANDOM(12, 20) function will generate a random number between 12 and 20, inclusive. This means that the possible numbers that can be outputted by the function are 12, 13, 14, 15, 16, 17, 18, 19, and 20. No other numbers outside of this range will be generated by the function.