A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.
Basic Function
<?php
function greet(string $name): string {
return "Hello, " . $name . "!";
}
echo greet("Alice"); // Hello, Alice!
Default Parameter Values
<?php
function makeConnection(string $host, int $port = 3306, string $charset = "utf8mb4"): string {
return "$host:$port ($charset)";
}
echo makeConnection("localhost"); // localhost:3306 (utf8mb4)
echo makeConnection("db.example.com", 5432, "utf8"); // custom values
Type Hints and Return Types
<?php
function add(int $a, int $b): int {
return $a + $b;
}
function divide(float $a, float $b): ?float {
if ($b == 0) return null; // nullable return type
return $a / $b;
}
var_dump(divide(10, 0)); // NULL
var_dump(divide(10, 3)); // float(3.333...)
Variadic Functions
<?php
function sum(int ...$numbers): int {
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
echo sum(1, 2, 3, 4, 5); // 15
$nums = [1, 2, 3];
echo sum(...$nums); // spread operator: 6
Anonymous Functions and Closures
<?php
$double = function(int $n): int {
return $n * 2;
};
echo $double(5); // 10
// Closure — capture variable with use
$multiplier = 3;
$multiply = function(int $n) use ($multiplier): int {
return $n * $multiplier;
};
echo $multiply(5); // 15
// Arrow function (PHP 7.4+)
$triple = fn($n) => $n * 3;
echo $triple(5); // 15