Home Backend Development Python Tutorial Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates

Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates

Sep 07, 2024 pm 02:30 PM

Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates

Es ist Tag Nr. 14 und ich bin wieder da, wo ich meine einfachen Python-Projekte zurückgelassen habe, bevor ich zum Flask gelaufen bin. Lol! Codieren kann aufregend und manchmal auch frustrierend sein (oder ist es meistens ...). Wie auch immer, Sie wissen es durch Ihre Erfahrungen besser. Deshalb freue ich mich darauf, meine zu dokumentieren. Heute habe ich Python-Module, Polymorphismus, JSON, Mathematik, Datetime, Scope und Iteratoren gelernt. Lass uns eintauchen.

1. Python-Module: Erstellen wiederverwendbarer Codebibliotheken

Module in Python sind Dateien, die Python-Code (Funktionen, Variablen oder Klassen) enthalten, der in verschiedenen Skripten oder Projekten wiederverwendet werden kann. Das Erstellen von Modulen fördert die Wiederverwendung von Code und macht Ihre Projekte sauberer und modularer.

Module erstellen und importieren:

Ein Modul ist einfach eine Python-Datei, die mit der Erweiterung .py gespeichert wird. Sie können Funktionen, Variablen und Klassen in einem Modul definieren und in ein anderes importieren.

Beispiel: Erstellen und Verwenden eines Moduls

  1. Erstellen Sie eine Datei namens mymodule.py mit folgendem Inhalt:
# mymodule.py
def greeting(name):
    print(f"Hello, {name}")
Copy after login
  1. Importieren Sie nun das Modul in ein anderes Python-Skript:
import mymodule

mymodule.greeting("Jonathan")  # Output: Hello, Jonathan
Copy after login

Sie können einem Modul beim Importieren auch einen Alias ​​zuweisen:

import mymodule as mx

mx.greeting("Jane")  # Output: Hello, Jane
Copy after login

Verwendung integrierter Module:

Python verfügt über viele integrierte Module. Sie können beispielsweise das Plattformmodul verwenden, um Systeminformationen abzurufen:

import platform

print(platform.system())  # Output: The OS you're running (e.g., Windows, Linux, etc.)
Copy after login

2. Arbeiten mit JSON in Python: Parsen und Generieren von JSON-Daten

JSON (JavaScript Object Notation) wird häufig zur Datenübertragung in Webanwendungen verwendet. Python stellt das JSON-Modul zum Parsen und Generieren von JSON bereit.

JSON analysieren:

Sie können einen JSON-String mit json.loads() in ein Python-Wörterbuch konvertieren.

import json

json_data = '{ "name": "John", "age": 30, "city": "New York" }'
parsed_data = json.loads(json_data)

print(parsed_data['age'])  # Output: 30
Copy after login

Konvertieren von Python-Objekten in JSON:

Sie können Python-Objekte (z. B. Diktat, Liste, Tupel) auch mit json.dumps() in einen JSON-String konvertieren.

Beispiel:

import json

python_obj = {"name": "John", "age": 30, "city": "New York"}
json_string = json.dumps(python_obj)

print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}
Copy after login

JSON-Ausgabe formatieren und anpassen:

Sie können die JSON-Zeichenfolge besser lesbar machen, indem Sie den Parameter „indent“ verwenden:

json_string = json.dumps(python_obj, indent=4)
print(json_string)
Copy after login

Dies gibt eine gut formatierte JSON-Zeichenfolge aus:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}
Copy after login

3. Python Math: Mathematische Operationen durchführen

Python bietet sowohl integrierte Funktionen als auch das Mathematikmodul zur Ausführung einer Vielzahl mathematischer Aufgaben.

Grundlegende mathematische Funktionen:

min() und max(): So finden Sie die Minimal- und Maximalwerte in einer Iteration:

print(min(5, 10, 25))  # Output: 5
print(max(5, 10, 25))  # Output: 25
Copy after login

abs(): Gibt den absoluten Wert einer Zahl zurück:

print(abs(-7.25))  # Output: 7.25
Copy after login

pow(): Berechnet die Potenz einer Zahl:

print(pow(4, 3))  # Output: 64 (4 to the power of 3)
Copy after login

Das Mathematikmodul:

Für fortgeschrittene mathematische Operationen bietet das Mathematikmodul einen umfangreichen Funktionsumfang.

  • Quadratwurzel: Mit math.sqrt():
import math

print(math.sqrt(64))  # Output: 8.0
Copy after login
  • Decke und Boden: Rundet eine Zahl auf oder ab:
print(math.ceil(1.4))  # Output: 2
print(math.floor(1.4))  # Output: 1
Copy after login
  • PI-Konstante: Zugriff auf den Wert von π:
print(math.pi)  # Output: 3.141592653589793
Copy after login

