Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basics of Python for PHP developers

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about the basic knowledge of Python applicable to PHP developers, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

As an object-oriented, literal translation computer programming language, Python has a history of more than ten years, mature and stable. This article will take you on a tour of the world of Python, assuming you don't have any knowledge of the Python programming language, but at least some basic programming knowledge, and we'll focus on comparing Python and PHP.

You've spent a lot of time on PHP, and switching to another language is imperative. You also know that standing still means being beaten passively. In fact, learning a new language is like traveling abroad: you will come into contact with new things, taste new food, experience different cultures, talk to different people, learn about everything new, and then go home to experience the original environment.

The goal of this article is quite simple: to briefly introduce the basic knowledge of Python and lay the foundation for readers to conduct in-depth search. Fortunately, you will realize that Python is actually no different from the language you used before. Once again, take tourism as an example, you don't need to go too far, you just need to go to neighboring countries that speak the same language.

What is Python?

Python is defined as a "universal high-level programming language". It is known for its simplicity and ease of use, and is one of the few languages that require spaces and indentation. Guido Van Rossum, the lead author of Python, is still active in the community and is jokingly called a benevolent dictator.

The flexibility and compactness of Python is commendable. It supports object-oriented programming, structured programming, aspect-oriented programming and functional programming. Python uses a small kernel design, but has a large number of extended libraries, thus ensuring the compactness and flexibility of the language.

From a grammatical point of view, you will find that Python is extraordinarily concise-almost pure. PHP developers will either be fascinated by the syntax of this approach or will find its limitations. It mainly depends on your own opinion. The attitude of the Python community to promote this sense of beauty is very clear, focusing more on aesthetics and simplicity than on smart skills. PHP developers who have formed a Perl tradition ("you can do it in many ways") (like myself) will face a completely opposite philosophy ("there should only be one way to achieve it").

In fact, the community defines a unique code-style term, Python (pythonic). You can say that your code is Python, which is a good use of Python terminology, while also showing the natural characteristics of the language. This article is not intended to be Pythonista (or Pythoneer), but if you want to continue on the road to Python, you must not miss the knowledge points of this article. Just as PHP has its own programming style and Perl has its own conceptual approach, learning the Python language inevitably requires you to start thinking in that language.

Another point: at the time of this writing, the * version of Python is V3.0, but this article focuses on Python V2.6. Python V3.0 is not backward compatible with previous versions, and V2.6 is the most widely used version. Of course, you can use the version you like according to your needs.

What is the difference between Python and PHP?

Generally speaking, PHP is a Web development language. Yes, it provides a command line interface and can even be used to develop embedded applications, but it is mainly used for Web development. In contrast, Python is a scripting language and can also be used for Web development. In this respect-- I know I would say that-- it's closer to Perl than PHP. (of course, in other respects, there is no real difference between them. Let's move on. )

PHP's syntax is full of dollar signs ($) and curly braces ({}), while Python is relatively concise and cleaner. PHP supports switch and do...while structures, while Python does not. PHP uses ternary operators (foo?bar:baz) and a lengthy list of function names, and naming conventions are omnipresent; instead, you'll find Python much more concise. The array type of PHP can support both simple lists and dictionaries or hashes, but Python separates the two. Python uses both concepts of variability and immutability: tuple, for example, is an immutable list. You can create a tuple, but you cannot modify it after it has been created. This concept may take some time to get familiar with, but it is extremely effective in avoiding mistakes. Of course, the only way to change tuple is to copy it. Therefore, if you find that you have made a large number of changes to immutable objects, you should reconsider your approach.

As mentioned earlier, indentation in Python makes sense: it can be very difficult to get used to when you first start learning the language. You can also create functions and methods that use keywords as parameters-this is very different from the standard positional parameters in PHP. Object-oriented followers will be delighted with the true object-oriented thinking in Python, including its "first-level" classes and functions. If you use a non-English language, you will love Python's strong internationalization and Unicode support. You'll also like the multithreading capabilities of Python; this is one of the features that fascinated me at first.

To sum up, PHP and Python are similar to each other in many ways. You can easily create variables, loops, use conditions, and create functions. You can even easily create reusable modules. The user communities in both languages are full of energy and passion. PHP has a larger user base, but this is mainly due to its advantage and popularity in hosting servers and Web focus.

Use Python

Listing 1 shows a basic Python script.

Listing 1. A simple Python script

For i in range (20): print (I)

Listing 2 shows the corollary of the script.

Listing 2. The result of listing 1

0 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Before going any further, let's learn some preliminary knowledge. Let's start with variables.

Variable

