I have been learning Python these days. In order to facilitate my memory and better compare and understand the advantages and disadvantages of the two languages in certain situations, I spent some time sorting out Python and PHP. Some differences in common syntax.
1. Case
PHP:
All user-defined functions, classes and keywords (such as if, else, echo, etc.) All variables are case-insensitive;
All variables are case-sensitive.
Python:
1. Case sensitive.
2. Variables
PHP:
1. Start with the “$” identifier such as $a = 1 and define
Python:
1. Direct definition such as a = 1 method
3. Array/Collection
PHP:
// 定义 $arr = array('Michael', 'Bob', 'Tracy'); // 调用方式 echo $arr[0] // Michael // 数组追加 array_push($arr, "Adam"); // array('Michael', 'Bob', 'Tracy','Adam');
Python:
# list方式(可变) classmates = ['Michael', 'Bob', 'Tracy'] # 调用方式 print(classmates[0]) # 'Michael' # 末尾追加元素 classmates.append('Adam') # ['Michael', 'Bob', 'Tracy', 'Adam'] # 指定插入位置 classmates.insert(1, 'Jack') #['Michael', 'Jack', 'Bob', 'Tracy'] # 删除指定元素 classmates.pop(1) #['Michael', 'Bob', 'Tracy']
What to say here Let’s take a look, Python’s array types are as follows:
list: linked list, ordered items, search by index, use square brackets "[]";
test_list = [1, 2, 3, 4, 'Oh']
print(test_list) print(test_tuple) print(test_dict) print(test_set)
[1, 2, 3, 4, 'Oh'] (1, 2, 'Hello', (4, 5)) {'Liu': 4, 'Wang': 1, 'Hu': 2} set(['Liu', 4, 'Wang', 'Hu'])
if($age = 'man'){ echo "男"; }else if($age < 20 and $age > 14){ echo "女"; }else{ echo "嗯哼"; }
<p>sex = ''<br/>if sex == 'man':<br/> print('男')<br/>elif sex == 'women':<br/> print('女')<br/>else:<br/> print('这~~')<br/></p>
$arr = array('a' => '苹果', 'b' =>'三星', 'c' => '华为', 'd' => '谷歌'); foreach ($arr as $key => $value){ echo "数组key:".$key."<br>"; echo "key对应的value:".$value."<br>"; }
arr = {'a': '苹果', 'b': '三星', 'c': '华为', 'd': '谷歌'} # 第一种 for (key,value) in arr.items(): print("这是key:" + key) print("这是key的value:" + value) # 第二种 for key in arr: print("这是key:" + key) print("这是key的value:" + arr[key])
function calc($number1, $number2 = 10) { return $number1 + $number2; } print(calc(7));
def calc(number1, number2 = 10): sum = number1 + number2 return sum print(calc(7))
The above is the detailed content of Detailed introduction to the basic syntax of Python VS PHP. For more information, please follow other related articles on the PHP Chinese website!