C++ C# Python JavaScript PHP разговорник

Я давно программирую на C++ и C#. Python начал изучать недавно. С JavaScript у меня с давних пор было знакомство, но шапочное, поэтому стал изучать и его. И вот решил составить «разговорник» — удобная штука, чтобы легко было вспоминать материал. Эту необъятную заметку я буду пополнять по мере изучения языков.

C++ C# Python 3 JavaScript PHP
Расширение файлов .cpp, .h, .hpp .cs .py .js .php
Исполняющая среда CPU + OS CLR (Common Language Runtime) Интерпретатор Python: CPython, IronPython, PyPy, Jython V8 (Chrome, Node.js) / SpiderMonkey (Mozilla Firefox) / Chakra (Internet Explorer) Zend Engine
Стандартная библиотека STL .NET Framework, .NET Core Стандартная библиотека СPython Web APIs (DOM, AJAX, etc.) The Standard PHP Library (SPL)

Общая структура (рыба) программы

// C++
#include <iostream>

int main(int argc, char** argv)
{
    // Your code goes here
    return 0;
}
// C#
using System;

namespace YourProjectNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Your code goes here
        }
    }
}
# Python 3
import some_module

if __name__ == "__main__":
    # This file has been launched from the command line
    # You code goes here
else:
    # This file has been imported by some other python script
    # You code goes here
'use strict'
// JavaScript (a module)
// Hello.js

export function Hello()
{
    console.log("Hello");
}

export let a = 5;
'use strict'
// JavaScript (a script that uses some module)

import {Hello, a} from './Hello.js' // since ES-2015
Hello();
console.log(a);
<?php
    // PHP
    echo "Hello, world!";
?>

Объявление локальной переменной (без инициализации)

// C++
int a;
// C#
int a;
// Although you cannot use uninitialized variable
# Python 3
a = None
// JavaScript
var a;             // (a=undefined) variable is scoped to the function in which it is declared
let b;             // (b=undefined) (since ES-2015) variable is scoped to the block in which it is declared
var c = undefined; // declare variable explicitly as undefined
var d = null;      // almost the same as undefined
<?php
    // PHP
    $a = null;
?>

Объявление локальной переменной (с инициализацией)

// C++
int a = 5;
auto b = 3.14;
// C#
int a = 5;
var b = 3.14;
# Python 3
a = 5
// JavaScript
var a = 5;
let b = 5;
<?php
    // PHP
    $a = 5;
?>

Строковые литералы

// C++
char* s = "Hello, World!";
// C#
string s = "Hello, World!";
# Python 3
s = "Hello, World!";
s = 'Hello, World!';
// JavaScript
s = 'Hello, World!';
s = "Hello, World!";
s = `Hello, World!`;
<?php
    // PHP
    $s = "Hello, World!";
    $s = 'Hello, World!';

// heredoc syntax
$str = <<<FOO
Multiline string literals, preserving
line breaks and other whitespace
(including indentation) in the text.
FOO
;

// nowdoc syntax
$str = <<<'BAR'
Nowdocs are to single-quoted strings
what heredocs are to double-quoted strings.
A nowdoc is specified similarly to a heredoc,
but no parsing is done inside a nowdoc.
BAR
;
?>

Определение функции
// C++
int sum(int a, int b)
{
    return a + b;
}
// C#
int sum(int a, int b)
{
    return a + b;
}
# Python 3
def sum(a, b):
    return a + b
// JavaScript
function sum(a, b)
{
    return a + b;
}

const square = function(x)
{
    return x ** 2;
};

Вызов функции

// C++
x = sum(y, z);
// C#
x = sum(y, z);
# Python 3
x = sum(y, z)
x = sum(a=y, b=z)
x = sum(b=z, a=y)
x = sum(3, 5)
x = sum(a=3, b=5)
x = sum(b=5, a=3)
x = sum('Hello, ', 'World!')
x = sum(a='Hello, ', b='World!')
x = sum(b='World!', a='Hello, ')
// JavaScript
x = sum(y, z);
x = square(4);

Лямбда-выражения

// C++
auto sum = [](int a, int b) { return a + b; };
var s = sum(4, 3); // s = 4 + 3
// C#
delegate int TwoIntParamsIntReturnValue(int a, int b);
...
TwoIntParamsIntReturnValuesum sum = (a, b) => { return a + b; };
var s = sum(4, 3); // s = 4 + 3
# Python 3
sum = lambda a, b : a + b
s = sum(3, 4) # a = 3 + 4
// JavaScript
let sum = (a, b) => { return a + b; };
let s = sum(4, 3); // s = 4 + 3

Вывод текста на экран (консоль)

// C++
std::cout << "Hello";
// C#
Console.WriteLine("Hello");
# Python 3
print("Hello")
// JavaScript
console.log("Hello");

Преобразование из строки в число

// C++
int a = std::atoi("5");
// C#
int a = int.Parse("5");
# Python 3
a = int("5")
// JavaScript
var a = Number("5");

Ветвления (If-ElseIf-Else)

// C++
if(a > 5)
    std::cout << "a > 5";
else if(a == 5)
    std::cout << "a == 5";
else
    std::cout << "a < 5";
// C#
if(a > 5)
    Console.WriteLine("a > 5");
else if(a == 5)
    Console.WriteLine("a == 5");
else
    Console.WriteLine("a < 5");
# Python 3
if a > 5:
    print("a > 5")
elif a == 5:
    print("a = 5")
else:
    print("a < 5")
// JavaScript
if(a > 5)
    console.log("a > 5");