As you can see, the representation variable does not require any special characters. The variable I is a pure I-with nothing special. You don't need any special characters (such as semicolons and parentheses) to indicate the end of a code block or language; you just need to use a simple colon in the for exercise (:). Also note that indentation indicates to Python what belongs to the for loop. For example, the code in listing 3 prints a description for each number in a loop.

Listing 3. Add a statement to each loop

For i in range (20): print (I) print ('all done?')

Instead, the code in listing 4 prints a note at the end of the loop.

Listing 4. Add a statement after the loop

For i in range (20): print (I) print ('all girls')

Now, when I see this code for the first time, I think it's complete nonsense. What? Make me believe that line wrapping and indentation can ensure the structure and operation of the code? Believe me, it won't be long before you get used to it (but I need to admit that you won't finish the statement until the semicolon is reached). If you work with other developers on Python projects, you will see how useful this readability can be. You are no longer always guessing, "what on earth is this smart guy trying to do here?"

In PHP, you use the = operator to assign values to variables (see listing 5). In Python, you use the same operator, but you just need to mark or point to the value. To me, it's just an assignment operation, and I don't need to worry too much about technical terms.

Listing 5. Create variabl

Yorkie = 'Marlowe' # meet our Yorkie Marlowe! Mutt = 'Kafka' # meet our mutt Kafka print (mutt) # prints Kafka

Python's convention for variable names is similar to PHP: you can only use letters, numbers, and underscores (_) when creating variable names. Similarly, the * characters of a variable name cannot be a number. Python variable names are case-sensitive, and you cannot use specific Python keywords such as if, else, while, def, or, and, not, in, and is as variable names. It's not surprising. Python allows you to perform string-based operations at will. Most of the operations in listing 6 should be familiar to you.

Listing 6. Common string-based operations

Yorkie = 'Marlowe' mutt =' Kafka' ylen = len (yorkie) # length of variable yorkie print (ylen) # prints 7 print (len (yorkie)) # does the same thing len (yorkie) # also does the same thing, print is implicit print (yorkie.lower ()) # lower cases the string print (yorkie.strip ('aeiou')) # removes vowels from end of string print (mutt.split (' f')) # splits "Kafka" into ['Ka' 'ka'] print (mutt.count (' a')) # prints 2, the number of a's in string yorkie.replace # replace a's with 4s

Conditional statement

You've seen how to use for loops; now let's talk about conditional statements. You'll find that the conditional statements in Phyon are basically the same as PHP: you can use the familiar if/else-type structure, as shown in listing 7.

Listing 7. A simple conditional test

Yorkie = 'Marlowe' mutt =' Kafka' if len (yorkie) > len (mutt): print ('The yorkie windows') Else: print ('The mutt windows')

You can also use if/elif/else (elif, the equivalent of elseif in PHP) to create more complex conditional tests, as shown in listing 8.

Listing 8. A more complex conditional test

Yorkie = 'Marlowe' mutt =' Kafka' if len (yorkie) + len (mutt) > 15: print ('The yorkie and the mutt windings') Elif len (yorkie) + len (mutt) > 10: print ('Too close to telltale') Else: print ('Nobody windows')

You might say that so far there is nothing different: there is not much difference between the book and the imagination. Now, let's look at the way Python handles lists, and you'll see the differences between the two languages.

List

A common list type is tuple, which is immutable. After you load a series of values in tuple, you do not change it. Tuple can contain numbers, strings, variables, and even other tuples. It is normal for Tuples to index from 0; you can use the-1 index to access an item. You can also run some functions on tuple (see listing 9).

Listing 9. Tuples

Items = (1, mutt, 'Honda', (1 Kafka')) print items [1] # prints Kafka print items [- 1] # prints (1) itemsitems2 = items [0:2] # items2 now contains (1,' Kafka') thanks to slice operation 'Honda' in items # returns TRUE len (items) # returns 4 items.index (' Kafka') # returns 1, because second item matches this index location

Lists are similar to tuple, except that they are variable. After you create a list, you can add, delete, and update values in the list. The list uses square brackets instead of parentheses (()), as shown in listing 10.

Listing 10. List

Groceries = ['ham','spam','eggs'] len (groceries) # returns 3 print groceries [1] # prints spam for x in groceries: print x.upper () # prints HAM SPAM EGGS groceries [2] =' bacon' groceries # list is now ['ham','spam','bacon'] groceries.append (' eggs') groceries # list is now ['ham','spam','bacon',' eggs'] groceries.sort () groceries # list is now ['bacon' 'eggs',' ham', 'spam']

A dictionary is similar to an associative array or hash; it uses key-value pairs to store and restrict information. But instead of using square brackets and parentheses, it uses angle brackets. Like lists, dictionaries are variable, which means that you can add, delete, and update values in them (see listing 11).

Listing 11. Dictionaries

Colorvalues = {'red': 1,' blue': 2, 'green': 3,' yellow': 4, 'orange': 5} colorvalues # prints {' blue': 2, 'orange': 5,' green': 3, 'yellow': 4,' red': 1} colorvalues ['blue'] # prints 2 colorvalues.keys () # retrieves all keys as a list: # [blue',' orange', 'green',' yellow' 'red'] colorvalues.pop (' blue') # prints 2 and removes the blue key/value pair colorvalues # after pop, we have: # {'orange': 5,' green': 3, 'yellow': 4,' red': 1}

Create a simple script in Python

Now you have some knowledge of Python. Next, we will create a simple Python script. The script reads the number of PHP session files located in your server / tmp directory and writes a summary report to the log file. In this script, you will learn how to import modules for specific functions, how to use files, and how to write to log files. You will also set a series of variables to track the information collected.

Listing 12 shows the entire script. Open an editor, paste the code into it, and save the file as tmp.py on the system. Then, run chmod + x on the file to make it executable (assuming you are using a UNIX ®system).

Listing 12. Tmp.py

#! / usr/bin/python import os from time import strftime stamp = strftime ("% Y-%m-%d% H:%M:%S") logfile ='/ path/to/your/logfile.log' path ='/ path/to/tmp/directory/' files = os.listdir (path) bytes = 0 numfiles = 0 for f in files: if f.startswith ('sess_'): info = os.stat (path + f) numfiles + = 1 bytes + = info [6 ] if numfiles > 1: title = 'files' else: title =' file' string = stamp + "-" + str (numfiles) + "session"\ + title + " "+ str (bytes) +" bytes\ n "file = open (logfile," a ") file.writelines (string) file.close ()

In the * * line, you can see a hash-bang line that identifies the location of the Python interpreter. In my system, it is located at / usr/bin/python. Please adjust this line according to the system requirements. The next two lines are used to import specific modules that will help you execute your job. Considering that the script needs to work with folders and files, you need to import the os module because it contains functions and methods that help you list files, read files, and manipulate folders. You also need to write to a log file, so you can add a timestamp to the entry-which requires the use of a time function. You don't need all the time functions, just import the strftime function.

In the next six lines, you set some variables. The * variable is stamp, which contains a date string. You then use the strftime function to create a timestamp in a specific format-in this case, 2010-01-03 12:43:03. Next, create a logfile variable and add a path to the file where the log file messages are actually stored (the file does not need to actually exist). For simplicity, I put a log file in the / logs folder, but you can also put it somewhere else. Again, the path variable contains the path to the / tmp directory. You can use any path, as long as you end with a slash (/).

The next three variables are also very simple: the files list contains all the files and folders in the specified path, as well as the bytes and numfiles variables. Both variables are set to 0; the script increments these values as it processes the file.

With all these definitions in place, then comes the core of the script: a simple for loop that processes the files in the file list. Each time you run a loop, the script calculates the file name; if it starts with sess_, the script runs os.stat () on the file, extracts file data (such as creation time, modification time, and byte size), increments the numfiles counter, and accumulates the file's byte size to the total. When the loop finishes running, the script checks to see if the value in the numfiles variable is greater than 1. If it is greater than 1, a new title variable is set to files;. Otherwise, title is set to file in the singular.

The * part of the script is also very simple: you create a string variable and add a line of data that starts with a timestamp, followed by numfiles (converted to a string) and bytes (also converted to a string). Note the continuation character (\); this character allows the code to run to the next line. It's a little trick to improve readability. Then, you use the open () function to open the log file in additional mode (after all, you always need to add content to the file), the writelines () function adds a string to the log file, and the close () function closes the file.

Now you have created a simple Python script. This script can be used to accomplish many tasks. For example, you can set up a cron job to run the script every hour to help you track the number of PHP sessions used in 24 hours. You can also use jQuery or some other JavaScript framework to connect to this script through Ajax to provide you with log file feeds (if you do this, you need to use the print command to return data).

As developers, we spend a lot of time learning specific languages and methods. Sometimes, doing so can lead to a dispute over the merits of different languages. I have participated in a lot of such debates, and I believe the same is true of readers. Admittedly, most of these discussions end up with the same result-"whatever you can do, I can do better"-which is pointless.

However, when you turn your attention to another language, you will find that most languages have similar tools, principles, and methods. Learning one language is difficult, but applying your knowledge to another language can greatly simplify the learning process. Even if you don't actually have to migrate to a second language, you can take your understanding of programming ideas and methods to the next level.

Fortunately, this article provides you with some knowledge about Python. I hope you can continue to learn this excellent language. You may never leave the world of PHP (after all, it's the tool you live on), but don't stop learning.

After reading the above, do you have any further understanding of the basics of Python for PHP developers? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report