Thomas Myer, Director, triple dog dare mediathomas Myer is a consultant, writer, and lecturer who lives in Austin. He created triple dog dare media.
Introduction:Are you an experienced PHP developer and want to learn python? This article will explore the world of Python development from the perspective of PHP developers, and convert familiar PHP concepts (such as variables, lists, and functions) into the same Python concept.
You are a PHP developer. You may have been writing applications for the past five years (or longer, you have already turned many imaginations into possibilities-e-commerce systems, simple content management systems, Twitter and Facebook integration, and various custom utilities. You may also need to maintain a large amount of Code-from simple display pages to custom applications that contain thousands of lines of code written by others.
Abbreviations
- Ajax:Asynchronous JavaScript + XML
- XML:Extensible Markup Language)
You have spent a lot of time on PHP and it is imperative to switch to another language. You also know that if you do not move it, it means passive attacks. In fact, learning a new language is like traveling abroad: you will get in touch with new things, taste new foods, enjoy different cultures, talk to different people, and learn about all new things, then return to your home to experience the original environment.
This article will guide you through the world of Python. This article assumes that you do not have any knowledge of the python programming language, but should have at least some basic programming knowledge. We will focus on comparing Python and PHP-not to distinguish between the two, but to a simple truth: it is easier to refer to existing knowledge when learning new knowledge.
The goal of this article is quite simple: briefly introduce the basic knowledge of Python and lay the foundation for readers to perform in-depth search. Fortunately, you will realize that python is actually no different from the language you used earlier. Taking tourism as an example, you don't need to go too far. You just need to go to a neighboring country with the same language.
What is Python?
Python is defined as a general 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 rosum, the main author of Python, is still very active in the community and is dubbedBenevolent dictatorship.
Python's flexibility and closeness are commendable. It supports object-oriented programming, structured programming, Aspect-Oriented Programming, and function programming. Python uses a small kernel design, but has a large number of extension libraries, thus ensuring the language's closeness and flexibility.
From a syntax perspective, you will find that python's conciseness is exceptionally prominent-almost a pure realm. PHP developers will either be fascinated by the syntax of this method or discover its limitations. This depends on your own opinions. The attitude of the python community to promote this aesthetic is very clear. They pay more attention to aesthetics and conciseness, rather than smart skills. PHP developers (like myself) who have formed a Perl tradition ("You can implement it in multiple ways) there will be a completely opposite philosophy ("there should be only one way to implement it ").
In fact, this community defines a unique term for code styles, namely, Python (Pythonic). You can say that your code is made of Python, which is a good use of Python terms and shows the natural features of the language. This article is not intended to be pythonista (or pythoneer), but if you want to continue with python, you must never miss this article. Just as PHP has its own programming style and Perl has its own conceptual methods, it is necessary to start to use this language to learn python.
Another key point: when writing this article, the latest version of python is V3.0, but this article focuses on Python v2.6. Python V3.0 is not backward compatible with earlier versions, and v2.6 is the most widely used version. Of course, you can use your preferred version as needed.
Back to Top
What is the difference between Python and PHP?
In general, 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. On the contrary, python is a scripting language and can also be used for web development. In this regard-I know I will say this-it is closer to Perl than PHP. (Of course, there is no practical difference between them in other aspects. Let's continue .)
PHP syntax is filled with dollar signs ($
) And braces ({}
), While python is more concise and clean. PHP supportswitch
Anddo...while
Structure, while python is not. PHP uses the ternary operator (foo?bar:baz
) And a lengthy list of function names, and naming conventions are even more confusing. On the contrary, you will find that python is much more concise. PHP array types support both simple list and dictionary or hash, but Python separates them.
Python uses both variability and immutability: for example, tuple is an immutable list. You can create a tuple, but it cannot be modified after it is created. This concept may take some time to get familiar with, but it is extremely effective to avoid errors. Of course, the only way to change tuple is to copy it. Therefore, if you find that a large number of changes have been made to immutable objects, you should reconsider your methods.
As mentioned earlier, indentation in Python has a meaning: it is very difficult for you to adapt to this language at the beginning. You can also create functions and methods that use keywords as parameters-different from standard location parameters in PHP. Object-oriented followers will be excited about the real object-oriented ideas in Python, including its "first-level" classes and functions. If you use a non-English language, you will love Python's powerful internationalization and Unicode support. You will also like the multi-threading feature of Python, which is also one of the features that I was fascinated by at first.
To sum up, PHP and Python are similar in many aspects. You can easily create variables, loops, conditions, and functions. You can even easily create reusable modules. The user communities in both languages are full of vigor and passion. PHP has a larger user base, but this is mainly due to its advantages and popularity in hosting servers and web attention.
Good-Brief introduction to this end. Let's start our exploration journey.
Back to Top
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 inevitable results of the script.
Listing 2. Result of Listing 1
012345678910111213141516171819 |
Before in-depth exploration, let's take a look at some preliminary knowledge. Start with the variable.
Variable
It can be seen that the variable does not need any special characters. Variablei
Is a purei
-Nothing special. Indicates that the end of a code block or language does not require any special characters (such as semicolons and parentheses ).for
Use a simple colon (:
). Note that indentation instructs Python about the attributesfor
Loop. For example, the Code in listing 3 will output a description for each number in the loop.
Listing 3. Add a statement for each loop
for i in range(20):print(i)print('all done?') |
Instead, the code in Listing 4 will output a description at the end of the loop.
Listing 4. Add a statement after the loop
for i in range(20):print(i)print('all done!') |
Now, when I first saw such code, I thought it was totally nonsense. What? Let me believe that line breaks and indentation can ensure the structure and operation of the code? Believe me, it won't take long for you to get used to it (but I need to admit that the semi-colon must be reached before you can conclude the execution of the sentence ). If you develop a python project with other developers, you will find this readability is of great use. You don't always guess, as before, "what is this smart guy doing here ?"
In PHP, you use=
The operator assigns a value to the variable (see listing 5 ). In python, you use the same operator, but you only need to mark or point to a value. For me, it is just a value assignment operation. I don't need to worry too much about special terms.
Listing 5. Creating Variables
yorkie = 'Marlowe' #meet our Yorkie Marlowe!mutt = 'Kafka' #meet our mutt Kafkaprint(mutt) #prints Kafka |
The variable name conventions in Python are similar to those in PHP: when creating a variable name, you can only use letters, numbers, and underscores (_
). Similarly, the first character of the variable name cannot be a number. Python variable names are case sensitive and you cannot use specific Python keywords (suchif、else、while、def、or、and、not、in
Andis
As the variable name. This is 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 yorkieprint(ylen) #prints 7print(len(yorkie)) #does the same thinglen(yorkie) #also does the same thing, print is implicitprint(yorkie.lower()) #lower cases the stringprint(yorkie.strip('aeiou')) #removes vowels from end of stringprint(mutt.split('f')) #splits "Kafka" into ['Ka', 'ka']print(mutt.count('a')) #prints 2, the number of a's in stringyorkie.replace('a','4') #replace a's with 4's |
Condition Statement
You have learned how to usefor
Loop. Now, let's discuss the conditional statements. You will find that the condition statements in phyon are basically the same as those in PHP: You can use the familiarif/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 wins!')else:print('The mutt wins!') |
You can also useif/elif/else
(elif
, Equivalentelseif
) Create more complex conditional tests, as shown in listing 8.
Listing 8. A complex conditional test
yorkie = 'Marlowe'mutt = 'Kafka'if len(yorkie) + len(mutt) > 15:print('The yorkie and the mutt win!')elif len(yorkie) + len(mutt) > 10:print('Too close to tell!')else:print('Nobody wins!') |
You may say that there is no difference so far: there is no big difference between it and the imagination. Now, let's look at the way Python processes the list. You will find the differences between the two languages.
List
A common list type isTupleIt is immutable. After a series of values are loaded in tuple, you will not change it. Tuple can contain numbers, strings, variables, and even other tuples. Tuples starts to create an index from 0, which is normal. You can use-1
Index to access the last project. You can also run some functions on tuple (see listing 9 ).
Listing 9. tuples
items = (1, mutt, 'Honda', (1,2,3))print items[1] #prints Kafkaprint items[-1] #prints (1,2,3)items2 = items[0:2] #items2 now contains (1, 'Kafka') thanks to slice operation'Honda' in items #returns TRUElen(items) #returns 4items.index('Kafka') #returns 1, because second item matches this index location |
Lists are similar to tuple, but they are variable. After creating 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 3print groceries[1] #prints spamfor x in groceries:print x.upper() #prints HAM SPAM EGGSgroceries[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 associated array or hash. It uses key-value pairs to store and limit information. But it does not use square brackets and parentheses, but uses angle brackets. Similar to the list, the dictionary is variable, which means you can add, delete, and update values (see listing 11 ).
Listing 11. Dictionary
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 2colorvalues.keys() #retrieves all keys as a list: #['blue', 'orange', 'green', 'yellow', 'red']colorvalues.pop('blue') #prints 2 and removes the blue key/value paircolorvalues #after pop, we have: #{'orange': 5, 'green': 3, 'yellow': 4, 'red': 1} |
Back to Top
Create a simple script in Python
Now you have some knowledge about Python. Next, we will create a simple Python script. The script reads the number of PHP session files in the/tmp directory of your server, and writes the summary report to the log file. In this script, you will learn how to import modules of a specific function, how to use files, and how to write log files. You will also set a series of variables to track the collected information.
Listing 12 shows the entire script. Open an editor, paste the code into it, and save the fileTMP. py. Then, runchmod + x
To make it an executable file (assuming you are using a UNIX system ).
Listing 12. tmp. py
#!/usr/bin/pythonimport osfrom time import strftimestamp = strftime("%Y-%m-%d %H:%M:%S")logfile = '/path/to/your/logfile.log'path = '/path/to/tmp/directory/'files = os.listdir(path)bytes = 0numfiles = 0for f in files:if f.startswith('sess_'):info = os.stat(path + f)numfiles += 1bytes += 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 first line, you can seeHash-bang row: It is used to identify the location of the python interpreter. In my system, it is located in/usr/bin/python. Adjust this line as required.
The next two lines are used to import specific modules, which will help you execute the job. Because the script needs to process folders and files, you need to importos
Module, because it contains various functions and methods, can help you list files, read files, and operate folders. You also need to write a log file, so you can add a timestamp for the entry-this requires a time function. You do not need all time functions, just importstrftime
Function.
In the next six rows, you have set some variables. The first variable isstamp
Contains a date string. Then, you usestrftime
The function creates a timestamp in a specific format. In this example, the timestamp format is2010-01-03 12:43:03
.
Next, createlogfile
Variable, and add a path to the file to actually store the log file message (this file does not need to actually exist ). For simplicity, I placed a log file in the/logs folder, but you can also place it elsewhere. Similarly,path
The path where the variable contains the/tmp directory. You can use any path, as long as the slash is used as the end (/
).
The following three variables are also very simple:files
The list contains all files and folders in the specified path. It also containsbytes
Andnumfiles
Two variables. Both variables are set0
The script increments these values when processing files.
After all these definitions are completed, the following is the core of the script: A simplefor
Loop, used to process files in the file list. The script calculates the file name every time it runs a loop.Sess _The script runs on the file.os.stat()
, Extract file data (such as the Creation Time, modification time, and byte size), increase progressivelynumfiles
Counter and accumulate the size of the file in bytes to the total number.
After the loop is completed, the script will checknumfiles
Whether the value in the variable is greater than 1. If the value is greater than 1, a newtitle
Set variablefiles
; Otherwise,title
Set to singularfile
.
The last part of the script is also very simple: you have createdstring
And add a row of data starting with a timestamp to the variable.numfiles
(Converted to string) and bytes (also converted to string ). Please note that the continue character (/
); This character allows the code to run to the next line. It is a small trick to improve readability.
Then, you useopen()
The function opens the log file in append mode (after all, you always need to add content to the file ),writelines()
The function adds the string to the log fileclose()
Function is used to close the file.
Now you have created a simple Python script. This script can be used to complete many tasks. For example, you can setcron
This script is Run hourly to help you track the number of PHP Sessions used within 24 hours. You can also use jquery or some other JavaScript frameworks to connect to this script through ajax to provide you with a log file feed (if this method is used, you need to useprint
Command to return data ).
Back to Top
Conclusion
As developers, we have invested a lot of time learning specific languages and methods. Sometimes, this will cause disputes between different languages. I have participated in many such debates, and I believe that is the case for readers. It should be acknowledged that most such discussions end with the same results-"What you can do, I can do it better"-in fact, this is meaningless.
However, when you look at another language, you will find that most languages have similar tools, principles, and methods. It is difficult to learn the first language, but applying your knowledge to another language can greatly simplify the learning process. Even if you do not actually migrate to the second language, you can increase your understanding of programming ideas and methods to a 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 PHP world (after all, it is a tool for your survival), but please do not stop learning.
References
Learning
- Visit Python and learn more about the language.
- Read the python documentation.
- The Python Beginners Guide is a good place to start learning the Python language.
- For free, refer to Python wikibook.
- Read "explore Python" to learn about all aspects of Python.
- Visit the developerworks Web Development Area, which provides various tools and information for Web 2.0 development.
- Php.net is a centralized resource library for PHP developers.
- Please visit "Recommended PHP reader list ".
- Browse all php content on developerworks.
- Refer to the PHP project resources on IBM developerworks to expand your PHP skills.
- To hear interesting interviews and discussions with software developers, visit {
Linkqueryappend (this)
} "Href =" http://www.ibm.com/developerworks/podcast/ "> developerworks podcasts.
- Want to use the database and PHP in combination? Please obtain Zend core for IBM, which is a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.
- {
Linkqueryappend (this)
} "Href =" http://www.ibm.com/developerworks/community "> my developerworks community covers a large number of topics and is an example of a successful community.
- Refer to recent seminars, trade exhibitions, network broadcasts, and other {
Linkqueryappend (this)
} "Href =" http://www.ibm.com/developerworks/views/opensource/events.jsp "> activity.
- Visit the developerworks open source area to get a wealth of how-to information, tools and project updates, and the most popular articles and tutorials to help you develop with open source technology, they are used in combination with IBM products.
- Stay tuned to developerworks technical events and network broadcasts.
- See the free developerworks demonstration center and learn about IBM and open-source technologies and product features.
Obtain products and technologies
- Python cookbook: Access ActiveState code, refer to the Python code example that can be used.
- You can download the IBM product evaluation trial software to improve your next open-source development project.
- Download the IBM product evaluation trial software or ibm soa sandbox for people to start using application development tools and middleware Products from DB2, Lotus, rational, Tivoli and websphere.
Discussion
- Participate {
Linkqueryappend (this)
} "Href =" http://www.ibm.com/developerworks/blogs "> developerworks blog and join the developerworks community.
- Participate in developerworks {
Linkqueryappend (this)
} "Href =" http://www.ibm.com/developerworks/forums/dw_forum.jsp? Forum = 992 & cat = 51 "> PHP Forum: Use IBM information management products (DB2 and IDs) to develop PHP applications.
About the author
Thomas Myer is a consultant, writer, and lecturer who lives in Austin. He created triple dog dare media.
Source: http://www.ibm.com/developerworks/cn/opensource/os-php-pythonbasics/index.html