xian123 发表于 2015-4-23 05:46:21

python and Django(二)

走马观花识python
一、python中的提示符
  主提示符 >>>等待输入下一个语句
  次提示符 …    等待输入当期语句的其他部分
二、编程方式
  语句:通知给解释器的一个命令。
>>> print 'hipython'
hipython

   表达式:可以是一个算式运算表达式或者是一个函数调用。
>>> abs(-5)
5

三、常用函数
  1、程序输出(print)  
>>> mystring='hipython'
(1)直接输出
>>> mystring
'hipython'
(2)print 输出
>>> print mystring
Hipython
(3)输出最后一个表达式的值
>>> _   
'hipython'
(4)实现字符串替换
>>> print "%s is string;%d is int,%f is float" %("mystr",100,1.23)
mystr is string;100 is int,1.230000 is float
(5)重定向输出
>>> logfile=open('d:/lyp/python/tmp.txt','a')
>>> print >>logfile,'Hello Python,O(∩_∩)O哈哈~'
>>> logfile.close()

  2、程序输入(raw_input)
接收一个输入
>>> str=raw_input('Please input')
>>> print str
hi python!

  3、函数帮助(help)
>>> help(raw_input)
Help on function Win32RawInput in module pywin.framework.app:
Win32RawInput(prompt=None)
    Provide raw_input() for gui apps

  4、显示对象的属性(dir)
dir(raw_input)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
  5、显示对象类型(type)
>>> type(raw_input)

  6、打开文件(open)
>>> myfile = open('D:/lyp/python/tmp.txt')
>>> myfile.read()
'\xef\xbb\xbfHello Python.\n'
  7、得到一个整数列表(range)
>>> mylist = range(4,10,2)
>>> print mylist

  8、得到对象长度(len)
>>> mystr='hipython'
>>> len(mystr)
8
  9、类型转换(int,string)
>>> myint=100
>>> str(myint)
'100'
>>> int(str(myint))
100
四、注释
(1)#直到行末
>>> print 123 #输出123
123
(2)文档字符串
>>> def myfun():
   "print abc"
   print 'abc'
   
>>> myfun.func_doc
'print abc'

五、运算符
(1)算术运算符
+ - * / // % **
加、减、乘、除、浮点除法、区余、乘方
>>> print (1+3-1)*4/2
6
>>> print 3**2
9
(2)比较运算符
<>= == !=
>>> 2>4
False
(3)逻辑运算符
and or not
>>> 2> not 2>> mystring='hipython'
>>> mystring
'h'
>>> mystring
'ip'
>>> mystring[-1]
'n'
>>> mystring*3
'hipythonhipythonhipython'
>>>

      4、列表和元组
理解为数组
列表用[],长度和元素可变;
元组用(),长度和元素不可变;
>>> mylist=['abc',1,'d','123']
>>> mylist.append(5)
>>> mylist
5
>>> myTuple=('abc',1,'d','123')
>>> myTuple
'abc'
>>> myTuple=3
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>>

      5、字典
理解为hashtable(key--value)
字典用{}
>>> myDict={'name':'lyp','age':27}
>>> myDict['sex']='man'
>>> myDict['age']
27
>>> myDict['sex']
'man'

七、流程控制
      1、条件判断
         if exp:
         elifexp:
         else:
>>> x=1
>>> if x>0:
   print 'true'
else:
   print 'false'
   
true
>>> if x>1:
   print 'x>1'
elif x==1:
   print 'x=1'
else:
   print 'x
页: [1]
查看完整版本: python and Django(二)