Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python VS PHP 基础语法

$
0
0

这几天在学习 python ,鄙人平时学习中为了方便记忆和更好的比较与理解语言二者之间在某些情况的优劣性,所以花了点时间,整理了一下 Python 和 php 常用语法的一些区别。

一、大小写

PHP:

所有用户定义的函数、类和关键词(例如 if、else、echo 等等)都对大小写不敏感; 所有变量都对大小写敏感。

Python:

1. 大小写敏感的。

二、变量

PHP:

1. 以“$”标识符开始 如 $a = 1 方式定义

Python:

1. 直接定义 如 a = 1 方式

三、数组/集合

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

这里要说一下, Python 的数组类型有以下几种:

list: 链表,有序的项目,通过索引进行查找,使用方括号“[]”; test_list=[ 1, 2, 3, 4, 'Oh'] tuple: 元组,元组将多样的对象集合到一起,不能修改,通过索引进行查找,使用括号”()”; test_tuple=( 1, 2, 'Hello',( 4, 5)) dict: 字典,字典是一组键(key)和值(value)的组合,通过键(key)进行查找,没有顺序, 使用大括号”{}”; test_dict={ 'Wang': 1, 'Hu': 2, 'Liu': 4} set: 集合,无序,元素只出现一次, 自动去重,使用”set([])” test_set=set([ 'Wang', 'Hu', 'Liu', 4, 'Wang'])

打印:

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']) 四、条件判断

PHP:

if($age = 'man'){ echo "男"; }else if($age < 20 and $age > 14){ echo "女"; }else{ echo "嗯哼"; }

Python:

sex = '' if sex == 'man': print('男') elif sex == 'women': print('女') else: print('这~~') 五、循环

PHP:

$arr = array('a' => '苹果', 'b' =>'三星', 'c' => '华为', 'd' => '谷歌'); foreach ($arr as $key => $value){ echo "数组key:".$key."<br>"; echo "key对应的value:".$value."<br>"; }

Python:

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]) 六、函数

PHP:

function calc($number1, $number2 = 10) { return $number1 + $number2; } print(calc(7));

Python:

def calc(number1, number2 = 10): sum = number1 + number2 return sum print(calc(7))

有什么讲错的地方或者好的建议,欢迎留言。


Viewing all articles
Browse latest Browse all 9596

Trending Articles