Python入门基本语法

来源:互联网 发布:淘宝电脑主机便宜原因 编辑:程序博客网 时间:2024/05/14 21:36
Python入门基本语法
Python标识符
Python不允许标点字符标识符,如@,$和%。Python是一种区分大小写的编程语言
Python中不使用括号来表示代码类/函数定义块或流量控制
代码块由行缩进,这是严格执行表示
多行语句
允许使用续行字符(\)表示该行应该继续。例如:
total = item_one + \
        item_two + \
        item_three
包含在语句[], {}, 或()括号内不能使用续行字符。例如:
days = ['Monday', 'Tuesday', 'Wednesday',
             'Thursday', 'Friday']
在Python中的引号
Python的接受单引号('),双引号(“)和三('''或”“”)引用来表示字符串
在Python中的注释
哈希符号(#)
在一行上的多个语句
分号(;)允许在单一行上编写多条语句
多组语句称为套件
if expression : 
   suite
elif expression : 
   suite 
else : 
   suite
给变量赋值
miles   = 1000.0   
name    = "John" 
Python字符串
str = 'Hello World!'
print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 6th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python 列表   
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd to 4th
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python 元组 元组可以被认为是只读的列表
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')
print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd to 4th
print tuple[2:]       # Prints elements starting from 3rd element
print tinytuple * 2   # Prints list two times
print tuple + tinytuple # Prints concatenated lists
Python字典 由键值对组成
tinydict = {'name': 'john','code':6734, 'dept': 'sales',2: 'saxxs'}
print tinydict['name']  # Prints value for 'name' key
print tinydict[2]       # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values
john
saxxs
{'dept': 'sales', 2: 'saxxs', 'code': 6734, 'name': 'john'}
['dept', 2, 'code', 'name']
['sales', 'saxxs', 6734, 'john']  
Python基本运算符
运算符 描述 示例
+ 加法 - 运算符的两侧的值增加 a + b = 30
- 减法- 从操作符左侧减去右手侧的值 a - b = -10
* 乘法- 相乘的运算符的两侧值 a * b = 200
/ 除法 - 由操作符的右侧的值除以左侧的值 b / a = 2
% 模- 由运算符的左侧除以运算符右侧返回余数 b % a = 0
** 指数幂- 执行运算符的指数(幂)计算 a**b = 10 的 20 次幂
// Floor Division - Floor除法 - 操作数相除,其结果的小数点后的数字将被删除。9//2 = 4 , 9.0//2.0 = 4.0
== 检查两个操作数的值是否相等,如果是,则条件为真。 (a == b) 不为真 true.
!= 检查两个操作数的值相等与否,如果值不相等,则条件变为真。 (a != b) 为 true.
<> 检查两个操作数的值相等与否,如果值不相等,则条件变为真。 (a <> b) 为 true. 这个类似于 != 运算符
> 检查左边的操作数的值是否大于右操作数的值,如果是,则条件为真。 (a > b) 不为 true.
< 检查左边的操作数的值是否小于右操作数的值,如果是,则条件为真。 (a < b) 为 true.
>= 检查左边的操作数的值是否大于或等于右操作数的值,如果是,则条件为真。 (a >= b) 不为 true.
<= 检查左操作数的值是否小于或等于右操作数的值,如果是,则条件变为真。 (a <= b) 为 true.
= 简单的赋值运算符,从右侧的操作数赋值给左侧的操作数 c = a + b 将分配 a + b 的值到 c
+= 相加并赋值运算符,它增加了右操作数到左操作数并分配结果到左操作数 c += a 相当于 c = c + a
-= 相减并赋值运算符,它从左操作数减去右操作数并分配结果到左边操作数 c -= a 相当于 c = c - a
*= 乘法并赋值运算符,左操作数乘以右边的操作数并分配结果值到左操作数 c *= a 相当于 c = c * a
/= 除法并赋值运算符,左操作数除以右操作数并分配结果到左操作数 c /= a 相当于 c = c / a
%= 模量和赋值运算符,两个操作数模量并分配结果到左操作数 c %= a 相当于 c = c % a
**= 指数和赋值运算符,执行指数(次幂)计算的运算符并赋值给左操作数 c **= a 相当于 c = c ** a
//= Floor除法,并分配一个值,执行Floor除法运算并赋值给左操作数 c //= a 相当于 c = c // a
& 二进制和操作拷贝位结果,如果它存在于两个操作数。 (a & b) = 12 也就是 0000 1100
| 二进制或运算符复制位如果它存在一个操作数中。 (a | b) = 61 也就是 0011 1101
^ 二进制异或运算符复制,如果它设置在一个操作数,而不是两个比特。 (a ^ b) = 49  也就是 0011 0001
~ 二进制的补运算符是一元的,具有“翻转”位的效应。 (~a ) = -61 也就是 1100 0011 以2的补码形式,由于一个带符号二进制数。
<< 二进制向左移位运算符。左边的操作数的值向左移动由右操作数指定的位数。 a << 2 = 240 也就是 1111 0000
>> 二进制向右移位运算符。左边的操作数的值是通过右操作数指定向右移动的位数。 a >> 2 = 15 也就是 0000 1111
and 所谓逻辑和运算符。如果两个操作数为真,那么则条件为真。 (a 和 b) 为 true.
or 所谓逻辑OR运算符。如果任何两个操作数都非零那么条件变为真。 (a 或 b) 为 true.
not 所谓逻辑非运算符。用来反转其操作数的逻辑状态。如果条件为真,那么逻辑非操作符执行结果则为假。not(a && b) 为 false.
in 计算结果为真,如果找到了变量指定的序列,否则为假。 x 在 y 中, 这里 in 结果是 1 ,如果 x is 是 y 序列成员
not in 如果变量没有在指定的顺序找到计算结果为真,否则为假。 x 不在 y 中, 这里 not in 结果是 1 ,如果 x 序列不是 y 的成员。
is 如果操作符两侧的变量是同一个对象计算结果为真,否则为假。 x 是 y, 这里 is 结果就是 1 ,如果 id(x) == id(y) 结果为 真.
is not 如果操作符两侧的变量为同一个对象,计算结果为假,否则真。 x 不是 y, 如果 id(x) 不为 id(y) 这里 is not 结果为 1
Python运算符优先级


下表列出了所有运算符从最高优先级到最低。
操作符 描述
** 幂(指数次幂)
~ + - 补充,一元加号和减号(方法名最后两个+@和 -@)
* / % // 乘法,除法,取模和floor除法
+ - 加法和减法
>> << 左,右按位移位
& 位 '与'
^ | 按位异'或'和常规'或'
<= < > >= 比较运算符
<> == != 运算符相等
= %= /= //= -= += |= &= >>= <<= *= **= 赋值运算符
is is not 标识运算符
in not in 运算符
note or and 逻辑运算符
if 语句
if expression:
   statement(s)
else 语句   
if expression:
   statement(s)
else:
   statement(s)
 elif 语句
if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)
内嵌 if...elif...else 结构   
if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   else
      statement(s)
