源程序文件通常以.py为扩展名 #!/usr/bin/python shebang,即执行脚本时通知内容要启动的解释器 import platform 导入模块 print platform.uname() 打印执行结果 给予脚本执行权限,即可执行! chmod +x first.py ./first.py Python程序可以分解为模块、语句、表达式、对象
Python key elements
1) Basic Data type
Integal类型(整型、布尔型) 浮点类型(浮点数、复数、十进制数字) 字符串
2) object reference (variable)
Python将所有数据存为内存对象 变量是指向内存对象的引用 内建函数type()用于返回给定数据项的数据类型 >>> a = ‘hello‘ >>> type(a) str 变量命名规则: 不能数字开头,区分大小写,禁止使用保留字 注意: 变量名没有类型,对象才有
3) Combining data types
数据结构:通过某种方式组织在一起的数据元素的集合 常用的组合数据类型: 序列类型( 列表 [] 元组() 字符串 ) 集合类型( 集合 ) 映射类型( 字典 ) 注意: 组合数据类型也是对象,因此其可以嵌套 列表和元组并不真正存储数据,而是存放对象引用 内置函数len()可以测量长度 >>> l1 = [1,2,3,4] >>> len(l1) 4
4) Logical operator
身份操作符 is 判定左端对象引用是否相同于右端对象引用 比较操作符 < > <= >= != == 成员操作符 in not in 逻辑运算符 and or not
5) Control flow statements
控制流语句是过程式编程语言的基本控制机制 常见控制流语句 if while for...in try
6) Arithmetic operators
提供了完整的算术操作符 + - * / // % 也可以使用增强的赋值操作符 += -= 注意: 同样的功能,使用增强型赋值操作符性能较好 int类型不可变
7) Input/output
输出 print语句 输入 input() raw__input() print "String %format1 %format2 ..." %(variable1,varuable2,...) 简单例: >>> num = 7.8 >>> print "The num is %f and %d" % (num,2) 7.800000 2 进阶如
Example:>>> d = { ' x ' :32, ' y ' :27.490325,< Span class= "hljs-string" > ' z ' :65} >>> print "% (x) -10d% (y) 0.3g"%d 32 27.5 output two items, the first meaning is to take the dictionary d in the key named 10 represents a minimum width of 10,d represents a decimal integer, the second meaning is the value of the dictionary D with the key named Y, 0 represents a 0 fill, a decimal point is used to divide the width of the field by precision, 3 means that the maximum number of characters in the print string is Span class= "Hljs-number" >3,g indicates that the exponent is less than-4 when using%e
8) Creation and invocation of a function
The function is the basic component for modular programming using def statement definition functions Python has a number of built-in functions in the standard library with many built-in modules, there are a number of function functions in the module have return values, default to None, you can also use "return value" to define the return values syntax : def funcName (arguments) : suite example : >>> def Testfunc (arg1) : print arg1 >> > TestFunc ( "Hello fanison!") Hello fanison! >>> callable (TestFunc) True callable () can be used to test whether a function can call
Statements and syntax
注释 # 续行 \ ‘‘‘:闭合操作符,单一语句跨多行 代码组: 缩进相同(4字符) 首行关键字开始,以冒号结束 同一行放置多个语句以分号作为分隔符 import导入模块
File structure
File Main program
__name__指示模块应如何被加载 如果模块被导入,__name__的值是模块名字 如果模块直接执行,__name__的值是‘__main__‘
"Python" Python Basics