简介
有兴趣可以看看: 解释性语言+动态类型语言+强类型语言
交互模式:(主要拿来试验,可以试试 ipython)
$python
>>> print 'hello world'
脚本
#!/usr/bin/env python
print 'hello world'
环境:
建议python2.7 + easy_install + pip + virtualenv + ipython
缩进
Python 函数没有明显的 begin 和 end,没有标明函数的开始和结束的花括号。唯一的分隔符是一个冒号 (:),接着代码本身是缩进的。
例子:
#函数
def func(value):
print value #缩进
if value == 1:
value += 1
elif value == 2:
pass
else:
value += 10
标识符
变量是标识符的例子。 标识符 是用来标识 某样东西 的名字。在命名标识符的时候,你要遵循这些规则:
1.python中的标识符是区分大小写的。
2.标示符以字母或下划线开头,可包括字母,下划线和数字,大小写敏感
3.以下划线开头的标识符是有特殊意义的。
以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用“from xxx import *”而导入;
以双下划线开头的(__foo)代表类的私有成员;
以双下划线开头和结尾的(foo)代表python里特殊方法专用的标识,如init()代表类的构造函数。
4.标识符不能是保留字
and elif global or yield
assert else if pass
break except import print
class exec in raise
continue finally is return
def for lambda try
del from not while
变量
赋值语句
1、赋值语句建立对象引用值
2、变量名在首次赋值时会被建立
3、变量名在引用前必须先赋值,不能引用未声明赋值的变量
赋值方式
简单赋值
Variable(变量)=Value(值)
s = ‘spam'
多变量赋值
python中原始的元组和列表赋值语句形成,最后已被通用化,以接受右侧可以是是任何类型的序列,只要长度相等即可。注意,长度一定相等
Variable1,variable2,...=Value1,Value2,...
s,h = ‘a','b' 元组赋值,位置性 【常用】
[s,h] =[‘a','b'] 列表赋值,位置性
a,b,c,d = ‘spam' 序列赋值,通用性
a,*b = ‘spam' 拓展序列解包(python3)
多目标赋值
a=b=variable
s = h = ‘spam' 多目标赋值
注意:多个变量内存中指向同一对象,对于可变类型需要,修改一个会对其他造成影响
自变赋值
如+=,-=,*=等。
在自变赋值中,python仅计算一次,而普通写法需计算两次;
自变赋值会修改原始对象,而不是创建一个新对象。
s +=42 增强赋值
x += y
优点:
左侧只需计算一次,优化技术自动原处修改,更快
l +=[] 原处修改
l = l+[] 复制,生成新的对象
运算符
一个表达式可以分解为运算符和操作数
运算符 的功能是完成某件事,它们由如+这样的符号或者其他特定的关键字表示
运算符需要数据来进行运算,这样的数据被称为 操作数
运算符优先顺序列表(从最高到最低)
运算符 描述
'expr' 字符串转换
{key:expr,...} 字典
[expr1,expr2...] 列表
(expr1,expr2,...) 元组
function(expr,...) 函数调用
x[index:index] 切片
x[index] 下标索引取值
x.attribute 属性引用
~x 按位取反
+x,-x 正,负
x**y 幂
x*y,x/y,x%y 乘,除,取模
x+y,x-y 加,减
x>y 移位
x&y 按位与
x^y 按位异或
x|y 按位或
x
x is y,x is not y 等同测试
x in y,x not in y 成员判断
not x 逻辑否
x and y 逻辑与
x or y 逻辑或
lambda arg,...:expr Lambda匿名函数
结合规律
运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算
计算顺序
默认地,运算符优先级表决定了哪个运算符在别的运算符之前计算。然而,如果你想要改变它们的计算顺序,你得使用圆括号。好的做法:默认对复杂的运算加括号,而不是依赖于默认结合和计算顺序
真值
真值测试
1、任何非零数字或非空对象都为真
2、数字零,空对象以及特殊对象None都为假
3、比较和相等测试都会递归地运用到数据结构中
4、比较和相等测试会返回True或False
真值表
对象/常量 值
"" 假
"string" 真
0 假
2>=1 真
-2()空元组 假
[]空列表 假
{}空字典 假
None 假
布尔表达式
三种布尔表达式运算符
x and y
x or y
not x
比较
数字通过相对大小进行比较
字符串时按照字典顺序的,一个字符一个字符比较
列表和元组从左到右对每部分的内容进行比较
字典通过排序后的键值列表进行比较
数字混合类型比较在python3是错误的,但是python2.6支持,固定但任意的排序规则
布尔数
有两个永远不改变的值True,False
布尔是整型的子类,但不能被再继承
没有nonzero()方法的对象的默认值是True
对于值为0的任何数字或空集,值False
在数学运算中,Bollean值的True和False分别对应于1和0
基本控制流
if
基本的条件测试语句,用来判断可能遇到的不同情况,并针对不同的情况进行操作
基本形式
if :
elif :
else:
注意
python根据缩进判断, elif和else部分是可选的
例子:
a = 1
b = 2
c = 3;d=4 #两个放一句用分号隔开,不过建议分行
if a print("branch a")
elif a == b:
print("branch b")
else:
print("branch c")
switch
python 本身没有 switch 语句,若需要,用if/elif/else实现完成同样的工作,某些情况可以考虑用字典
也可以用dict的形式
if/else三元运算符
A = ((X and Y) or Z)
A = Y if X else Z
例: a = ‘t' if x else ‘a'
[code]
for
基本语法
循环控制语句,可以用于循环遍历某一序列
else块可选,在循环终止的时候执行,若是break终止循环,else不执行
格式:
[code]
for in :
if:
break
if:
continue
else:
注意:
1.对象集合可以是列表,字典以及元组等
2.for..in循环对于任何序列都适用
3.for遍历一个字典时,遍历的是字典的键
rang & xrange
可以通过range()函数产生一个整数列表,完成计数循环
range([start,] stop[, step])
start可选参数,起始数
stop终止数,若为x,产生从0-(x-1)的整数列表
step可选参数,步长,未写默认为1
range(1,5) 包含序列为 [1,2,3,4]
xrange和range区别
(python3.x的可无视)
在Range的方法中,它会生成一个list的对象,但是在XRange中,它生成的却是一个xrange的对象,当返回的东西不是很大的时候,或者在一个循环里,基本上都是从头查到底的情况下,这两个方法的效率差不多。但是,当返回的东西很大,或者循环中常常会被Break出来的话,还是建议使用XRange,这样既省空间,又会提高效率。
>>> print range(1, 5)
[1, 2, 3, 4]
>>> print xrange(1, 5)
xrange(1, 5)
在上面语句中,range返回了一个普通List,而xrange返回了一个特定的xrange类型的对象。由于 xrange 方法也创建整数 list(其使用相同参数),所以它与 range 方法非常相似。但是,xrange 方法仅在需要时才在 list 中创建整数。当需要迭代大量整数时,xrange 方法更适用,因为它不会创建极大的 list,那样会消耗大量计算机内存。
while
与if语句类似,含一个条件测试语句,循环,允许重复执行一个语句块。
可选else语句块,同for的else块。
格式:
while :
if :
break
if :
continue
else:
说明:
while循环条件变为False的时候,else块才被执行
若是使用break结束循环,while可选的else块不执行
python没有do while或do until循环语句
break & continue & pass
break,终止循环语句,停止循环,若是for/while循环中终止,其else不执行
continue,结束当前,进入下一轮循环 - 跳到最近所在循环的开头处(来到循环首行)
pass 什么事也不做,只是空占位语句,它用于那些语法上必须要有什么语句,但程序什么也不做的场合
循环else块 :只有循环正常离开时才会执行,即
如果你从for或while循环中break终止 ,任何对应的循环else块将不执行。记住,break语句也可以在for循环中使用
其他
编写循环的技巧:
在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这样的情况)。如果你想要修改你迭代的序列(例如,复制选择项),你可以迭代它的复本。使用切割标识就可以很方便的做到这一点
>>>
... if len(x) > 6: a.insert(0, x)
在字典中循环时,关键字和对应的值可以使用 iteritems() 方法同时解读出来
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到。
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.