Python je široko uporabljen programski jezik, ki ponuja več edinstvenih funkcij in prednosti v primerjavi z jeziki, kot je Java in C++. Naša vadnica za Python temeljito razloži osnove in napredne koncepte Pythona, začenši z namestitvijo, pogojne izjave , zanke , vgrajene podatkovne strukture , objektno orientirano programiranje , generatorji , obravnavanje izjem , Python RegEx in številni drugi koncepti. Ta vadnica je namenjena začetnikom in delujočim profesionalcem.
V poznih osemdesetih letih prejšnjega stoletja Guido van Rossum sanjal o razvoju Pythona. Prva različica Python 0.9.0 je bil izdan leta 1991 . Od izdaje je Python začel pridobivati na priljubljenosti. Glede na poročila je Python trenutno najbolj priljubljen programski jezik med razvijalci zaradi visokih zahtev na tehnološkem področju.
Kaj je Python
Python je splošno namenski, dinamično tipiziran, visokonivojski, preveden in interpretiran, ki zbira smeti in je izključno objektno usmerjen programski jezik, ki podpira proceduralno, objektno usmerjeno in funkcionalno programiranje.
Lastnosti Pythona:
Python jih ima veliko spletna sredstva , odprtokodnih projektov , in živahno skupnost . Učenje jezika, skupno delo na projektih in prispevanje k ekosistemu Python so za razvijalce zelo preprosti.
Zaradi preprostega jezikovnega okvira je Python lažje razumeti in vanj pisati kodo. Zaradi tega je fantastičen programski jezik za začetnike. Poleg tega pomaga izkušenim programerjem pri pisanju jasne kode brez napak.
Python ima veliko knjižnic tretjih oseb, ki jih je mogoče uporabiti za lažjo funkcionalnost. Te knjižnice pokrivajo številna področja, na primer spletni razvoj, znanstveno računalništvo, analizo podatkov in drugo.
Java proti Pythonu
Python je odlična izbira za hiter razvoj in skriptna opravila. Medtem ko Java poudarja močan tipski sistem in objektno usmerjeno programiranje.
Tukaj je nekaj osnovnih programov, ki ponazarjajo ključne razlike med njimi.
Tiskanje 'Hello World'
Koda Python:
print('Hello World)'
V Pythonu je to ena vrstica kode. Za tiskanje 'Hello World' je potrebna preprosta sintaksa
Java koda:
public class HelloWorld { public static void main(String[] args) { System.out.println('Hello, World!'); } }
V Javi moramo deklarirati razrede, strukture metod in veliko drugih stvari.
Medtem ko oba programa dajeta enak rezultat, lahko opazimo razliko v sintaksi v izjavi za tiskanje.
najdi moj iphone android
- V Pythonu se je enostavno naučiti in pisati kodo. Medtem ko je v Javi, zahteva več kode za izvajanje določenih nalog.
- Python je dinamično tipiziran, kar pomeni, da nam ni treba deklarirati spremenljivke, medtem ko je Java statistično tipizirana, kar pomeni, da moramo deklarirati tip spremenljivke.
- Python je primeren za različna področja, kot so podatkovna znanost, strojno učenje, spletni razvoj itd. Medtem ko je Java primerna za spletni razvoj, razvoj mobilnih aplikacij (Android) in drugo.
Osnovna sintaksa Python
V programskem jeziku Python ni uporabe zavitih oklepajev ali podpičja. Je angleščini podoben jezik. Toda Python uporablja zamik za definiranje bloka kode. Zamik ni nič drugega kot dodajanje presledka pred stavkom, ko je to potrebno.
Na primer -
def func(): statement 1 statement 2 ………………… ………………… statement N
V zgornjem primeru stavki, ki so na isti ravni desno, pripadajo funkciji. Na splošno lahko za določitev zamika uporabimo štiri presledke.
Namesto podpičja, kot se uporablja v drugih jezikih, Python konča svoje izjave z znakom NewLine.
Python je jezik, ki razlikuje velike in male črke, kar pomeni, da se velike in male črke obravnavajo drugače. Na primer, 'ime' in 'Ime' sta dve različni spremenljivki v Pythonu.
V Pythonu lahko komentarje dodate s simbolom '#'. Vsako besedilo, napisano za simbolom '#', se šteje za komentar in ga tolmač ignorira. Ta trik je uporaben za dodajanje opomb kodi ali začasno onemogočanje bloka kode. Pomaga tudi pri boljšem razumevanju kode s strani nekaterih drugih razvijalcev.
'če' , 'drugače', 'za' , 'medtem ko' , 'poskusi', 'razen' in 'končno' je nekaj rezerviranih ključnih besed v Pythonu, ki jih ni mogoče uporabiti kot imena spremenljivk. Ti izrazi se v jeziku uporabljajo iz posebnih razlogov in imajo ustaljene pomene. Če uporabljate te ključne besede, lahko vaša koda vključuje napake ali pa jih tolmač zavrne kot potencialne nove spremenljivke.
Zgodovina Pythona
Python je ustvaril Guido van Rossum . V poznih osemdesetih letih prejšnjega stoletja je Guido van Rossum, nizozemski programer, začel delati na Pythonu v Centrum Wiskunde & Informatica (CWI) na Nizozemskem. Želel je ustvariti naslednika Programski jezik ABC ki bi bilo lahko berljivo in učinkovito.
Februarja 1991 je bila izdana prva javna različica Pythona, različica 0.9.0. To je zaznamovalo uradno rojstvo Python kot odprtokodni projekt . Jezik je dobil ime po britanski humoristični seriji ' Leteči cirkus Montyja Pythona '.
Razvoj Pythona je šel skozi več stopenj. Januarja 1994 je bil Python 1.0 izdan kot uporaben in stabilen programski jezik. Ta različica je vključevala številne funkcije, ki so še danes prisotne v Pythonu.
Od 1990-ih do 2000-ih , je Python postal priljubljen zaradi svoje preprostosti, berljivosti in vsestranskosti. Oktobra 2000 je bil izdan Python 2.0 . Python 2.0 je uvedel razumevanje seznamov, zbiranje smeti in podporo za Unicode.
Decembra 2008 je bil izdan Python 3.0. Python 3.0 je uvedel več nazaj nezdružljivih sprememb za izboljšanje berljivosti in vzdrževanja kode.
Skozi leta 2010 se je priljubljenost Pythona povečala, zlasti na področjih, kot sta strojno učenje in spletni razvoj. Zaradi bogatega ekosistema knjižnic in ogrodij je postal priljubljen med razvijalci.
The Python Software Foundation (PSF) je bila ustanovljena leta 2001 za promocijo, zaščito in napredek programskega jezika Python in njegove skupnosti.
Zakaj se učiti Python?
Python programerju ponuja veliko uporabnih funkcij. Zaradi teh lastnosti je najbolj priljubljen in pogosto uporabljan jezik. Spodaj smo našteli nekaj bistvenih funkcij Pythona.
- Objektno usmerjeni jezik : Podpira objektno usmerjeno programiranje, kar olajša pisanje modularne kode za večkratno uporabo.
Kje se uporablja Python?
Python je splošni, priljubljen programski jezik in se uporablja na skoraj vseh tehničnih področjih. Spodaj so navedena različna področja uporabe Pythona.
- Umetna inteligenca : AI je tehnologija v vzponu in Python je popoln jezik za umetno inteligenco in strojno učenje zaradi razpoložljivosti zmogljivih knjižnic, kot so TensorFlow, Keras in PyTorch.
- DevOps : Python se pogosto uporablja v DevOps za avtomatizacijo in skriptiranje upravljanja infrastrukture, upravljanja konfiguracije in procesov uvajanja.
- Zahteve : knjižnica za izdelavo zahtev HTTP
- SQLAlchemy : knjižnica za delo z bazami podatkov SQL
- Obupana : ogrodje za izdelavo aplikacij z več dotiki
- Pygame : knjižnica za razvoj iger
- Ogrodje REST : komplet orodij za izdelavo RESTful API-jev
- FastAPI : sodobno, hitro spletno ogrodje za gradnjo API-jev
- Streamlit : knjižnica za izdelavo interaktivnih spletnih aplikacij za strojno učenje in podatkovno znanost
- NLTK : knjižnica za obdelavo naravnega jezika
Python ima širok nabor knjižnic in ogrodij, ki se pogosto uporabljajo na različnih področjih, kot so strojno učenje, umetna inteligenca, spletne aplikacije itd. Nekatera priljubljena ogrodja in knjižnice Pythona definiramo takole.
Funkcija Python print().
Funkcija Python print() se uporablja za prikaz izhoda na konzoli ali terminalu. Omogoča nam prikaz besedila, spremenljivk in drugih podatkov v človeku berljivi obliki.
Sintaksa:
print(object(s), sep=separator, end=end, file=file, flush=flush)
Vzame enega ali več argumentov, ločenih z vejico(,), in na koncu privzeto doda 'novo vrstico'.
Parametri:
- objekt(i) – kolikor želite podatkov za prikaz, bo najprej pretvorjeno v niz in natisnjeno na konzoli.
- sep – Loči objekte s posredovanim ločilom, privzeta vrednost = ' '.
- konec – konča vrstico z znakom za novo vrstico
- datoteka - predmet datoteke z metodo pisanja, privzeta vrednost = sys.stdout
primer:
# Displaying a string print('Hello, World!') # Displaying multiple values name = 'Aman' age = 21 print('Name:', name, 'Age:', age) # Printing variables and literals x = 5 y = 7 print('x =', x, 'y =', y, 'Sum =', x + y) # Printing with formatting percentage = 85.75 print('Score: {:.2f}%'.format(percentage))
Izhod:
Hello, World! Name: Aman Age: 21 X = 5 y = 7 Sum = 12 Score: 85.75%
V tem primeru se stavek za tiskanje uporablja za tiskanje nizov, celih števil in vrednosti s plavajočim v obliki, ki je berljiva za ljudi.
Stavek za tiskanje se lahko uporablja za odpravljanje napak, beleženje in zagotavljanje informacij uporabniku.
Pogojni stavki Python
Pogojni stavki nam pomagajo izvesti določen blok za določen pogoj. V tej vadnici se bomo naučili, kako uporabiti pogojni izraz za izvedbo drugega bloka stavkov. Python ponuja ključni besedi if in else za nastavitev logičnih pogojev. The Elif ključna beseda se uporablja tudi kot pogojni stavek.
Primer kode za stavek if..else
x = 10 y = 5 if x > y: print('x is greater than y') else: print('y is greater than or equal to x')
Izhod:
x is greater than y
V zgornji kodi imamo dve spremenljivki, x in y, z 10 oziroma 5. Nato smo uporabili stavek if..else, da preverimo, ali je x večji od y ali obratno. Če je prvi pogoj resničen, se izpiše stavek 'x je večji od y'. Če je prvi pogoj napačen, se namesto tega natisne stavek 'y je večji ali enak x'.
Ključna beseda if preveri, ali je pogoj resničen, in izvede blok kode v njem. Koda znotraj bloka else se izvede, če je pogoj napačen. Na ta način nam stavek if..else pomaga izvesti različne bloke kode glede na pogoj.
O tem bomo podrobneje izvedeli v nadaljnjem članku za vadnico Python.
Python Loops
Včasih bomo morda morali spremeniti potek programa. Izvedbo določene kode bo morda treba večkrat ponoviti. V ta namen programski jeziki ponujajo različne zanke, ki lahko večkrat ponovijo določeno kodo. Upoštevajte naslednjo vadnico, da boste podrobno razumeli izjave.
Python For Loop
fruits = ['apple', 'banana', 'cherry'] for x in fruits: print(x, end=' ')
Izhod:
apple banana cherry
Python While Loop
i = 1 while i<5: print(i, end=" " ) i +="1" < pre> <p> <strong>Output:</strong> </p> <pre> 1 2 3 4 </pre> <p>In the above example code, we have demonstrated using two types of loops in Python - For loop and While loop.</p> <p>The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be used to print a range of numbers.</p> <p>The While loop repeats a code block if the specified condition is true. In the example, we have initialized a variable i to 1 and used a while loop to print the value of i until it becomes greater than or equal to 6. The i += 1 statement is used to increment the value of i in each iteration.</p> <p>We will learn about them in the tutorial in detail.</p> <h2>Python Data Structures</h2> <p> <strong>Python offers four built-in data structures:</strong> <strong>lists</strong> , <strong>tuples</strong> , <strong>sets</strong> , and <strong>dictionaries</strong> that allow us to store data in an efficient way. Below are the commonly used data structures in Python, along with example code:</p> <h3>1. Lists </h3> <ul> <li>Lists are <strong>ordered collections</strong> of data elements of different data types.</li> <li>Lists are <strong>mutable</strong> meaning a list can be modified anytime.</li> <li>Elements can be <strong>accessed using indices</strong> .</li> <li>They are defined using square bracket ' <strong>[]</strong> '.</li> </ul> <p> <strong>Example:</strong> </p> <pre> # Create a list fruits = ['apple', 'banana', 'cherry'] print('fuirts[1] =', fruits[1]) # Modify list fruits.append('orange') print('fruits =', fruits) num_list = [1, 2, 3, 4, 5] # Calculate sum sum_nums = sum(num_list) print('sum_nums =', sum_nums) </pre> <p> <strong>Output:</strong> </p> <pre> fuirts[1] = banana fruits = ['apple', 'banana', 'cherry', 'orange'] sum_nums = 15 </pre> <h3>2. Tuples </h3> <ul> <li>Tuples are also <strong>ordered collections</strong> of data elements of different data types, similar to Lists.</li> <li>Elements can be <strong>accessed using indices</strong> .</li> <li>Tuples are <strong>immutable</strong> meaning Tuples can't be modified once created.</li> <li>They are defined using open bracket ' <strong>()</strong> '.</li> </ul> <p> <strong>Example:</strong> </p> <pre> # Create a tuple point = (3, 4) x, y = point print('(x, y) =', x, y) # Create another tuple tuple_ = ('apple', 'banana', 'cherry', 'orange') print('Tuple =', tuple_) </pre> <p> <strong>Output:</strong> </p> <pre> (x, y) = 3 4 Tuple = ('apple', 'banana', 'cherry', 'orange') </pre> <h3>3. Sets </h3> <ul> <li>Sets are <strong>unordered</strong> collections of immutable data elements of different data types.</li> <li>Sets are <strong>mutable</strong> .</li> <li>Elements can't be accessed using indices.</li> <li>Sets <strong>do not contain duplicate elements</strong> .</li> <li>They are defined using curly braces ' <strong>{}</strong> '</li> </ul> <p> <strong>Example:</strong> </p> <pre> # Create a set set1 = {1, 2, 2, 1, 3, 4} print('set1 =', set1) # Create another set set2 = {'apple', 'banana', 'cherry', 'apple', 'orange'} print('set2 =', set2) </pre> <p> <strong>Output:</strong> </p> <pre> set1 = {1, 2, 3, 4} set2 = {'apple', 'cherry', 'orange', 'banana'} </pre> <h3>4. Dictionaries </h3> <ul> <li>Dictionary are <strong>key-value pairs</strong> that allow you to associate values with unique keys.</li> <li>They are defined using curly braces ' <strong>{}</strong> ' with key-value pairs <strong>separated by colons ':'</strong> .</li> <li>Dictionaries are <strong>mutable</strong> .</li> <li>Elements can be accessed using keys.</li> </ul> <p> <strong>Example:</strong> </p> <pre> # Create a dictionary person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'} print('person =', person) print(person['name']) # Modify Dictionary person['age'] = 27 print('person =', person) </pre> <p> <strong>Output:</strong> </p> <pre> person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'} Umesh person = {'name': 'Umesh', 'age': 27, 'city': 'Noida'} </pre> <p>These are just a few examples of Python's built-in data structures. Each data structure has its own characteristics and use cases.</p> <h2>Python Functional Programming</h2> <p>This section of the Python tutorial defines some important tools related to functional programming, such as lambda and recursive functions. These functions are very efficient in accomplishing complex tasks. We define a few important functions, such as reduce, map, and filter. Python provides the functools module that includes various functional programming tools. Visit the following tutorial to learn more about functional programming.</p> <p>Recent versions of Python have introduced features that make functional programming more concise and expressive. For example, the 'walrus operator':= allows for inline variable assignment in expressions, which can be useful when working with nested function calls or list comprehensions.</p> <h2>Python Function</h2> <ol class="points"> <li> <strong>Lambda Function</strong> - A lambda function is a small, <strong>anonymous function</strong> that can take any number of arguments but can only have one expression. Lambda functions are often used in functional programming to create functions 'on the fly' without defining a named function.</li> <li> <strong>Recursive Function</strong> - A recursive function is a function that calls itself to solve a problem. Recursive functions are often used in functional programming to perform complex computations or to traverse complex data structures.</li> <li> <a href="/python-map-function"> <strong>Map Function</strong> </a> - The map() function applies a given function to each item of an iterable and returns a new iterable with the results. The input iterable can be a list, tuple, or other.</li> <li> <a href="/python-filter-function"> <strong>Filter Function</strong> </a> - The filter() function returns an iterator from an iterable for which the function passed as the first argument returns True. It filters out the items from an iterable that do not meet the given condition.</li> <li> <a href="/reduce-python"> <strong>Reduce Function</strong> </a> - The reduce() function applies a function of two arguments cumulatively to the items of an iterable from left to right to reduce it to a single value.</li> <li> <strong>functools Module</strong> - The functools module in Python provides higher-order functions that operate on other functions, such as partial() and reduce().</li> <li> <strong>Currying Function</strong> - A currying function is a function that takes multiple arguments and returns a sequence of functions that each take a single argument.</li> <li> <strong>Memoization Function</strong> - Memoization is a technique used in functional programming to cache the results of expensive function calls and return the cached Result when the same inputs occur again.</li> <li> <strong>Threading Function</strong> - Threading is a technique used in functional programming to run multiple tasks simultaneously to make the code more efficient and faster.</li> </ol> <h2>Python Modules</h2> <p> Python modules are the program files that contain Python code or functions. Python has two types of modules - User-defined modules and built-in modules. A module the user defines, or our Python code saved with .py extension, is treated as a user-define module.</p> <p>Built-in modules are predefined modules of Python. To use the functionality of the modules, we need to import them into our current working program.</p> <p>Python modules are essential to the language's ecosystem since they offer reusable code and functionality that can be imported into any Python program. Here are a few examples of several Python modules, along with a brief description of each:</p> <p> <strong>Math</strong> : Gives users access to mathematical constants and pi and trigonometric functions.</p> <p> <strong>Datetime</strong> : Provides classes for a simpler way of manipulating dates, times, and periods.</p> <p> <a href="/python-os-module"> <strong>OS</strong> </a> : Enables interaction with the base operating system, including administration of processes and file system activities.</p> <p> <a href="/python-random-module"> <strong>Random</strong> </a> : The random function offers tools for generating random integers and picking random items from a list.</p> <p> <strong>JSON</strong> : JSON is a data structure that can be encoded and decoded and is frequently used in online APIs and data exchange. This module allows dealing with JSON. <br> <strong>Re</strong> : Supports regular expressions, a potent text-search and text-manipulation tool.</p> <p> <strong>Collections</strong> : Provides alternative data structures such as sorted dictionaries, default dictionaries, and named tuples.</p> <p> <strong>NumPy</strong> : NumPy is a core toolkit for scientific computing that supports numerical operations on arrays and matrices.</p> <p> <strong>Pandas</strong> : It provides high-level data structures and operations for dealing with time series and other structured data types.</p> <p> <strong>Requests</strong> : Offers a simple user interface for web APIs and performs HTTP requests.</p> <h2>Python File I/O</h2> <p>Files are used to store data in a computer disk. In this tutorial, we explain the built-in file object of Python. We can open a file using Python script and perform various operations such as writing, reading, and appending. There are various ways of opening a file. We are explained with the relevant example. We will also learn to perform read/write operations on binary files.</p> <p> <strong>Python's file input/output (I/O) system</strong> offers programs to communicate with files stored on a disc. Python's built-in methods for the file object let us carry out actions like reading, writing, and adding data to files.</p> <p>The <strong>open()</strong> method in Python makes a file object when working with files. The name of the file to be opened and the mode in which the file is to be opened are the two parameters required by this function. The mode can be used according to work that needs to be done with the file, such as ' <strong>r</strong> ' for reading, ' <strong>w</strong> ' for writing, or ' <strong>a</strong> ' for attaching.</p> <p>After successfully creating an object, different methods can be used according to our work. If we want to write in the file, we can use the write() functions, and if you want to read and write both, then we can use the append() function and, in cases where we only want to read the content of the file we can use read() function. Binary files containing data in a binary rather than a text format may also be worked with using Python. Binary files are written in a manner that humans cannot directly understand. The <strong>rb</strong> and <strong>wb</strong> modes can read and write binary data in binary files.</p> <h2>Python Exceptions</h2> <p>An exception can be defined as an unusual condition in a program resulting in an interruption in the flow of the program.</p> <p>Whenever an exception occurs, the program stops the execution, and thus the other code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error.</p> <p> <strong>Python Exceptions</strong> are an important aspect of error handling in Python programming. When a program encounters an unexpected situation or error, it may raise an exception, which can interrupt the normal flow of the program.</p> <p>In Python, exceptions are represented as objects containing information about the error, including its type and message. The most common type of Exception in Python is the Exception class, a base class for all other built-in exceptions.</p> <p>To handle exceptions in Python, we use the <strong>try</strong> and <strong>except</strong> statements. The <strong>try</strong> statement is used to enclose the code that may raise an exception, while the <strong>except</strong> statement is used to define a block of code that should be executed when an exception occurs.</p> <p> <strong>For example, consider the following code:</strong> </p> <pre> try: x = int ( input ('Enter a number: ')) y = 10 / x print ('Result:', y) except ZeroDivisionError: print ('Error: Division by zero') except ValueError: print ('Error: Invalid input') </pre> <p> <strong>Output:</strong> </p> <pre> Enter a number: 0 Error: Division by zero </pre> <p>In this code, we use the try statement to attempt to perform a division operation. If either of these operations raises an exception, the matching except block is executed.</p> <p>Python also provides many built-in exceptions that can be raised in similar situations. Some common built-in exceptions include <strong>IndexError, TypeError</strong> , and <strong>NameError</strong> . Also, we can define our custom exceptions by creating a new class that inherits from the Exception class.</p> <h2>Python CSV</h2> <p>A CSV stands for 'comma separated values', which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheets or databases in plain text and has a common format for data interchange. A CSV file opens into the Excel sheet, and the rows and columns data define the standard format.</p> <p>We can use the CSV.reader function to read a CSV file. This function returns a reader object that we can use to repeat over the rows in the CSV file. Each row is returned as a list of values, where each value corresponds to a column in the CSV file.</p> <p> <strong>For example, consider the following code:</strong> </p> <pre> import csv with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) </pre> <p>Here, we open the file data.csv in read mode and create a <strong>csv.reader</strong> object using the <strong>csv.reader()</strong> function. We then iterate over the rows in the CSV file using a for loop and print each row to the console.</p> <p>We can use the <strong>CSV.writer()</strong> function to write data to a CSV file. It returns a writer object we can use to write rows to the CSV file. We can write rows by calling the <strong>writer ()</strong> method on the writer object.</p> <p> <strong>For example, consider the following code:</strong> </p> <pre> import csv data = [ ['Name', 'Age', 'Country'], ['Alice', '25', 'USA'], ['Bob', '30', 'Canada'], ['Charlie', '35', 'Australia'] ] with open('data.csv', 'w') as file: writer = csv.writer(file) for row in data: writer.writerow(row) </pre> <p>In this program, we create a list of lists called data, where each inner list represents a row of data. We then open the file data.csv in write mode and create a <strong>CSV.writer</strong> object using the CSV.writer function. We then iterate over the rows in data using a for loop and write each row to the CSV file using the writer method.</p> <h2>Python Sending Mail</h2> <p>We can send or read a mail using the Python script. Python's standard library modules are useful for handling various protocols such as PoP3 and IMAP . Python provides the <a href="/python-sending-email-using-smtp">smtplib</a> module for sending emails using SMTP (Simple Mail Transfer Protocol). We will learn how to send mail with the popular email service SMTP from a Python script.</p> <h3>Python Magic Methods</h3> <p>The Python magic method is the special method that adds 'magic' to a class. It starts and ends with double underscores, for example, <strong>_init_</strong> or <strong>_str_</strong> .</p> <p>The built-in classes define many magic methods. The <strong>dir()</strong> function can be used to see the number of magic methods inherited by a class. It has two prefixes and suffix underscores in the method name.</p> <ul> <li>Python magic methods are also known as <strong>dunder methods</strong> , short for ' double underscore ' methods because their names start and end with a double underscore.</li> <li> <strong>Magic methods</strong> are automatically invoked by the Python interpreter in certain situations, such as when an object is created, compared to another object, or printed.</li> <li>Magic methods can be used to customize the behavior of classes, such as defining how objects are compared, converted to strings, or accessed as containers.</li> <li>Some commonly used magic methods include <strong>init</strong> for initializing an object, str for converting an object to a string, <strong>eq</strong> for comparing two objects for equality, and <strong>getitem</strong> and <strong>setitem</strong> for accessing items in a container object.</li> </ul> <p>For example, the <strong>str</strong> magic method can define how an object should be represented as a string. Here's an example</p> <pre> class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name} ({self.age})' person = Person('Vikas', 22) print(person) </pre> <p> <strong>Output:</strong> </p> <pre> Vikas (22) </pre> <p>In this example, the str method is defined to return a formatted string representation of the Person object with the person's name and age.</p> <p>Another commonly used magic method is <strong>eq</strong> , which defines how objects should be compared for equality. Here's an example:</p> <pre> class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y point1 = Point(2, 3) point2 = Point(3, 4) point3 = Point(2, 3) print(point1 == point2) print(point1 == point3) </pre> <p> <strong>Output:</strong> </p> <pre> False True </pre> <p>In this example, the <strong>eq</strong> method is defined to return True if two Point objects have the same x and y coordinates and False otherwise.</p> <h2>Python Oops Concepts</h2> <p>Everything in Python is treated as an object, including integer values, floats, functions, classes, and none. Apart from that, Python supports all oriented concepts. Below is a brief introduction to the Oops concepts of Python.</p> <ul> <li> <a href="/classes-objects-python"> <strong>Classes and Objects</strong> </a> - Python classes are the blueprints of the Object. An object is a collection of data and methods that act on the data.</li> <li> <a href="/python-inheritance"> <strong>Inheritance</strong> </a> - An inheritance is a technique where one class inherits the properties of other classes.</li> <li> <a href="/python-constructor"> <strong>Constructor</strong> </a> - Python provides a special method __init__() which is known as a constructor. This method is automatically called when an object is instantiated.</li> <tr><td>Data Member</td> - A variable that holds data associated with a class and its objects. <li> <strong>Polymorphism</strong> - Polymorphism is a concept where an object can take many forms. In Python, polymorphism can be achieved through method overloading and method overriding.</li> </tr><tr><td>Method Overloading</td> - In Python, method overloading is achieved through default arguments, where a method can be defined with multiple parameters. The default values are used if some parameters are not passed while calling the method. <li> <strong>Method Overriding</strong> - Method overriding is a concept where a subclass implements a method already defined in its superclass.</li> <li> <strong>Encapsulation</strong> - Encapsulation is wrapping data and methods into a single unit. In Python, encapsulation is achieved through access modifiers, such as public, private, and protected. However, Python does not strictly enforce access modifiers, and the naming convention indicates the access level.</li> <li> <strong>Data Abstraction</strong> : A technique to hide the complexity of data and show only essential features to the user. It provides an interface to interact with the data. Data abstraction reduces complexity and makes code more modular, allowing developers to focus on the program's essential features.</li> </tr></ul> <p>To read the Oops concept in detail, visit the following resources.</p> <ul> <li> Python Oops Concepts - In Python, the object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book, house, pencil, etc. and the class defines its properties and behaviours.</li> <li> <a href="/classes-objects-python">Python Objects and classes</a> - In Python, objects are instances of classes and classes are blueprints that defines structure and behaviour of data.</li> <li> <a href="/python-constructor">Python Constructor</a> - A constructor is a special method in a class that is used to initialize the object's attributes when the object is created.</li> <li> <a href="/python-inheritance">Python Inheritance</a> - Inheritance is a mechanism in which new class (subclass or child class) inherits the properties and behaviours of an existing class (super class or parent class).</li> <li> Python Polymorphism - Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling different classes to be used interchangeably through a common interface.</li> </ul> <h2>Python Advance Topics</h2> <p>Python includes many advances and useful concepts that help the programmer solve complex tasks. These concepts are given below.</p> <h3> Python Iterator </h3> <p>An iterator is simply an object that can be iterated upon. It returns one Object at a time. It can be implemented using the two special methods, <strong>__iter__()</strong> and __next__().</p> <p>Iterators in Python are objects that allow iteration over a collection of data. They process each collection element individually without loading the entire collection into memory.</p> <p>For example, let's create an iterator that returns the squares of numbers up to a given limit:</p> <pre> def __init__(self, limit): self.limit = limit self.n = 0 def __iter__(self): return self def __next__(self): if self.n <= 2 self.limit: square="self.n" ** self.n +="1" return else: raise stopiteration numbers="Squares(5)" for n in numbers: print(n) < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 4 9 16 25 </pre> <p>In this example, we have created a class Squares that acts as an iterator by implementing the __iter__() and __next__() methods. The __iter__() method returns the Object itself, and the __next__() method returns the next square of the number until the limit is reached.</p> <p>To learn more about the iterators, visit our Python Iterators tutorial.</p> <h3> Python Generators </h3> <p> <strong>Python generators</strong> produce a sequence of values <strong>using a yield statement</strong> rather than a return since they are functions that return iterators. Generators terminate the function's execution while keeping the local state. It picks up right where it left off when it is restarted. Because we don't have to implement the iterator protocol thanks to this feature, writing iterators is made simpler. Here is an illustration of a straightforward generator function that produces squares of numbers:</p> <pre> # Generator Function def square_numbers(n): for i in range(n): yield i**2 # Create a generator object generator = square_numbers(5) # Print the values generated by the generator for num in generator: print(num) </pre> <p> <strong>Output:</strong> </p> <pre> 0 1 4 9 16 </pre> <h2>Python Modifiers</h2> <p> <strong>Python Decorators</strong> are functions used to modify the behaviour of another function. They allow adding functionality to an existing function without modifying its code directly. Decorators are defined using the <strong>@</strong> symbol followed by the name of the decorator function. They can be used for logging, timing, caching, etc.</p> <p>Here's an example of a decorator function that adds timing functionality to another function:</p> <pre> import time from math import factorial # Decorator to calculate time taken by # the function def time_it(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f'{func.__name__} took {end-start:.5f} seconds to run.') return result return wrapper @time_it def my_function(n): time.sleep(2) print(f'Factorial of {n} = {factorial(n)}') my_function(25) </pre> <p> <strong>Output:</strong> </p> <pre> </pre> <p>In the above example, the time_it decorator function takes another function as an argument and returns a wrapper function. The wrapper function calculates the time to execute the original function and prints it to the console. The @time_it decorator is used to apply the time_it function to the my_function function. When my_function is called, the decorator is executed, and the timing functionality is added.</p> <h2>Python MySQL</h2> <p>Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.</p> <ul> <li> <strong>Environment Setup</strong> : Installing and configuring MySQL Connector/Python to use Python with MySQL.</li> <li> <strong>Database Connection</strong> : Establishing a connection between Python and MySQL database using MySQL Connector/Python.</li> <li> <strong>Creating New Database</strong> : Creating a new database in MySQL using Python.</li> <li> <strong>Creating Tables</strong> : Creating tables in the MySQL database with Python using SQL commands.</li> <li> <strong>Insert Operation</strong> : Insert data into MySQL tables using Python and SQL commands.</li> <li> <strong>Read Operation</strong> : Reading data from MySQL tables using Python and SQL commands.</li> <li> <strong>Update Operation</strong> : Updating data in MySQL tables using Python and SQL commands.</li> <li> <strong>Join Operation</strong> : Joining two or more tables in MySQL using Python and SQL commands.</li> <li> <strong>Performing Transactions</strong> : Performing a group of SQL queries as a single unit of work in MySQL using Python.</li> </ul> <p>Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.</p> <h2>Python MongoDB</h2> <p> Python MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.</p> <p>Here are some common tasks when working with MongoDB in Python:</p> <ol class="points"> <li> <strong>Environment Setup</strong> : Install and configure MongoDB and PyMongo library on your system.</li> <li> <strong>Database Connection</strong> : Connect to a MongoDB server using the MongoClient class from PyMongo.</li> <li> <strong>Creating a new database</strong> : Use the MongoClient Object to create a new database.</li> <li> <strong>Creating collections</strong> : Create collections within a database to store documents.</li> <li> <strong>Inserting documents</strong> : Insert new documents into a collection using the insert_one() or insert_many() methods.</li> <li> <strong>Querying documents</strong> : Retrieve documents from a collection using various query methods like find_one(), find(), etc.</li> <li> <strong>Updating documents</strong> : Modify existing documents in a collection using update_one() or update_many() methods.</li> <li> <strong>Deleting documents</strong> : Remove documents from a collection using the delete_one() or delete_many() methods.</li> <li> <strong>Aggregation</strong> : Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.</li> <tr><td>Indexing:</td> Improve query performance by creating indexes on fields in collections. </tr></ol> <p>There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.</p> <h2> Python SQLite </h2> <p>Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.</p> <p>Various API methods are available through the SQLite3 library that may be used to run SQL queries, insert , select , update , and remove data, as well as get data from tables. Additionally, it allows transactions, allowing programmers to undo changes in case of a problem. Python SQLite is a fantastic option for creating programs that need an embedded database system, including desktop, mobile, and modest-sized web programs. SQLite has become popular among developers for lightweight apps with database functionality thanks to its ease of use, portability, and smooth connection with Python.</p> <h2> Python CGI </h2> <p> <strong>Python CGI</strong> is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.</p> <p>Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.</p> <h2> Asynchronous Programming in Python </h2> <p> <strong>Asynchronous programming</strong> is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.</p> <p>Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.</p> <p>Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including <strong>asyncio.gather(),</strong> <strong>asyncio.wait(),</strong> and <strong>asyncio.create_task().</strong> </p> <p>Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.</p> <h2> Python Concurrency </h2> <p>The term ' <strong>concurrency</strong> ' describes a program's capacity to carry out several tasks at once, enhancing the program's efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.</p> <p>The <strong>threading module</strong> in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python's asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write highperformance, scalable programs that can handle multiple tasks concurrently.</p> <p>Python's threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.</p> <p>For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.</p> <p>The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.</p> <p>With libraries like Dask , <a href="/pyspark-tutorial">PySpark</a> , and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.</p> <h2> Web Scrapping using Python </h2> <p>The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.</p> <p>We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python's requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like <strong>Beautiful Soup and lxml</strong> .</p> <p>We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website's server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.</p> <p>Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.</p> <h2>Natural Language Processing (NLP) using Python</h2> <p>A branch of artificial intelligence (AI) called 'natural language processing' (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.</p> <p> <strong>For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library.</strong> It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy , which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.</p> <p>NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.</p> <p>Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.</p> <h2>Conclusion:</h2> <p>In this tutorial, we've looked at some of Python's most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.</p> <p>Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.</p> <h2>Prerequisite</h2> <p>Before learning Python, you must have the basic knowledge of programming concepts.</p> <h2>Audience</h2> <p>Our Python tutorial is designed to help beginners and professionals.</p> <h2>Problem</h2> <p>We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.</p> <hr></=></pre></5:>
V zgornjem primeru kode smo prikazali uporabo dveh vrst zank v Pythonu – zanke For in While.
Zanka For se uporablja za ponavljanje po zaporedju elementov, kot je seznam, tuple ali niz. V primeru smo definirali seznam sadja in uporabili zanko for za tiskanje vsakega sadja, lahko pa jo uporabimo tudi za tiskanje obsega števil.
Zanka While ponovi blok kode, če je podani pogoj resničen. V primeru smo inicializirali spremenljivko i na 1 in uporabili zanko while za tiskanje vrednosti i, dokler ni večja ali enaka 6. Stavek i += 1 se uporablja za povečanje vrednosti i v vsaki ponovitvi .
O njih se bomo podrobneje seznanili v vadnici.
Podatkovne strukture Python
Python ponuja štiri vgrajene podatkovne strukture: seznami , tuples , kompleti , in slovarji ki nam omogočajo učinkovito shranjevanje podatkov. Spodaj so pogosto uporabljene podatkovne strukture v Pythonu skupaj s primeri kode:
1. Seznami
- Seznami so naročene zbirke podatkovnih elementov različnih tipov podatkov.
- Seznami so spremenljiv kar pomeni, da je seznam mogoče kadar koli spremeniti.
- Elementi so lahko dostopno z uporabo indeksov .
- Določeni so z oglatim oklepajem ' [] '.
primer:
# Create a list fruits = ['apple', 'banana', 'cherry'] print('fuirts[1] =', fruits[1]) # Modify list fruits.append('orange') print('fruits =', fruits) num_list = [1, 2, 3, 4, 5] # Calculate sum sum_nums = sum(num_list) print('sum_nums =', sum_nums)
Izhod:
fuirts[1] = banana fruits = ['apple', 'banana', 'cherry', 'orange'] sum_nums = 15
2. Tuples
- Tuples so tudi naročene zbirke podatkovnih elementov različnih tipov podatkov, podobno kot seznami.
- Elementi so lahko dostopno z uporabo indeksov .
- Tuples so nespremenljiv kar pomeni, da enkrat ustvarjenih torkov ni več mogoče spreminjati.
- Opredeljeni so z odprtim oklepajem ' () '.
primer:
# Create a tuple point = (3, 4) x, y = point print('(x, y) =', x, y) # Create another tuple tuple_ = ('apple', 'banana', 'cherry', 'orange') print('Tuple =', tuple_)
Izhod:
(x, y) = 3 4 Tuple = ('apple', 'banana', 'cherry', 'orange')
3. Kompleti
- Kompleti so neurejeno zbirke nespremenljivih podatkovnih elementov različnih tipov podatkov.
- Kompleti so spremenljiv .
- Do elementov ni mogoče dostopati z uporabo indeksov.
- Kompleti ne vsebujejo podvojenih elementov .
- Definirani so z zavitimi oklepaji ' {} '
primer:
# Create a set set1 = {1, 2, 2, 1, 3, 4} print('set1 =', set1) # Create another set set2 = {'apple', 'banana', 'cherry', 'apple', 'orange'} print('set2 =', set2)
Izhod:
set1 = {1, 2, 3, 4} set2 = {'apple', 'cherry', 'orange', 'banana'}
4. Slovarji
- Slovar so pari ključ-vrednost ki vam omogočajo, da vrednosti povežete z edinstvenimi ključi.
- Definirani so z zavitimi oklepaji ' {} ' s pari ključ-vrednost ločeno z dvopičjem ':' .
- Slovarji so spremenljiv .
- Do elementov lahko dostopate s tipkami.
primer:
# Create a dictionary person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'} print('person =', person) print(person['name']) # Modify Dictionary person['age'] = 27 print('person =', person)
Izhod:
person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'} Umesh person = {'name': 'Umesh', 'age': 27, 'city': 'Noida'}
To je le nekaj primerov podatkovnih struktur, vgrajenih v Python. Vsaka podatkovna struktura ima svoje značilnosti in primere uporabe.
Funkcionalno programiranje Python
Ta razdelek vadnice Python opredeljuje nekatera pomembna orodja, povezana s funkcionalnim programiranjem, kot so lambda in rekurzivne funkcije. Te funkcije so zelo učinkovite pri opravljanju zapletenih nalog. Definiramo nekaj pomembnih funkcij, kot so zmanjšanje, preslikava in filtriranje. Python nudi modul functools, ki vključuje različna funkcionalna programska orodja. Če želite izvedeti več o funkcionalnem programiranju, obiščite naslednjo vadnico.
Zadnje različice Pythona so uvedle funkcije, zaradi katerih je funkcionalno programiranje bolj jedrnato in izrazno. Na primer, 'operator mroža':= omogoča dodeljevanje spremenljivk v vrstici v izrazih, kar je lahko uporabno pri delu z ugnezdenimi funkcijskimi klici ali razumevanjem seznamov.
Funkcija Python
- Lambda funkcija - Funkcija lambda je majhna, anonimna funkcija ki lahko sprejme poljubno število argumentov, vendar ima lahko samo en izraz. Funkcije lambda se pogosto uporabljajo v funkcionalnem programiranju za ustvarjanje funkcij 'sprotno' brez definiranja imenovane funkcije.
- Rekurzivna funkcija - Rekurzivna funkcija je funkcija, ki pokliče samo sebe, da reši problem. Rekurzivne funkcije se pogosto uporabljajo v funkcionalnem programiranju za izvajanje kompleksnih izračunov ali za prečkanje kompleksnih podatkovnih struktur.
- Funkcija zemljevida - Funkcija map() uporabi dano funkcijo za vsako postavko iterable in vrne novo iterable z rezultati. Vhodni iterable je lahko seznam, tuple ali kaj drugega.
- Funkcija filtra - Funkcija filter() vrne iterator iz iterable, za katerega funkcija, posredovana kot prvi argument, vrne True. Filtrira elemente iz iterable, ki ne izpolnjujejo podanega pogoja.
- Zmanjšajte funkcijo - Funkcija reduce() uporabi funkcijo dveh argumentov kumulativno za elemente iterable od leve proti desni, da jo zmanjša na eno samo vrednost.
- modul functools - Modul functools v Pythonu zagotavlja funkcije višjega reda, ki delujejo na drugih funkcijah, kot sta partial() in reduce().
- Curry funkcija - Currying funkcija je funkcija, ki sprejme več argumentov in vrne zaporedje funkcij, od katerih vsaka sprejme en argument.
- Funkcija pomnilnika - Memoizacija je tehnika, ki se uporablja v funkcionalnem programiranju za predpomnjenje rezultatov dragih funkcijskih klicev in vrnitev predpomnjenega rezultata, ko se isti vnosi znova pojavijo.
- Funkcija navojev - Threading je tehnika, ki se uporablja v funkcionalnem programiranju za hkratno izvajanje več nalog, da je koda učinkovitejša in hitrejša.
Moduli Python
Moduli Python so programske datoteke, ki vsebujejo kodo ali funkcije Python. Python ima dve vrsti modulov - uporabniško definirane module in vgrajene module. Modul, ki ga določi uporabnik, ali naša koda Python, shranjena s pripono .py, se obravnava kot modul, ki ga določi uporabnik.
Vgrajeni moduli so vnaprej določeni moduli Pythona. Za uporabo funkcionalnosti modulov jih moramo uvoziti v naš trenutni delovni program.
Moduli Python so bistveni za ekosistem jezika, saj ponujajo kodo za večkratno uporabo in funkcionalnost, ki jo je mogoče uvoziti v kateri koli program Python. Tukaj je nekaj primerov več modulov Python, skupaj s kratkim opisom vsakega:
matematika : uporabnikom omogoča dostop do matematičnih konstant ter pi in trigonometričnih funkcij.
Datum čas : ponuja razrede za enostavnejši način upravljanja z datumi, časi in obdobji.
TI : Omogoča interakcijo z osnovnim operacijskim sistemom, vključno z upravljanjem procesov in dejavnosti datotečnega sistema.
naključen : Naključna funkcija ponuja orodja za generiranje naključnih celih števil in izbiranje naključnih elementov s seznama.
JSON : JSON je podatkovna struktura, ki jo je mogoče kodirati in dekodirati in se pogosto uporablja v spletnih API-jih in izmenjavi podatkov. Ta modul omogoča delo z JSON.
Re : podpira regularne izraze, zmogljivo orodje za iskanje in obdelavo besedila.
Zbirke : Zagotavlja alternativne podatkovne strukture, kot so razvrščeni slovarji, privzeti slovarji in imenovane tuple.
NumPy : NumPy je osnovni komplet orodij za znanstveno računalništvo, ki podpira numerične operacije na nizih in matricah.
Pande : Zagotavlja podatkovne strukture in operacije na visoki ravni za obravnavo časovnih vrst in drugih strukturiranih tipov podatkov.
Zahteve : ponuja preprost uporabniški vmesnik za spletne API-je in izvaja zahteve HTTP.
V/I datoteke Python
Datoteke se uporabljajo za shranjevanje podatkov na računalniški disk. V tej vadnici razložimo vgrajeni predmet datoteke Pythona. Datoteko lahko odpremo s skriptom Python in izvedemo različne operacije, kot so pisanje, branje in dodajanje. Datoteko lahko odprete na različne načine. Pojasnjeni smo z ustreznim primerom. Naučili se bomo tudi izvajati operacije branja/pisanja na binarnih datotekah.
Pythonov vhodno-izhodni (I/O) sistem datotek ponuja programe za komunikacijo z datotekami, shranjenimi na disku. Vgrajene metode Pythona za objekt datoteke nam omogočajo izvajanje dejanj, kot so branje, pisanje in dodajanje podatkov v datoteke.
The odprto() metoda v Pythonu naredi objekt datoteke pri delu z datotekami. Ime datoteke, ki jo želite odpreti, in način, v katerem naj se datoteka odpre, sta parametra, ki ju zahteva ta funkcija. Način je mogoče uporabiti glede na delo, ki ga je treba opraviti z datoteko, na primer ' r 'za branje,' notri 'za pisanje ali' a ' za pritrditev.
Po uspešni izdelavi predmeta lahko uporabimo različne metode glede na naše delo. Če želimo pisati v datoteko, lahko uporabimo funkcije write(), če pa želite brati in pisati oboje, potem lahko uporabimo funkcijo append() in v primerih, ko želimo prebrati le vsebino datoteko lahko uporabimo funkcijo read(). Z binarnimi datotekami, ki vsebujejo podatke v binarni in ne besedilni obliki, je mogoče delati tudi z uporabo Pythona. Binarne datoteke so napisane na način, ki ga ljudje neposredno ne razumejo. The rb in wb načini lahko berejo in zapisujejo binarne podatke v binarne datoteke.
10 ml na unče
Izjeme Python
Izjema je lahko opredeljena kot neobičajno stanje v programu, ki povzroči prekinitev poteka programa.
Kadarkoli pride do izjeme, program ustavi izvajanje, zato se druga koda ne izvede. Zato so izjema napake med izvajanjem, ki jih ni mogoče obravnavati s skriptom Python. Izjema je objekt Python, ki predstavlja napako.
Izjeme Python so pomemben vidik obravnavanja napak v programiranju Python. Ko program naleti na nepričakovano situacijo ali napako, lahko sproži izjemo, ki lahko prekine običajni potek programa.
V Pythonu so izjeme predstavljene kot objekti, ki vsebujejo informacije o napaki, vključno z njeno vrsto in sporočilom. Najpogostejša vrsta izjem v Pythonu je razred izjem, osnovni razred za vse druge vgrajene izjeme.
Za obravnavanje izjem v Pythonu uporabljamo poskusi in razen izjave. The poskusi stavek se uporablja za pritrditev kode, ki lahko povzroči izjemo, medtem ko razen stavek se uporablja za definiranje bloka kode, ki naj se izvede, ko pride do izjeme.
Na primer, razmislite o naslednji kodi:
try: x = int ( input ('Enter a number: ')) y = 10 / x print ('Result:', y) except ZeroDivisionError: print ('Error: Division by zero') except ValueError: print ('Error: Invalid input')
Izhod:
Enter a number: 0 Error: Division by zero
V tej kodi uporabljamo stavek try za poskus izvedbe operacije deljenja. Če katera od teh operacij sproži izjemo, se izvede ujemajoči se blok razen.
Python ponuja tudi številne vgrajene izjeme, ki jih je mogoče sprožiti v podobnih situacijah. Nekatere pogoste vgrajene izjeme vključujejo IndexError, TypeError , in NameError . Prav tako lahko definiramo svoje izjeme po meri tako, da ustvarimo nov razred, ki deduje razred Exception.
Python CSV
CSV pomeni 'vrednosti, ločene z vejicami', kar je definirano kot preprosta oblika datoteke, ki uporablja posebno strukturiranje za urejanje tabelaričnih podatkov. Tabelarne podatke, kot so preglednice ali baze podatkov, shranjuje v navadnem besedilu in ima skupno obliko za izmenjavo podatkov. Datoteka CSV se odpre v Excelovem listu, podatki vrstic in stolpcev pa določajo standardno obliko.
Za branje datoteke CSV lahko uporabimo funkcijo CSV.reader. Ta funkcija vrne predmet bralnika, ki ga lahko uporabimo za ponavljanje čez vrstice v datoteki CSV. Vsaka vrstica je vrnjena kot seznam vrednosti, kjer vsaka vrednost ustreza stolpcu v datoteki CSV.
Na primer, razmislite o naslednji kodi:
import csv with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Tukaj odpremo datoteko data.csv v načinu branja in ustvarimo a csv.reader objekt z uporabo csv.reader() funkcijo. Nato z zanko for ponovimo vrstice v datoteki CSV in vsako vrstico natisnemo na konzolo.
Lahko uporabimo CSV.writer() funkcijo za zapisovanje podatkov v datoteko CSV. Vrne predmet zapisovalca, ki ga lahko uporabimo za pisanje vrstic v datoteko CSV. Vrstice lahko pišemo tako, da pokličemo pisatelj () metoda na objektu pisca.
Na primer, razmislite o naslednji kodi:
import csv data = [ ['Name', 'Age', 'Country'], ['Alice', '25', 'USA'], ['Bob', '30', 'Canada'], ['Charlie', '35', 'Australia'] ] with open('data.csv', 'w') as file: writer = csv.writer(file) for row in data: writer.writerow(row)
V tem programu ustvarimo seznam seznamov, imenovan podatkov, kjer vsak notranji seznam predstavlja vrstico podatkov. Nato odpremo datoteko data.csv v načinu pisanja in ustvarimo a CSV.writer predmet s funkcijo CSV.writer. Nato ponovimo vrstice v podatkih z uporabo zanke for in vsako vrstico zapišemo v datoteko CSV z metodo pisanja.
Python pošilja pošto
S pomočjo skripta Python lahko pošljemo ali preberemo pošto. Moduli standardne knjižnice Python so uporabni za upravljanje različnih protokolov, kot sta PoP3 in IMAP. Python zagotavlja smtplib modul za pošiljanje e-pošte z uporabo SMTP (Simple Mail Transfer Protocol). Naučili se bomo pošiljanja pošte s priljubljeno e-poštno storitvijo SMTP iz skripta Python.
Čarobne metode Python
Čarobna metoda Python je posebna metoda, ki razredu doda 'čarovnijo'. Začne in konča z dvojnimi podčrtaji, npr. _vroče_ oz _str_ .
Vgrajeni razredi definirajo številne čarobne metode. The ti() funkcijo lahko uporabite za ogled števila čarobnih metod, ki jih podeduje razred. V imenu metode ima dve predponi in pripono podčrtaj.
- Čarobne metode Python so znane tudi kot dunderjeve metode , okrajšava za metode z dvojnim podčrtajem, ker se njihova imena začnejo in končajo z dvojnim podčrtajem.
- Magične metode samodejno prikliče tolmač Python v določenih situacijah, na primer ko je predmet ustvarjen, primerjan z drugim predmetom ali natisnjen.
- Čarobne metode je mogoče uporabiti za prilagoditev vedenja razredov, kot je definiranje primerjave predmetov, pretvorbe v nize ali dostopa do njih kot vsebnikov.
- Nekatere pogosto uporabljene magične metode vključujejo toplota za inicializacijo predmeta, str za pretvorbo predmeta v niz, en za primerjavo dveh predmetov za enakost in z naslovom in setitem za dostop do elementov v objektu vsebnika.
Na primer, str čarobna metoda lahko definira, kako naj bo predmet predstavljen kot niz. Tukaj je primer
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name} ({self.age})' person = Person('Vikas', 22) print(person)
Izhod:
Vikas (22)
V tem primeru je metoda str definirana tako, da vrne oblikovano predstavitev niza objekta Person z imenom in starostjo osebe.
Druga pogosto uporabljena magična metoda je en , ki določa, kako naj se predmeti primerjajo za enakost. Tukaj je primer:
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y point1 = Point(2, 3) point2 = Point(3, 4) point3 = Point(2, 3) print(point1 == point2) print(point1 == point3)
Izhod:
False True
V tem primeru je en metoda je definirana tako, da vrne True, če imata dva objekta Point enake koordinate x in y, drugače pa False.
Python Oops koncepti
Vse v Pythonu se obravnava kot predmet, vključno s celimi vrednostmi, lebdečimi vrednostmi, funkcijami, razredi in nič. Poleg tega Python podpira vse usmerjene koncepte. Spodaj je kratek uvod v Oops koncepte Pythona.
- Razredi in objekti - Razredi Python so načrti predmeta. Objekt je zbirka podatkov in metod, ki delujejo na podatke.
- Dedovanje - Dedovanje je tehnika, pri kateri en razred podeduje lastnosti drugih razredov.
- Konstruktor - Python nudi posebno metodo __init__(), ki je znana kot konstruktor. Ta metoda se samodejno pokliče, ko se objekt ustvari.
- Polimorfizem - Polimorfizem je koncept, pri katerem ima predmet lahko veliko oblik. V Pythonu je polimorfizem mogoče doseči s preobremenitvijo metode in preglasitvijo metode.
- Preglasitev metode - Preglasitev metode je koncept, kjer podrazred izvaja metodo, ki je že definirana v njegovem nadrazredu.
- Enkapsulacija - Enkapsulacija je zavijanje podatkov in metod v eno samo enoto. V Pythonu je enkapsulacija dosežena z modifikatorji dostopa, kot so javni, zasebni in zaščiteni. Vendar pa Python ne uveljavlja strogo modifikatorjev dostopa in konvencija o poimenovanju označuje raven dostopa.
- Abstrakcija podatkov : tehnika za skrivanje kompleksnosti podatkov in prikaz le bistvenih funkcij uporabniku. Zagotavlja vmesnik za interakcijo s podatki. Abstrakcija podatkov zmanjša kompleksnost in naredi kodo bolj modularno, kar razvijalcem omogoča, da se osredotočijo na bistvene funkcije programa.
Če želite podrobno prebrati koncept Oops, obiščite naslednje vire.
- Python Ups Koncepti - V Pythonu je objektno usmerjena paradigma oblikovanje programa z uporabo razredov in objektov. Predmet je povezan s stvarnimi entitetami, kot so knjiga, hiša, svinčnik itd., razred pa določa njegove lastnosti in vedenje.
- Objekti in razredi Python - V Pythonu so objekti primerki razredov, razredi pa načrti, ki definirajo strukturo in obnašanje podatkov.
- Konstruktor Python - Konstruktor je posebna metoda v razredu, ki se uporablja za inicializacijo atributov predmeta, ko je predmet ustvarjen.
- Python dedovanje - Dedovanje je mehanizem, pri katerem novi razred (podrazred ali podrejeni razred) podeduje lastnosti in vedenja obstoječega razreda (superrazred ali nadrejeni razred).
- Polimorfizem Python - Polimorfizem omogoča, da se objekti različnih razredov obravnavajo kot objekti skupnega nadrazreda, kar omogoča izmenično uporabo različnih razredov prek skupnega vmesnika.
Python napredne teme
Python vključuje številne napredke in uporabne koncepte, ki programerju pomagajo pri reševanju kompleksnih nalog. Ti pojmi so navedeni spodaj.
Iterator Python
Iterator je preprosto predmet, ki ga je mogoče ponoviti. Vrne en predmet naenkrat. Izvaja se lahko z dvema posebnima metodama, __iter__() in __naprej__().
Iteratorji v Pythonu so objekti, ki omogočajo iteracijo po zbirki podatkov. Obdelujejo vsak element zbirke posebej, ne da bi celotno zbirko naložili v pomnilnik.
Na primer, ustvarimo iterator, ki vrne kvadrate števil do dane meje:
def __init__(self, limit): self.limit = limit self.n = 0 def __iter__(self): return self def __next__(self): if self.n <= 2 self.limit: square="self.n" ** self.n +="1" return else: raise stopiteration numbers="Squares(5)" for n in numbers: print(n) < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 4 9 16 25 </pre> <p>In this example, we have created a class Squares that acts as an iterator by implementing the __iter__() and __next__() methods. The __iter__() method returns the Object itself, and the __next__() method returns the next square of the number until the limit is reached.</p> <p>To learn more about the iterators, visit our Python Iterators tutorial.</p> <h3> Python Generators </h3> <p> <strong>Python generators</strong> produce a sequence of values <strong>using a yield statement</strong> rather than a return since they are functions that return iterators. Generators terminate the function's execution while keeping the local state. It picks up right where it left off when it is restarted. Because we don't have to implement the iterator protocol thanks to this feature, writing iterators is made simpler. Here is an illustration of a straightforward generator function that produces squares of numbers:</p> <pre> # Generator Function def square_numbers(n): for i in range(n): yield i**2 # Create a generator object generator = square_numbers(5) # Print the values generated by the generator for num in generator: print(num) </pre> <p> <strong>Output:</strong> </p> <pre> 0 1 4 9 16 </pre> <h2>Python Modifiers</h2> <p> <strong>Python Decorators</strong> are functions used to modify the behaviour of another function. They allow adding functionality to an existing function without modifying its code directly. Decorators are defined using the <strong>@</strong> symbol followed by the name of the decorator function. They can be used for logging, timing, caching, etc.</p> <p>Here's an example of a decorator function that adds timing functionality to another function:</p> <pre> import time from math import factorial # Decorator to calculate time taken by # the function def time_it(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f'{func.__name__} took {end-start:.5f} seconds to run.') return result return wrapper @time_it def my_function(n): time.sleep(2) print(f'Factorial of {n} = {factorial(n)}') my_function(25) </pre> <p> <strong>Output:</strong> </p> <pre> </pre> <p>In the above example, the time_it decorator function takes another function as an argument and returns a wrapper function. The wrapper function calculates the time to execute the original function and prints it to the console. The @time_it decorator is used to apply the time_it function to the my_function function. When my_function is called, the decorator is executed, and the timing functionality is added.</p> <h2>Python MySQL</h2> <p>Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.</p> <ul> <li> <strong>Environment Setup</strong> : Installing and configuring MySQL Connector/Python to use Python with MySQL.</li> <li> <strong>Database Connection</strong> : Establishing a connection between Python and MySQL database using MySQL Connector/Python.</li> <li> <strong>Creating New Database</strong> : Creating a new database in MySQL using Python.</li> <li> <strong>Creating Tables</strong> : Creating tables in the MySQL database with Python using SQL commands.</li> <li> <strong>Insert Operation</strong> : Insert data into MySQL tables using Python and SQL commands.</li> <li> <strong>Read Operation</strong> : Reading data from MySQL tables using Python and SQL commands.</li> <li> <strong>Update Operation</strong> : Updating data in MySQL tables using Python and SQL commands.</li> <li> <strong>Join Operation</strong> : Joining two or more tables in MySQL using Python and SQL commands.</li> <li> <strong>Performing Transactions</strong> : Performing a group of SQL queries as a single unit of work in MySQL using Python.</li> </ul> <p>Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.</p> <h2>Python MongoDB</h2> <p> Python MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.</p> <p>Here are some common tasks when working with MongoDB in Python:</p> <ol class="points"> <li> <strong>Environment Setup</strong> : Install and configure MongoDB and PyMongo library on your system.</li> <li> <strong>Database Connection</strong> : Connect to a MongoDB server using the MongoClient class from PyMongo.</li> <li> <strong>Creating a new database</strong> : Use the MongoClient Object to create a new database.</li> <li> <strong>Creating collections</strong> : Create collections within a database to store documents.</li> <li> <strong>Inserting documents</strong> : Insert new documents into a collection using the insert_one() or insert_many() methods.</li> <li> <strong>Querying documents</strong> : Retrieve documents from a collection using various query methods like find_one(), find(), etc.</li> <li> <strong>Updating documents</strong> : Modify existing documents in a collection using update_one() or update_many() methods.</li> <li> <strong>Deleting documents</strong> : Remove documents from a collection using the delete_one() or delete_many() methods.</li> <li> <strong>Aggregation</strong> : Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.</li> <tr><td>Indexing:</td> Improve query performance by creating indexes on fields in collections. </tr></ol> <p>There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.</p> <h2> Python SQLite </h2> <p>Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.</p> <p>Various API methods are available through the SQLite3 library that may be used to run SQL queries, insert , select , update , and remove data, as well as get data from tables. Additionally, it allows transactions, allowing programmers to undo changes in case of a problem. Python SQLite is a fantastic option for creating programs that need an embedded database system, including desktop, mobile, and modest-sized web programs. SQLite has become popular among developers for lightweight apps with database functionality thanks to its ease of use, portability, and smooth connection with Python.</p> <h2> Python CGI </h2> <p> <strong>Python CGI</strong> is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.</p> <p>Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.</p> <h2> Asynchronous Programming in Python </h2> <p> <strong>Asynchronous programming</strong> is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.</p> <p>Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.</p> <p>Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including <strong>asyncio.gather(),</strong> <strong>asyncio.wait(),</strong> and <strong>asyncio.create_task().</strong> </p> <p>Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.</p> <h2> Python Concurrency </h2> <p>The term ' <strong>concurrency</strong> ' describes a program's capacity to carry out several tasks at once, enhancing the program's efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.</p> <p>The <strong>threading module</strong> in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python's asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write highperformance, scalable programs that can handle multiple tasks concurrently.</p> <p>Python's threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.</p> <p>For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.</p> <p>The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.</p> <p>With libraries like Dask , <a href="/pyspark-tutorial">PySpark</a> , and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.</p> <h2> Web Scrapping using Python </h2> <p>The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.</p> <p>We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python's requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like <strong>Beautiful Soup and lxml</strong> .</p> <p>We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website's server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.</p> <p>Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.</p> <h2>Natural Language Processing (NLP) using Python</h2> <p>A branch of artificial intelligence (AI) called 'natural language processing' (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.</p> <p> <strong>For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library.</strong> It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy , which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.</p> <p>NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.</p> <p>Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.</p> <h2>Conclusion:</h2> <p>In this tutorial, we've looked at some of Python's most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.</p> <p>Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.</p> <h2>Prerequisite</h2> <p>Before learning Python, you must have the basic knowledge of programming concepts.</p> <h2>Audience</h2> <p>Our Python tutorial is designed to help beginners and professionals.</p> <h2>Problem</h2> <p>We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.</p> <hr></=>
V tem primeru smo ustvarili razred Squares, ki deluje kot iterator z implementacijo metod __iter__() in __next__(). Metoda __iter__() vrne sam predmet, metoda __next__() pa vrne naslednji kvadrat števila, dokler ni dosežena omejitev.
Če želite izvedeti več o iteratorjih, obiščite našo vadnico o iteratorjih Python.
Generatorji Python
Python generatorji ustvarite zaporedje vrednosti z uporabo izjave o donosu namesto vrnitve, saj gre za funkcije, ki vračajo iteratorje. Generatorji prekinejo izvajanje funkcije, medtem ko ohranijo lokalno stanje. Ko se znova zažene, se nadaljuje tam, kjer je končal. Ker nam zaradi te funkcije ni treba implementirati protokola iteratorja, je pisanje iteratorjev poenostavljeno. Tukaj je ilustracija enostavne funkcije generatorja, ki proizvaja kvadrate števil:
# Generator Function def square_numbers(n): for i in range(n): yield i**2 # Create a generator object generator = square_numbers(5) # Print the values generated by the generator for num in generator: print(num)
Izhod:
0 1 4 9 16
Modifikatorji Python
Okraševalci Python so funkcije, ki se uporabljajo za spreminjanje obnašanja druge funkcije. Omogočajo dodajanje funkcionalnosti obstoječi funkciji brez neposrednega spreminjanja njene kode. Dekoraterji so definirani z uporabo @ simbol, ki mu sledi ime funkcije dekoraterja. Uporabljajo se lahko za beleženje, merjenje časa, predpomnjenje itd.
Tukaj je primer funkcije dekoraterja, ki doda funkcijo merjenja časa drugi funkciji:
import time from math import factorial # Decorator to calculate time taken by # the function def time_it(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f'{func.__name__} took {end-start:.5f} seconds to run.') return result return wrapper @time_it def my_function(n): time.sleep(2) print(f'Factorial of {n} = {factorial(n)}') my_function(25)
Izhod:
V zgornjem primeru funkcija dekoratorja time_it vzame drugo funkcijo kot argument in vrne funkcijo ovoja. Funkcija ovoja izračuna čas za izvedbo izvirne funkcije in ga natisne na konzolo. Dekorater @time_it se uporablja za uporabo funkcije time_it v funkciji my_function. Ko se pokliče my_function, se izvede dekorater in doda se funkcija merjenja časa.
Python MySQL
Python MySQL je močan sistem za upravljanje relacijskih baz podatkov. Nastaviti moramo okolje in vzpostaviti povezavo za uporabo MySQL s Pythonom. Z ukazi SQL v Pythonu lahko ustvarimo novo bazo podatkov in tabele.
- Nastavitev okolja : Namestitev in konfiguracija MySQL Connector/Python za uporabo Pythona z MySQL.
- Povezava z bazo podatkov : Vzpostavitev povezave med Pythonom in bazo podatkov MySQL z uporabo MySQL Connector/Python.
- Ustvarjanje nove baze podatkov : Ustvarjanje nove baze podatkov v MySQL z uporabo Pythona.
- Ustvarjanje tabel : Ustvarjanje tabel v bazi podatkov MySQL s Pythonom z uporabo ukazov SQL.
- Vstavi operacijo : Vnesite podatke v tabele MySQL z uporabo ukazov Python in SQL.
- Preberite operacijo : Branje podatkov iz tabel MySQL z uporabo ukazov Python in SQL.
- Operacija posodobitve : Posodabljanje podatkov v tabelah MySQL z uporabo ukazov Python in SQL.
- Pridružite se operaciji : Združevanje dveh ali več tabel v MySQL z uporabo ukazov Python in SQL.
- Izvajanje transakcij : Izvajanje skupine poizvedb SQL kot ene enote dela v MySQL z uporabo Pythona.
Druge relativne točke vključujejo obravnavanje napak, ustvarjanje indeksov in uporabo shranjenih procedur in funkcij v MySQL s Pythonom.
Python MongoDB
Python MongoDB je priljubljena zbirka podatkov NoSQL, ki shranjuje podatke v dokumente, podobne JSON. Je brez sheme in zagotavlja visoko razširljivost in prilagodljivost za shranjevanje podatkov. MongoDB lahko uporabljamo s Pythonom z uporabo knjižnice PyMongo, ki ponuja preprost in intuitiven vmesnik za interakcijo z MongoDB.
Tukaj je nekaj pogostih nalog pri delu z MongoDB v Pythonu:
- Nastavitev okolja : Namestite in konfigurirajte knjižnico MongoDB in PyMongo v vašem sistemu.
- Povezava z bazo podatkov : Povežite se s strežnikom MongoDB z uporabo razreda MongoClient iz PyMongo.
- Ustvarjanje nove baze podatkov : uporabite objekt MongoClient za ustvarjanje nove baze podatkov.
- Ustvarjanje zbirk : ustvarite zbirke v zbirki podatkov za shranjevanje dokumentov.
- Vstavljanje dokumentov : Vstavite nove dokumente v zbirko z uporabo metod insert_one() ali insert_many().
- Poizvedovanje po dokumentih : Pridobite dokumente iz zbirke z uporabo različnih poizvedovalnih metod, kot so find_one(), find() itd.
- Posodabljanje dokumentov : Spremenite obstoječe dokumente v zbirki z uporabo metod update_one() ali update_many().
- Brisanje dokumentov : odstranite dokumente iz zbirke z uporabo metod delete_one() ali delete_many().
- Združevanje : Izvedite operacije združevanja, kot je združevanje, štetje itd., z uporabo ogrodja cevovoda združevanja.
V MongoDB je veliko bolj naprednih tem, kot so razčlenjevanje podatkov, replikacija in več, vendar te naloge pokrivajo osnove dela z MongoDB v Pythonu.
Python SQLite
Relacijske baze podatkov so zgrajene in vzdrževane z uporabo Python SQLite, kompaktnega, samostojnega mehanizma baze podatkov brez strežnika. Zaradi svoje mobilnosti in preprostosti je priljubljena možnost za lokalne ali manjše aplikacije. Python ima vgrajen modul za povezovanje z bazami podatkov SQLite, imenovan SQLite3, ki razvijalcem omogoča brez težav delo z bazami podatkov SQLite.
V knjižnici SQLite3 so na voljo različne metode API-ja, ki se lahko uporabljajo za izvajanje poizvedb SQL, vstavljanje, izbiranje, posodabljanje in odstranjevanje podatkov ter pridobivanje podatkov iz tabel. Poleg tega omogoča transakcije, kar programerjem omogoča razveljavitev sprememb v primeru težave. Python SQLite je fantastična možnost za ustvarjanje programov, ki potrebujejo vdelan sistem baze podatkov, vključno z namiznimi, mobilnimi in skromnimi spletnimi programi. SQLite je postal priljubljen med razvijalci za lahke aplikacije s funkcionalnostjo baze podatkov zahvaljujoč enostavni uporabi, prenosljivosti in gladki povezavi s Pythonom.
Python CGI
Python CGI je tehnologija za izvajanje skriptov prek spletnih strežnikov za ustvarjanje dinamične spletne vsebine. Ponuja komunikacijski kanal in vmesnik za dinamično ustvarjanje vsebine za zunanje skripte CGI in spletni strežnik. Skripti Python CGI lahko ustvarjajo spletne strani HTML, obravnavajo vnos obrazcev in komunicirajo z bazami podatkov. Python CGI strežniku omogoča izvajanje skriptov Python in zagotavljanje rezultatov odjemalcu, kar ponuja hiter in učinkovit pristop k ustvarjanju dinamičnih spletnih aplikacij.
Skripte Python CGI je mogoče uporabiti za številne stvari, vključno z ustvarjanjem dinamičnih spletnih strani, obdelavo obrazcev in interakcijo z zbirkami podatkov. Ker je Python, močan in priljubljen programski jezik, mogoče uporabiti za ustvarjanje skriptov, omogoča bolj prilagojen in prilagodljiv pristop k ustvarjanju spleta. Razširljive, varne in vzdržljive spletne aplikacije je mogoče ustvariti s Python CGI. Python CGI je priročno orodje za spletne razvijalce, ki gradijo dinamične in interaktivne spletne aplikacije.
Asinhrono programiranje v Pythonu
Asinhrono programiranje je paradigma računalniškega programiranja, ki omogoča samostojno in sočasno delovanje dejavnosti. Pogosto se uporablja v aplikacijah, kot so spletni strežniki, programska oprema za baze podatkov in omrežno programiranje, kjer je treba sočasno obravnavati več nalog ali zahtev.
Python ima med svojimi knjižnicami in ogrodji za asinhrono programiranje asyncio, Twisted in Tornado. Asyncio, eden od teh, ponuja preprost vmesnik za asinhrono programiranje in je uradna knjižnica za asinhrono programiranje v Pythonu.
Korutine so funkcije, ki jih je mogoče ustaviti in znova zagnati na določenih mestih v kodi in jih uporablja asyncio. To omogoča, da številne korutine delujejo hkrati, ne da bi se medsebojno motile. Za izdelavo in vzdrževanje korutin knjižnica ponuja več razredov in metod, vključno z asyncio.gather(), asyncio.wait(), in asyncio.create_task().
Dogodkovne zanke, ki so zadolžene za načrtovanje in delovanje korutin, so še ena značilnost asyncia. S kroženjem med korutinami na neblokirni način zanka dogodkov nadzoruje izvajanje korutin in zagotavlja, da nobena korutina ne blokira druge. Poleg tega podpira časovnike in razporejanje povratnih klicev, kar je lahko koristno, ko je treba dejavnosti dokončati ob določenih urah ali intervalih.
Python Concurrency
Izraz ' sočasnost ' opisuje zmogljivost programa za izvajanje več nalog hkrati, s čimer se poveča učinkovitost programa. Python ponuja več modulov in metod, povezanih s sočasnostjo, vključno z asinhronim programiranjem, večprocesiranjem in večnitnostjo. Medtem ko večprocesiranje vključuje izvajanje številnih procesov hkrati v sistemu, večnitnost vključuje izvajanje številnih niti hkrati znotraj enega procesa.
The navojni modul v Pythonu programerjem omogoča izgradnjo večnitnosti. Ponuja razrede in operacije za vzpostavitev in nadzor niti. Nasprotno pa večprocesni modul razvijalcem omogoča načrtovanje in nadzor procesov. Pythonov asyncio modul zagotavlja podporo za asinhrono programiranje, ki razvijalcem omogoča pisanje neblokirne kode, ki lahko hkrati obravnava več nalog. Z uporabo teh tehnik lahko razvijalci napišejo visoko zmogljive, razširljive programe, ki lahko hkrati obravnavajo več nalog.
Pythonov modul za navoje omogoča hkratno izvajanje več niti znotraj enega procesa, kar je koristno za dejavnosti, vezane na V/I.
Za operacije, ki zahtevajo CPE, kot je obdelava slik ali analiza podatkov, večprocesni moduli omogočajo sočasno izvajanje številnih procesov v več jedrih CPE.
Modul asyncio podpira asinhroni V/I in dovoljuje ustvarjanje enonitne sočasne kode z uporabo korutin za omrežne aplikacije z visoko sočasnostjo.
S knjižnicami, kot je Dask, PySpark , in MPI, se lahko Python uporablja tudi za vzporedno računalništvo. Te knjižnice omogočajo porazdelitev delovnih obremenitev po številnih vozliščih ali gručih za boljšo zmogljivost.
Web Scrapping z uporabo Pythona
Postopek spletnega strganja se uporablja za samodejno pridobivanje podatkov s spletnih mest. Različna orodja in knjižnice črpajo podatke iz HTML in drugih spletnih formatov. Python je med najpogosteje uporabljanimi programskimi jeziki za spletno strganje zaradi svoje enostavne uporabe, prilagodljivosti in raznolikosti knjižnic.
Narediti moramo nekaj korakov, da izvedemo spletno strganje s Pythonom. Najprej se moramo odločiti, katero spletno stran bomo postrgali in katere podatke zbrati. Nato lahko oddamo zahtevo spletnemu mestu in prejmemo vsebino HTML z uporabo Pythonovega paketa zahtev. Ko imamo besedilo HTML, lahko izvlečemo potrebne podatke z uporabo različnih paketov za razčlenjevanje, kot je Čudovita juha in lxml .
Uporabimo lahko več strategij, kot so upočasnitev zahtev, uporaba uporabniških agentov in uporaba posrednikov, da preprečimo preobremenitev strežnika spletnega mesta. Prav tako je ključnega pomena, da upoštevate pogoje storitve za spletno mesto in spoštujete njegovo datoteko robots.txt.
Podatkovno rudarjenje, ustvarjanje potencialnih strank, sledenje cenam in številne druge uporabe so možne za spletno strganje. Ker pa je nepooblaščeno spletno strganje lahko v nasprotju z zakonom in neetično, je bistveno, da ga uporabljate strokovno in etično.
Obdelava naravnega jezika (NLP) z uporabo Pythona
Veja umetne inteligence (AI), imenovana 'obdelava naravnega jezika' (NLP), proučuje, kako računalniki in človeški jezik medsebojno delujejo. Zahvaljujoč NLP lahko računalniki zdaj razumejo, interpretirajo in proizvajajo človeški jezik. Zaradi svoje preprostosti, vsestranskosti in močnih knjižnic, kot sta NLTK (Natural Language Toolkit) in spaCy, je Python dobro znan programski jezik za NLP.
Za naloge NLP, vključno s tokenizacijo, izvorom, lematizacijo, označevanjem dela govora, identifikacijo poimenovane entitete, analizo čustev in drugimi, NLTK ponuja popolno knjižnico. Ima različne korpuse (velike, organizirane zbirke besedil) za razvoj in vrednotenje modelov NLP. Druga zelo priljubljena knjižnica za naloge NLP je spaCy, ki ponuja hitro in učinkovito obdelavo ogromnih količin besedila. Omogoča preprosto spreminjanje in razširitev ter ima vnaprej pripravljene modele za različne delovne obremenitve NLP.
NLP se lahko uporablja v Pythonu za različne praktične namene, vključno s klepetalnimi roboti, analizo razpoloženja, kategorizacijo besedila, strojnim prevajanjem in več. NLP uporabljajo na primer chatboti za razumevanje in odgovarjanje na vprašanja uporabnikov v slogu naravnega jezika. Analiza razpoloženja, ki je lahko koristna za spremljanje blagovne znamke, analizo povratnih informacij strank in druge namene, uporablja NLP za kategorizacijo razpoloženja besedila (pozitivno, negativno ali nevtralno). Besedilni dokumenti so kategorizirani z uporabo obdelave naravnega jezika (NLP) v vnaprej določene kategorije za zaznavanje neželene pošte, kategorizacijo novic in druge namene.
Python je močno in uporabno orodje pri analizi in obdelavi človeškega jezika. Razvijalci lahko izvajajo različne dejavnosti NLP in ustvarjajo uporabne aplikacije, ki lahko komunicirajo s potrošniki v naravnem jeziku s knjižnicami, kot sta NLTK in spaCy.
Zaključek:
V tej vadnici smo si ogledali nekaj najpomembnejših funkcij in zamisli Pythona, vključno s spremenljivkami, tipi podatkov, zankami, funkcijami, moduli in še več. Obravnavane so bile tudi bolj zapletene teme, vključno s spletnim strganjem, obdelavo naravnega jezika, paralelizmom in povezavo z bazo podatkov. Imeli boste trdno podlago za nadaljnje učenje o Pythonu in njegovih aplikacijah z uporabo informacij, ki ste se jih naučili v tej lekciji.
fmoviez
Ne pozabite, da je vadba in razvijanje kode najboljši način za učenje Pythona. V javaTpoint boste morda našli veliko virov za podporo nadaljnjega učenja, vključno z dokumentacijo, vadnicami, spletnimi skupinami in drugim. Python lahko obvladate in z njim ustvarite čudovite stvari, če trdo delate in vztrajate.
Predpogoj
Preden se naučite Python, morate imeti osnovno znanje konceptov programiranja.
Občinstvo
Naša vadnica za Python je zasnovana tako, da pomaga začetnikom in profesionalcem.
Težava
Zagotavljamo vam, da v tej vadnici za Python ne boste našli nobene težave. Če pa pride do kakršne koli napake, jo prosim objavite v kontaktnem obrazcu.
=>5:>