else if(a == 5)
    console.log("a == 5");
else
    console.log("a < 5");

Switch-Case

// C++
switch(a)
{
    case 1:
        std::cout << "1";
        break;
    case 2:
        std::cout << "2";
        break;
    default:
        std::cout << "default";
}
// C#
switch(a)
{
    case 1:
        Console.WriteLine("1");
        break;
    case 2:
        Console.WriteLine("2");
        break;
    default:
        Console.WriteLine("default");
        break;
}
# Python 3
# There's no Switch-Case clause in Python
# You can use [if-elif-else] instead
// JavaScript
switch(a)
{
    case 1:
        console.log("1");
        break;
    case 2:
        console.log("2");
        break;
    default:
        console.log("default");
}

Цикл For

// C++
for (int i = 1; i <= 10; i++)
    std::cout << i;
// C#
for (int i = 1; i <= 10; i++)
    Console.WriteLine(i.ToString());
# Python 3
for i in range(1, 11):
    print(i)
// JavaScript
for (let i = 1; i <= 10; i++)
    console.log(i);

Цикл While

// C++
int i = 1;
while(i <= 10)
    std::cout << i;
// C#
int i = 1;
while(i <= 10)
    Console.WriteLine(i.ToString());
# Python 3
i = 1
while i <= 10:
    print(i)
    i = i + 1
// JavaScript
var i = 1;
while(i <= 10)
{
    console.log(i);
    i++;
}

Цикл ForEach

// C++
#include <vector>
...
std::vector<int> vec {0, 1, 2, 3};
for(int i : vec)
    std::cout << i;
// C#
using System.Collections.Generic;
...
var vec = new List<int> {0, 1, 2, 3};
foreach(int i in vec)
    Console.WriteLine(i);
# Python 3
vec = ['1', 2, 'hello', 3]
for i in vec:
    print(i)
// JavaScript
let array = ['1', 2, 'hello', 3];
for(let x of array)
    console.log(x);

Форматированный вывод

// C++
int x = 100;
double y = 3.14;
std::cout << "x = " << x << ", y = " << y;
// C#
int x = 100;
double y = 3.14;
Console.WriteLine("x = {0}, y = {1}", x, y);
Console.WriteLine($"x = {x}, y = {y}");
# Python 3
x = 100
y = 3.14
print( "x = %i, y = %f" % (x, y) )
print( "x = {0}, y = {1}".format(x, y) )
// JavaScript
var x = 100;
var y = 3.14;
console.log(`x = ${x}, y = ${y}`);

Возведение числа в степень

// C++
#include <cmath>
...
double x = 2.0;
double y = std::pow(x, 3);
double z = std::pow(x, 0.5);
// C#
using System;
...
double x = 2.0;
double y = Math.Pow(x, 3);
double z = Math.Pow(x, 0.5);
# Python 3
x = 2.0
y = x ** 3
z = x ** 0.5
// JavaScript
var x = 2.0;
var y = x ** 3;
var z = x ** 0.5;

Runtime Type Information

// C++
int a;
std::cout << typeid(a).name();
// C#
int a;
Console.WriteLine(a.GetType());
# Python 3
a = 5
print(type(a))
// JavaScript
let a = 5;
console.log(typeof a);

Сравнение переменных

// C++
int a = 5;
int b = 5;
std::cout << (a == b);
// C#
int a = 5;
int b = 5;
Console.WriteLine(a == b); // True
Console.WriteLine(Object.ReferenceEquals(a, b)); // False
Console.WriteLine(Object.ReferenceEquals(a, a)); // False

object c = 5;
Console.WriteLine(c == c); // True
Console.WriteLine(Object.ReferenceEquals(c, c)); // True
# Python 3
a = 5
b = 5
print(a == b) # True (value equality)
print(a is b) # True (reference equality)
// JavaScript
let a = 5;
let b = "5";
console.log(a == b);    // true (type conversion takes place)
console.log(a === b);   // false (no type conversion)
console.log(a === 5);   // true (no type conversion)
console.log(b === "5"); // true (no type conversion)

Классы

// C++
************************************************
// C#
************************************************
# Python 3
class Vector:
    # constructor
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # to string
    def __str__(self):
        return "x = {0}, y = {1}".format(self.x, self.y)

    # operator +
    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        else:
            raise TypeError("other must be a Vector")

    # operator *
    def __mul__(self, number):
        return Vector(self.x * number, self.y * number)

    # operator *
    __rmul__ = __mul__

    # example of a static method
    @staticmethod
    def originOfCoordinates(mat):
        return Vector(0, 0)
// JavaScript
************************************************
<?php
// PHP
************************************************
?>

Коллекции (списки, кортежи, множества и пр.)

// C++
#include <vector>
...
std::vector<int> lst{1, 2, 3};
lst.push_back(4);
lst.push_back(5);
for(auto i : lst)
    std::cout << i << ' '; // 1 2 3 4 5
// C#
var lst = new List<object> { 1, 2, "hello", 3 };
lst.Add("bye");
lst.Add(4);
foreach (var i in lst)
    Console.WriteLine(i);
# Python 3
lst = [1, 2, "hello", 3]
ls.append("bye")
ls.append(4)
print(ls) # [1, 2, ,"hello", 3, "bye", 4]
// JavaScript
************************************************
<?php
// PHP
************************************************
?>

************************************************

// C++
************************************************
// C#
************************************************
# Python 3
************************************************
// JavaScript
************************************************
<?php
// PHP
************************************************
?>

Добавить комментарий

Ваш адрес email не будет опубликован.