Modules in Python
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module:-
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module:-
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)Python Datetime:-
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)Date Output:-
When we execute the code from the example above the result will be:
2020-08-13 12:30:24.912671The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Example
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))A reference of all the legal format codes:
| Directive | Description | Example | |
|---|---|---|---|
| %a | Weekday, short version | Wed | |
| %A | Weekday, full version | Wednesday | |
| %w | Weekday as a number 0-6, 0 is Sunday | 3 | |
| %d | Day of month 01-31 | 31 | |
| %b | Month name, short version | Dec | |
| %B | Month name, full version | December | |
| %m | Month as a number 01-12 | 12 | |
| %y | Year, short version, without century | 18 | |
| %Y | Year, full version | 2018 | |
| %H | Hour 00-23 | 17 | |
| %I | Hour 00-12 | 05 | |
| %p | AM/PM | PM | |
| %M | Minute 00-59 | 41 | |
| %S | Second 00-59 | 08 | |
| %f | Microsecond 000000-999999 | 548513 | |
| %z | UTC offset | +0100 | |
| %Z | Timezone | CST | |
| %j | Day number of year 001-366 | 365 | |
| %U | Week number of year, Sunday as the first day of week, 00-53 | 52 | |
| %W | Week number of year, Monday as the first day of week, 00-53 | 52 | |
| %c | Local version of date and time | Mon Dec 31 17:41:00 2018 | |
| %x | Local version of date | 12/31/18 | |
| %X | Local version of time | 17:41:00 | |
| %% | A % character | % |
Python Math:-
Built-in Math Functions:-
The min() and max() functions can be used to find the lowest or highest value in an iterable:
Example
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)abs() function returns the absolute (positive) value of the specified number:x = abs(-7.25)
print(x)pow(x, y) function returns the value of x to the power of y (xy).Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)The Math Module
Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import mathWhen you have imported the math module, you can start using methods and constants of the module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math
x = math.sqrt(64)
print(x)math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:Example
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1math.pi constant, returns the value of PI (3.14...):Example
import math
x = math.pi
print(x)Python JSON:-
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
Example
Import the json module:
import jsonParse JSON - Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads() method.
The result will be a Python dictionary.
Example
Convert from JSON to Python:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])Convert from Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Example
Convert from Python to JSON:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Comments
Post a Comment
Please do not enter any spam link in the comment box.