elif expression4:
   statement(s)
else:
   statement(s)   
while 循环
while expression:
   statement(s)
for 循环
for iterating_var in sequence:
   statements(s)
 遍历序列索引
替代方式是通过每个项目迭代,索引偏移到序列本身:
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print 'Current fruit :', fruits[index]
print "Good bye!"   
定义一个函数
def functionname( parameters ):
   "function_docstring"   #可选的声明
   function_suite
   return [expression]
import 语句 hello.py
import hello
创建类   
class ClassName:
   'Optional class documentation string'
   class_suite
创建实例对象:
class Employee:
   'Optional class documentation string'
   def __init__(self, a, b):
      self.a = a
      self.b = b
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
访问属性
Employee.empCount
内置类的属性
__dict__ : 字典包含类的命名空间。
__doc__ : 类文档字符串,或者如果是None那么表示未定义。
__name__: 类名
__module__: 其中类定义的模块名称。此属性在交互模式为“__main__”。
__bases__ : 一个可能为空的元组包含基类,其基类列表为出现的顺序。   
方法的基础
1__init__ ( self [,args...] )
构造函数(任何可选参数)
调用示例 : obj = className(args)
2 __del__( self )
析构函数,删除对象
调用示例 : dell obj
3 __repr__( self )
求值的字符串表示
调用示例 : repr(obj)
4 __str__( self )
可打印字符串表示
调用示例 : str(obj)
5 __cmp__ ( self, x )
对象比较
调用示例 : cmp(obj, x)
Python中可用的流行时间模块
time.time()返回当前系统时间
#!/usr/bin/python
import time;  # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
struct_time  结构
索引 属性
0 tm_year 2018
1 tm_mon 1 - 12
2 tm_mday 1 - 31
3 tm_hour 0 - 23
4 tm_min 0 - 59
5 tm_sec 0 - 61 (60 或 61 是闰秒)
6 tm_wday 0 to 6 (0 为星期一)
7 tm_yday 1 to 366 (Julian日期) 一年中的第几天
8 tm_isdst -1, 0, 1, -1 表示库决定DST 夏令时
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
结果为
Local current time : time.struct_time(tm_year=2015, tm_mon=12, tm_mday=7, tm_hour=10, tm_min=29, tm_sec=43, tm_wday=0, tm_yday=341, tm_isdst=0)
获取格式化的时间 :
import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime
结果为
Local current time : Mon Dec 07 10:31:46 2015
获取日历月份:
import calendar
cal = calendar.month(2015, 1)
print "Here is the calendar:"
print cal;
time模块:
Python中可用的流行时间模块,时间之间转换
SN 方法及描述
1 time.altzone
当地DST时区的偏移量,如果一个定义在UTC西部秒钟。这是负值,如果当地的DST时区为UTC东边(如西欧,包括英国)。如果白天不为零只用这个。
2 time.asctime([tupletime])
接受一个时间元组,并返回一个可读的24个字符的字符串,如“Tue Dec 11 18:07:14 2015'。
3 time.clock( )
返回当前CPU时间为几秒钟的浮点数。以测量不同方法的计算成本,time.clock的值比time.time()更有用
4 time.ctime([secs])
类似asctimeasctime(localtime(secs)),不带参数就像asctime()
5 time.gmtime([secs])
接收表示从epoch秒钟的瞬间,并返回一个时间元组t及UTC时间。注意:t.tm_isdst始终为0
6 time.localtime([secs])
接收表示从epoch秒钟的瞬间,并返回一个时间元组t与被本地时间(t.tm_isdst是0或1,这取决于是否DST的适用于即时秒通过本地规则)
7 time.mktime(tupletime)
接受表示为一个时间的元组中的本地时间瞬间,并返回浮点值从epoch以秒表示的时刻
8 time.sleep(secs)
暂停secs秒钟调用线程
9 time.strftime(fmt[,tupletime])
接收表示为一个时间的元组中的本地时间瞬间并返回表示所指定的字符串fmt瞬间的字符串
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
根据格式字符串格式化解析str并返回时间元组格式
11 time.time( )
返回当前时刻,自时代浮点秒数
12 time.tzset()
重置所使用的库例程的时间转换规则。环境变量TZ指定如何完成此操作。
calendar 模块
SN 方法及描述
1 calendar.calendar(year,w=2,l=1,c=6)
返回为多行字符串的逐年日历格式化成用c空格分隔的三列。 w是中的每一个日期字符的宽度;每行的长度为21* w +18+2* c。 l为每个星期的行数。
2 calendar.firstweekday( )
返回当前设置为每个星期开始工作日。默认情况下,当先导入calendar,这是0,意思是星期一。
3 calendar.isleap(year)
如果今年是闰年返回true,否则为false。
4 calendar.leapdays(y1,y2)
返回范围内的总数在range(y1,y2)。
5 calendar.month(year,month,w=2,l=1)
返回为多行字符串与日历月month年year,每周一条线加上两个标题行。 w是中的每一个日期字符的宽度;每行的长度为7* W +6。 l为每个星期的行数。
6 calendar.monthcalendar(year,month)
返回整数的列表。每个子列表表示一个星期。月month年year都设置为0;在一个月内,day都被设置为一天,月份,1及以上的数字。
7 calendar.monthrange(year,month)
返回两个整数。第一个是星期几月month年year的第一天的代码;第二个是在所述月份的天数。星期代码是0(星期一)至6日(星期日);月数是1〜12。
8 calendar.prcal(year,w=2,l=1,c=6)
打印类似calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
打印类似calendar.month(year,month,w,l).
10 calendar.setfirstweekday(weekday)
将每个星期的第一天工作日代码设置。星期代码是0(星期一)至6日(星期日)。
11 calendar.timegm(tupletime)
time.gmtime的反向:接受一个时刻在时间元组的形式,并返回同一时刻为从epoch浮点秒数。
12 calendar.weekday(year,month,day)
返回给定日期的星期代码。星期代码0(星期一)至6日(星期日);月份数字代码为1(一月)到12(12月)。
http://www.yiibai.com/python/python_cgi_programming.html#
0 0