Getting Started with Python for PHPer-Super Basics

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.

Basic description method

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.

What is # coding = utf8?

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.

I don't need $ in the variable name

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

At the end of the process; (semicolon) No need

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! !! !!")

The way to write the function definition is different

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)

You don't need parentheses in the if statement

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!")

How to write a conditional expression

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||operatorHow 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

Examples of loops and arrays

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])

Arrays and lists, associative arrays and dictionaries

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.

How to write a for statement

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)

Precautions when turning the list with a for statement

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])

Precautions when turning a dictionary with a for statement

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 thekey (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. ..

Minor differences

It's a small place, but it's a very important story.

None, not null

Null in PHP is written as None in Python. Note that the acronym is capital.

True instead of true, False instead of false

The words are the same, but the acronym is capital. Let's be careful.

Not!

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.')

Summary

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

Getting Started with Python for PHPer-Super Basics
Getting Started with Python for PHPer-Classes
Getting Started with Python Basics of Python
Getting Started with Python for PHPer-Functions
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python
Getting Started with Python Functions
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Settings for getting started with MongoDB in python
Getting Started with Google App Engine for Python & PHP
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Getting Started with Lisp for Pythonista: Supplement
Django 1.11 started with Python3.6
Python basics ② for statement
Getting Started with Golang 2
Getting started with apache2
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Getting started with Python with 100 knocks on language processing
MongoDB Basics: Getting Started with CRUD in JAVA
Getting started with AWS IoT easily in Python
Materials to read when getting started with Python
Getting Started with python3 # 2 Learn about types and variables
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Get started with Python! ~ ② Grammar ~
Getting Started with Django with PyCharm
Getting Started with python3 # 3 Try Advanced Computations Using Import Statements
Getting Started with Mathematics Starting with Python Programming Challenges Personal Notes-Problem 1-1
Get started with Python! ~ ① Environment construction ~
SNS Python basics made with Flask
Link to get started with python
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Getting Started with Sparse Matrix with scipy.sparse
Getting Started with Cisco Spark REST-API
Getting started with USD on Windows
Get started with Python in Blender
Getting Started with CPU Steal Time
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Python basics