Have you ever heard someone say Python has batteries included? Have you wondered what the heck that means? Well, I can explain.
Screw creating your own modules all the time, Python has standard ones built in! These standard modules let you find files, tell/count time, and much more. Remember everything we used with the import function? All of those are modules. The standard ones are the ones we never created in a different program! Should there be something you want to do that isn't a standard module, you should be able to find a download for them, hopefully for free (if you do that, be very careful, as it could be a virus or have viruses attached). So, what standard modules have we been using? Well, up until this point, you never knew you were doing the things in this article all along. The standard modules we know about so far are time and random.
We already talked about time and random and how to use them, but there's a little more. With time.sleep(), you can make the program do nothing for a certain amount of time. There's a faster way to do it, though.
from time import sleep
When you type that, it will make things a little faster to type, like this.
sleep(5)
We do sleep(5) instead of time.sleep(5). We can do that because we imported sleep from time.
There's also another thing to talk about with random. We all know about random.randint, the function we used in the fortune teller program, the multiplication one, and so on. We all know how random.randint works, but there's something else: random.random().
random.random() will give you a random number between 0 and 1. Try it!
>>> import random
>>> print(random.random())
0.19406666194760636
If you want a number that isn't between 0 and 1, you can multiply the answer. Let's try getting a number between 0 and 10.
>>> print(random.random() * 10)
8.2903170046567
If you don't want a super specific float, you can use the int() function or the round() function, like this.
>>> print(int(random.random() * 10))
8
The int function took our number and turned it into an integer!
In this article, you learned about importing from a module, and random.random(). I challenge you to go to one of the old programs and change it with these methods!
No comments:
Post a Comment