What I learnt
- Built-in modules
- importing builtin modules
- using the datetime module
Built-in modules
The Python Built-in Modules are a set of pre-installed modules that come with Python.
Example of built-in modules
- Using the random module This module implements pseudo-random number generators for various distributions. It is used to generate random numbers for various purposes like generating a random password, selecting a random item from a list, etc.
# import random
data = [1, 2, 3, 4, 5, 6, 7]
print(random.random())
# Output: 0.123456789 (randomly selected float between 0 and 1)
print(random.randint(1, 10))
# Output: 5 (randomly selected integer between 1 and 10)
print(random.choice(data)) # Output: 4 (randomly selected from the list)
- Using the datetime module The datetime module provides a set of classes to work with dates and times. It is used to get the current date and time, add or subtract days, months, or years, etc.
from datetime import date, datetime
today = date.today()
tomorrow = date.today() + date.resolution
yesterday = date.today() - date.resolution
print("Today's date is:", today) # Output: Today's date is: 2023-02-17
print("Tomorrow's date is:", tomorrow) # Output: Tomorrow's date is: 2023-02-18
print("Yesterday's date:", yesterday)
# Output: Yesterday's date: 2023-02-16
Exercise
- 1. Using the datetime module, print the current time and date. Hint: Use the datetime module and the now() method.
from datetime import datetime, date
today_time = datetime.now()
current_time = today_time.strftime('%H:%M:%S') # 24 hour format
current_date = date.today()
print(f'Today\'s is {current_date} and the time is {current_time}')
print(current_time)
print(current_date)
- Using the time module
Exercise
- 2. Using the time module, create a clock that prints the current time every second.
import time
while True:
localtime = time.localtime()
result = time.strftime("%I:%M:%S %p", localtime) # the strftime() method takes two arguments, the format and the time object to format and returns a string representing the time.
print(result)
time.sleep(1)
- Using the argv in sys module
The argv module is used to get the command line arguments passed to a script.
It is also good to note that the first argument is the name of the script.
i.e. the first argument is the name of the script and the second argument is the first command line argument.
import sys
print(sys.argv) # Output: ['built_in_modules.py']
Exercise
Using the argv module, create a script that takes two arguments and prints the sum of the two numbers.
num_1 = int(sys.argv[1])
num_2 = int(sys.argv[2])
sum = (num_1 + num_2)
print(sum)
- Using the os module The os module provides a way of using operating system dependent functionality.
print(os.getcwd()) # This method returns the current working directory.
Exercise
- 3. Using the os module, create a script that creates a new directory inside the current directory and also rename a file in the current directory.
os.mkdir('new_dir') # This method creates a new directory.
os.rename('new_dir', 'new_dir_2') # This method renames a file or directory.
Exercise
'''
You have been tasked to create a random number guessing game.
The game should generate a random number between 1 and 20 (inclusive).
Instructions:
- Ask user to pick range of numbers (min and max)
- Generate a random number between the min and max then store it in a variable
- Ask user to guess a number
- Compare user's guess to the random number generated
- If user guesses correctly, print "You win!"
- If user guesses incorrectly, print "You lose!"
'''
import sys
import random
try:
min_number = int(sys.argv[1])
max_number = int(sys.argv[2])
if max_number <= min_number:
print('Sorry, your maximum number must be higher than your minimum number')
if min_number < 1:
print('The minimum number you can enter should be 1')
if max_number >= 21:
print('The maximum number you can enter should be 20')
print(
f'Hello and welcome to our game \n You numbers will be generated between {min_number} and { max_number}')
while True:
try:
user_input = int(
input(f'Pick a number between {min_number} and {max_number} \n >>>'))
# Generate a random int
computer_guess = random.randrange(min_number, max_number, 1)
# Compare User input to computer guess
if computer_guess == user_input:
print('You are rock! ๐ค๐พ')
break
elif (user_input < min_number):
print('Your number choice is too small!')
elif (user_input > max_number):
print('Your number choice is too high!')
except ValueError:
print('Only numbers are allowed!')
else:
print('Incorrect guess, please try again!๐')
except ValueError:
# Handle invalid input
print('Only numbers are allowed')
Conclusion
This article is a continuation of my Day 8-Python Modules and Packages article.
In this article, we learnt about the built-in modules in Python. We also learnt how to import and use the built-in modules. This is a very important concept in Python and it is good to know how to use the built-in modules.
Resources
If you found this article helpful, please leave a comment and share with your friends.
Top comments (0)