From PHP to Python Through Simple CLI Examples

Writing apps with a programming language is always good news. Most probably you already feel comfortable with some important concepts in computer science and are ready to learn Python right away.

Most programming tutorials out there often follow a scheme like this:

  • Introduction
  • Operators
  • Flow control
  • Data structures
  • Object oriented principles

However the important concepts are usually the same in most languages. So what if you just want a quick overview of Python as a PHP developer, or vice versa? This post provides a big picture about how PHP and Python relate to each other, and is specially aimed to PHP developers who want to plunge into Python quickly.

Before diving in, be sure to set up your environment. Install a new version of PHP and Python as well as an IDE that allows you to work with multiple languages at the same time.

This is what I have used to run the examples.

  • OS: Debian 9 Stretch
  • Desktop Environment: LXDE
  • PHP 7.2
  • Python 3.5.3
  • IDE: Eclipse IDE for PHP Developers with the PyDev plugin

There won’t be enough space in this post to mention all differences and similarities between PHP and Python since I will mainly focus on the command line side of things.

Without any further ado, let’s get started!

0. PHP’s Focus Is Web Dev While Python Is a General Purpose Language

PHP stands for PHP: Hypertext Preprocessor and it was designed for web development. Its focus is the Web, but it lacks support for data science. With a few exceptions like NumPHP, which is inspired by NumPy, or PHP-ML (PHP Machine Learning), there are no PHP equivalents to SciPy, Pandas, Matplotlib and many other powerful Python tools that shine in data analysis, statistics and machine learning.

When it comes to developing desktop applications Python is also a more practical choice than PHP.

Nowadays Python is probably a better choice than PHP for writing desktop and data science apps, but some will still stick with PHP arguing that is okay for Web development. Be that as it may, a simple way to get started with Python as a PHP developer is the CLI.

1. PHP and Python Are Interpreted

The interactive mode helps you take baby steps when learning a programming language since it allows you to play around with code snippets. Can you spot the difference between these two hello worlds?

Exactly. In Python there’s no need to write semicolons at the end of the sentences.

But most importantly, this example illustrates how commands can be read directly from the tty. Both PHP and Python are similar in a sense that they are interpreted. They don’t need to be translated into machine code by a compiler, but are run directly on the fly by an interpreter.

As a result scripts are run through the interpreter this way.

By the way, PHP’s and Python’s syntax are quite different from each other – this example was to break the ice first.

2. Off-Side Rule vs Free-Form

Here is another visual exercise: A function that calculates whether or not a given number is prime.

number.php

number.py

To the experienced eye it is straightforward to figure out what it does.

As you see, the Python flavor is a bit more concise than its PHP counterpart because Python does not require curly brackets when defining if statements, loops, functions, classes and so on, as PHP does. Code blocks are denoted by indentation the amount of which doesn’t matter as long as blocks are well-structured – PEP 8 recommend four spaces.

Technically speaking, Python adheres to the off-side rule whereas PHP belongs to the free-form family of languages.

If you can’t wait to learn more about the import statement please go to section 9. Python Is Modular.

3. Coding Conventions: PSR vs PEP

At this point, don’t worry if you feel a bit insecure on camelcasing, docstrings, how long the lines of your code should be, how many indent spaces your code must have, and things of that nature.

Code recommendations come to the rescue!

Look at the PHP Standards Recommendations (PSR) on the on hand and the Style Guide for Python Code (PEP 8) on the other, and learn about writing code as it is recommended by the developers community.

Here are two tips for visual learners and lazy programmers that will speed up the learning process of coding conventions.

  1. Browse a few trending repositories on GitHub and observe how developers write their code
  2. Use a coding standards checker like pycodestyle

4. Python and PHP Are Dynamically Typed

Let’s keep on spotting differences and similarities between PHP and Python little by little, by adding a factorial function to the files that we created in section 2. Off-Side Rule vs Free-Form.

number.php

number.py

Some obvious differences: The reserved word function is to define a function in PHP, whereas in Python it is the word def, which means define. In PHP variables start with the $ symbol because PHP is influenced by a few other languages like Perl – which in turn was inspired by shell scripting where variables start with a dollar sign too. This is not the case with Python.

And here is a nice, important common trait: Both Python and PHP are dynamically typed. In contrast to statically typed languages such as Java and C++, with PHP and Python you don’t have to declare variables to be of a particular type in order to access them later.

5. Mixing Data: Weakly Typed vs Strongly Typed

The example below concatenates a string and an integer.

This is to show you that Python is more strict than PHP when it comes to mixing data types. Now, try to add a string to an integer:

Cool! Note how PHP doesn’t throw any errors allowing to combine different types of data, performing an implicit type conversion when necessary. Technically speaking, the former is weakly typed whereas the latter is strongly typed.

Don’t let arithmetic operations mislead you:

Python does not throw an error when mixing an int with a float because it does support mixed arithmetic. Remember, arithmetic operations can be run on operands of different numeric types.

6. Case Sensitivity

yOu kNow, CaSE-sEnSiTIveNesS!

Python is case sensitive while PHP is partially case sensitive. PHP is case insensitive in some cases only: user defined functions, class methods and keywords such as if, else, null, foreach, echo, among others.

7. PHP Arrays Are Equivalent to Python Lists and Python Dictionaries

This section is about data structures. We are adding to the number.php and number.py files above a new function that calculates the first n Fibonacci numbers.

number.php

number.py

The new thing being introduced is a sequence of numbers, in other words, a data structure that stores a collection of integer values. In PHP this is called array while in Python it is called list. Let’s see how this works.

The examples above are easy, but the terminology used for referring to data types may be a bit tricky. The reason being: PHP arrays are not actually arrays in the traditional sense of the word where an array is a data structure storing elements of the same type. A PHP array is actually a dictionary with an optional key, which, if not specified, will behave as a Python list.

PHP arrays are can be seen as an equivalent to Python lists and dictionaries also, as it is shown next.

Dictionary, associative array, map and symbol table, all these are synonyms. The important thing is that PHP arrays, Python lists and Python dictionaries, they all are flexible data structures that enable to create collections of mixed types — integers, strings, objects, etc. — referenced with a key.

8. Primitive Data Types and Data Structures

Regarding built-in data types, PHP comes out-of-the-box with boolean, integer, float and string. These are the so-called scalar that you’d also expect to find in languages like C++ and Java. On the other hand, there’s no such thing in Python where everything is an object. By analogy we can say that Python supports boolean, int, float, complex and str, but remember: those are objects.

PHP has one built-in data structure only, array, which is actually a flexible dictionary as it was pointed out in the previous section. However, PHP provides you with useful data structures through the Standard PHP Library (SPL).

Python natively supports lists, dictionaries, tuples and sets. Additional data structures are implemented in modules, for example heapq, which provides an implementation of the heap queue algorithm.

9. Python Is Modular

The following two examples write the data contained in a PHP array and a Python list into a CSV file, respectively.

write_olympics.php

write_olympics.py

The idea consists in opening a file for writing and then iterate through to print the elements one by one in the form of a CSV row.

Note that apart from built-in functions such as open() and range(), just to name a few, the Python Standard Library also provides a lot of functionality encapsulated in modules. The csv module gives you a bunch of functions for reading/writing files into the file system. This contrasts with PHP where functionality is out there – the fputcsv function can be called in PHP apps straightaway without including anything first.

The next script is called from the command line with two parameters (an integer and a CSV file name) so that the second one, triangular.csv, will contain the 1,000 first triangular numbers.


write_triangular.php


write_triangular.py

In PHP, command line arguments are accessed directly through the $argv array. Notice, on the other hand, that write_triangular.py has to import the sys module first because Python implements a modular philosophy by design.

Writing your own Python modules is a piece of cake. Remember the number.php and number.py files that we already created? This is a module. Yeah. We’ve been developing our own module since section 2. Off-Side Rule vs Free-Form without even realizing it. Now, imagine we’re writing a recreational math app on famous integer sequences. We want a custom module with Fibonacci, triangular numbers, square numbers and primes.

number.php

number.py

That’s it. We just added the triangular() and square() functions to the number module. It’s all about adding definitions which will be imported at some point whenever is required.

As you see, a PHP equivalent to Python’s import is the include statement (require and require_once are an option too).

10. Access Modifiers in Object Oriented Programming

The next code is uncomplicated if you are already familiar with object oriented principles.

chess.php

chess.py

The Piece class represents a chess piece, and the methods available are the getters and set_position() only.

Think about it, it certainly doesn’t make sense to change the color or the name of a chess piece once it is instantiated – the only exception are pawns but they are out of the scope of this example. We want to hide from the outside world the piece’s name and color, but not its position on the board.

As a PHP programmer, the interesting thing to be noted is that Python doesn’t support access modifiers like private and protected; everything is public in Python.

The semantics of private and protected is expressed by convention: a single underscore (_) means protected and a double underscore (__), also called dunder, means private. But in reality nothing stops you from accessing “private” variables starting with a dunder, which names are mangled by Python as shown below.

Be aware that accessing the piece’s color like this is just an example for learning purposes since it is considered a bad practice in Python. Despite the fact that it is technically possible to access the __color variable through the mangled name _Piece__color, you shouldn’t do so because it doesn’t make sense to change that value.

PHP instead doesn’t allow to access private properties:

Conclusion

That’s all for today. I hope this post helped you get a big picture of Python from a PHP perspective — again, I am sorry if I didn’t mention something important since this is a fairly broad topic! Here are the differences and similarities that we have addressed.

PHP Python
Purpose Web General
Interpreted Yes Yes
Free software Yes Yes
Code blocks Free-form Off-side rule
Style guide PSR PEP 8
Dynamically typed Yes Yes
Type system Weak Strong
Mixed arithmetic Yes Yes
Case sensitive Partially Yes
Data types Are scalars: boolean, integer, float and string Are objects: boolean, int, float, complex and str
Data structures array, and the Standard PHP Library (SPL) list, dict, tuple, set, and other modules
Modular No Yes
Object-oriented design support Yes Yes
Access modifiers Yes No
0 comentarios

¿Me dejas un comentario? ¡Gracias!

Deja un comentario

Los campos obligatorios están marcados con *