For those who want to try other languages because PHP can be written to some extent-I like Python-I have summarized the differences with PHP and the parts that should be noted. It's a Python missionary activity.
I would like to proceed based on Python 2.7.
Hello World
Anyway, this is it.
# helloworld.py
print("Hello World!")
Execute this file with the following command.
% python helloworld.py
% Hello World!
Unlike PHP, there is no convenient function that you can see if you access it via Apache, so it is troublesome, but let's execute it from the command line. CodeRunner is convenient for Mac users.
Let's implement the same in PHP and Python.
<?php
/**
*When you specify the time, the corresponding greeting will be displayed!
*/
function greet($hour) {
if ($hour > 4 && $hour < 12) {
echo "Good Morning!" . PHP_EOL;
} elseif ($hour > 12 && $hour < 18) {
echo "Good Afternoon!" . PHP_EOL;
} else {
echo "Good Evening!" . PHP_EOL;
}
}
greet(8); // Good Morning!
greet(15); // GOod Afternoon!
greet(21); // GOod Evening!
# coding=utf8
def greet(hour):
"""When you specify the time, the corresponding greeting will be displayed!"""
if 4 < hour < 12:
print("Good Morning!")
elif 12 < hour < 18:
print("Good Afternoon!")
else:
print("Good Evening!")
greet(8) # Good Morning!
greet(15) # GOod Afternoon!
greet(21) # GOod Evening!
I will explain one by one.
Suddenly a mysterious code. What's on the first line of Python code? ..
# coding=utf8
Actually, without this, Japanese (multibyte characters) cannot be written in the Python source code. ..
By default, Python determines the character code of the source code as ʻASCII, so you can't read it unless you tell ** "This is written in UTF-8!" **. It's a hassle, but please think of it as
magic`.
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# coding=utf8
print("Actually, you can write in various ways.")
By the way, lines starting with #
are treated as comments in Python.
It's the same as //
in PHP.
Whenever you define a variable in PHP, you have to prefix the variable name with $
, but in Python it is not.
It's OK if you write the variable name obediently.
variable = 10
That's right.
PHP required a ; (semicolon)
at the end of the process, but Python does not.
print("There is no semicolon in the butt! !! !!")
I also saw this.
PHP uses function
, but Python uses def
.
Another difference is that Python doesn't need {}
.
As you know because it's famous, Python doesn't use {}
to represent scopes, it uses indent
.
def func(argument): #Last: (colon)Don't forget!
print(argument)
Like functions, if statements use indent
instead of{}
to express the scope.
Also, you don't need ()
where you define the conditional expression.
You must also add a : (colon)
to the end of the if statement.
if 4 < hour < 12: #It's annoying to write a colon! !! !!
print("Good Morning!")
Strictly speaking, it is not about if statements, but there are differences in the description method of conditional expressions.
In PHP, the && operator
is used to connect conditional expressions, but in Python, the ʻand operator` is used.
hour > 4 and hour < 12
PHP||operator
How to write in Python is as you can imagine.
hour > 4 or hour < 12
** "Oh, the ʻand operator` doesn't appear in the sample above." **
For those who think, in Python, conditional expressions of inequality signs can be written by connecting them as follows-convenient.
4 < hour < 12
First, let's write the same thing in both PHP and Python.
<?php
$jobs = array(
"John" => "Guitar",
"Paul" => "Guitar",
"George" => "Bass",
"Ringo" => "Drums",
);
foreach ($jobs as $name => $job) {
printf("%s: %s" . PHP_EOL, $name, $job);
}
$names = array("John", "Paul", "George", "Ringo");
for ($i = 0; $i < count($names) ; $i++) {
printf("%d: %s" . PHP_EOL, $i, $names[$i]);
}
# coding=utf8
jobs = {
"John": "Guitar",
"Paul": "Guitar",
"George": "Bass",
"Ringo": "Drums",
}
for name, job in jobs.items():
print("{}: {}".format(name, job))
names = ["John", "Paul", "George", "Ringo"]
for index, name in enumerate(names)):
print("{}: {}".format(index, names[index])
In PHP, both array with subscripts of numbers and associative array with subscripts of strings are defined by ʻarray, but in Python,
list / [] and
dict / {} `are used respectively.
#list
names = ["John", "Paul", "George", "Ringo"]
names = list("John", "Paul", "George", "Ringo")
#dictionary
jobs = {
"John": "Guitar",
"Paul": "Guitar",
"George": "Bass",
"Ringo": "Drums",
}
jobs = dict( #I wonder if I can write this way too much. ..
John="Guitar",
Paul="Guitar",
George="Bass",
Ringo="Drums",
)
Note in the dictionary that ** element order is not preserved! !! !! ** **
In the example, the elements are defined in the order of John``` Paul
George`` Ringo
, but if you look at the execution result, you will see that the output order has changed.
Like the ʻif statement, the
for statement does not have a
() , and instead of the
{} , the scope must be represented by a
indentand a
: (colon)` must be added at the end.
Python's for statement
is similar to PHP's foreach statement
.
There is no so-called ordinary for statement
likefor ($ i = 0; $ i <10; $ i ++)
.
If you say "I really want to write it", it will look like the following.
for index in range(0, 10):
print(index)
When the list
is turned by the for statement
, the element
is returned as it is, and the element number (subscript)
cannot be obtained.
names = ["John", "Paul", "George", "Ringo"]
for name in names:
print(name)
If you want to take the element number (subscript)
together, use the ʻenumerate function`.
names = ["John", "Paul", "George", "Ringo"]
for index, name in enumerate(names)):
print("{}: {}".format(index, names[index])
If you turn the dictionary
with a for statement
, you will get the key (subscript)
instead of the element
. ..
jobs = {
"John": "Guitar",
"Paul": "Guitar",
"George": "Bass",
"Ringo": "Drums",
}
for name in jobs:
print(name)
Use the ʻitems method to get both the
elementand the
key (subscript)`.
jobs = {
"John": "Guitar",
"Paul": "Guitar",
"George": "Bass",
"Ringo": "Drums",
}
for name, job in jobs.items():
print("{}: {}".format(name, job))
It's a little confusing. ..
It's a small place, but it's a very important story.
Null
in PHP is written as None
in Python.
Note that the acronym is capital
.
The words are the same, but the acronym is capital
.
Let's be careful.
Isn't there a cancellation !
That is often used in ʻif statements? Please note that it will be
not` in Python.
if not result:
print('Failed.')
However, ! =
Remains the same.
if result != True:
print('Failed.')
There are a lot of things that I can't explain, but for the time being, it's like this. .. Next, let's talk about functions.
Recommended Posts