4. Arbeiten mit Datumsangaben: Zeitverwaltung in Python

Das Datetime-Modul von Python hilft bei der Verwaltung von Datums- und Uhrzeitangaben. Sie können das aktuelle Datum generieren, bestimmte Komponenten (wie Jahr, Monat, Tag) extrahieren oder Datumsobjekte bearbeiten.

Abrufen des aktuellen Datums und der aktuellen Uhrzeit:

Die Funktion datetime.now() gibt das aktuelle Datum und die aktuelle Uhrzeit zurück.

import datetime

current_time = datetime.datetime.now()
print(current_time)
# Output: 2024-09-06 05:15:51.590708 (example)
Copy after login

Ein bestimmtes Datum erstellen:

Sie können ein benutzerdefiniertes Datum mit dem datetime()-Konstruktor erstellen.

custom_date = datetime.datetime(2020, 5, 17)
print(custom_date)  # Output: 2020-05-17 00:00:00
Copy after login

Datumsangaben mit strftime() formatieren:

Sie können Datumsobjekte mit strftime() in Zeichenfolgen formatieren.

Beispiel:

formatted_date = custom_date.strftime("%B %d, %Y")
print(formatted_date)  # Output: May 17, 2020
Copy after login

Hier ist eine Tabelle mit einigen gängigen Formatcodes, die in strftime() verwendet werden:

Directive Description Example
%a Short weekday Wed
%A Full weekday Wednesday
%b Short month name Dec
%B Full month name December
%Y Year (full) 2024
%H Hour (24-hour format) 17
%I Hour (12-hour format) 05

Polymorphism in Python

Polymorphism refers to the ability of different objects to be treated as instances of the same class through a common interface. It allows methods to do different things based on the object it is acting upon.

Method Overriding
In Python, polymorphism is often achieved through method overriding. A subclass can provide a specific implementation of a method that is already defined in its superclass.

Example:

class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# Using polymorphism
def animal_sound(animal):
    print(animal.make_sound())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!
Copy after login

In the above example, animal_sound() can handle both Dog and Cat objects because they both implement the make_sound() method, demonstrating polymorphism.

Operator Overloading

Polymorphism also allows you to define how operators behave with user-defined classes by overloading them.

Example:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 1)
v3 = v1 + v2

print(v3)  # Output: Vector(6, 4)
Here, the + operator is overloaded to handle Vector objects, allowing us to add vectors using the + operator.

2. Iterators in Python
An iterator is an object that allows you to traverse through a container, such as a list or tuple, and retrieve elements one by one. Python iterators implement two main methods: __iter__() and __next__().

Creating an Iterator
You can create your own iterator by defining a class with __iter__() and __next__() methods.

Example:

python
Copy code
class CountDown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        current = self.start
        self.start -= 1
        return current

# Using the iterator

cd = CountDown(5)
for number in cd:
    print(number)
# Output: 5, 4, 3, 2, 1
Copy after login

In this example, CountDown is an iterator that counts down from a starting number to 1.

Using Built-in Iterators
Python provides built-in iterators such as enumerate(), map(), and filter().

Example:

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)

for num in squared:
    print(num)
# Output: 1, 4, 9, 16, 25
Copy after login

Here, map() applies a function to all items in the list and returns an iterator.

Scope in Python

Scope determines the visibility of variables in different parts of the code. Python uses the LEGB rule to resolve names: Local, Enclosing, Global, and Built-in.

Local Scope

Variables created inside a function are local to that function.

Example:

def my_func():
    x = 10  # Local variable
    print(x)

my_func()
# Output: 10
Copy after login

Here, x is accessible only within my_func().

Global Scope

Variables created outside any function are global and accessible from anywhere in the code.

Example:

Copy code
x = 20  # Global variable

def my_func():
    print(x)

my_func()
print(x)
# Output: 20, 20
Copy after login

Enclosing Scope

In nested functions, an inner function can access variables from its enclosing (outer) function.

Example:

def outer_func():
    x = 30

    def inner_func():
        print(x)  # Accessing variable from outer function

    inner_func()

outer_func()
# Output: 30
Copy after login

Global Keyword

To modify a global variable inside a function, use the global keyword.

Example:

x = 50

def my_func():
    global x
    x = 60

my_func()
print(x)
# Output: 60
Copy after login

Nonlocal Keyword

The nonlocal keyword allows you to modify a variable in the nearest enclosing scope that is not global.

Example:

def outer_func():
    x = 70

    def inner_func():
        nonlocal x
        x = 80

    inner_func()
    print(x)

outer_func()
# Output: 80
Copy after login

In this example, nonlocal allows inner_func() to modify the x variable in outer_func().

Check out my #100daysofMiva repo on GitHub. Follow, Star and Share.

The above is the detailed content of Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles