用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

feng    -  云代码空间

——

python 学习笔记

2013-01-16|2394阅||

摘要:>>> a = "this is a test"                  如果字符串赋值有空格则要用单引号或者双引号括起来 >>> b = "I love python " >>> c = a + "\n" + b 

>>> a = "this is a test"                  如果字符串赋值有空格则要用单引号或者双引号括起来
>>> b = "I love python "
>>> c = a + "\n" + b                     \n代表换行呵
>>> c                                           直接用变量名得到输出会用单引号括起来,因为这样可以让非字符串对象也显示为字符串,如\n代表的换行
'this is a test\nI love python '
>>> print c                              
this is a test
I love python

>>> print _                  _代表最后表达式的值,在这里_的值是C
this is a test
I love python
>>> _
'this is a test\nI love python '
>>>

字符串替换功能
>>> a = 'test'
>>> b =4
>>> print " we have %d times %s in last day !" % (b,a)  %d代表一个整型值来替换,而%s代表一个字符串来替换,%f代表一个浮点数来替换
 we have 4 times test in last day !
>>>

读取用户输入-raw_input()函数
>>> a=raw_input('Please entere your name :')                  raw_input()函数中可以输入提示用户输入的信息,这样方便用户输入正确的内容
Please entere your name :peter
>>> print a
peter
>>>

获得python的帮助办法
调用内建的help()函数
>>> help(int)
Help on class int in module __builtin__:

class int(object)
 |  int(x[, base]) -> integer
 |
 |  Convert a string or number to an integer, if possible.  A floating point
 |  argument will be truncated towards zero (this does not include a string
 |  representation of a floating point number!)  When converting a string, use
 |  the optional base.  It is an error to supply a base when converting a
 |  non-string. If the argument is outside the integer range a long object
 |  will be returned instead.


>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
(END)

python中括号不是必须的,不过为了可读性,使用括号总是值得的,任何维护代码的人都会感谢你!
python是动态类型语言,也就是不需要预先声明变量的类型,变量的类型和值在赋值的那一刻被初始化
python不支持自增长1或者自减1的操作,,python将--n解释为-(-n),从而得到n,++n一样得到n,因为+ -都是单目操作符
布尔值是一个特殊的整型,常用true  和false来表示,在数值上下文中true表示为1,false 表示为0




python中字符串被定义为引号之间的字符集合,(引号可以是单引号,双引号,三引号(三个连接单引号或者三个连接双引号''' 或者"""))
+号代表字符串连接,而*号代表字符中复制
注意切片操作符[ N:M],N是从0开始的,第N个字符到第M个字符之前的字符串



 列表元素用中括号[ ]表示的,可以更改元素个数,元素
列表切片得到也是列表,可以列改元素
 元组元素是用小括号( )表示,元组元素不可以更改
元组切片得到是也是元组,不能被修改
  
字典就是perl中的hash,由键值对构成,,用{ }来表示


print 语句用逗号抑制换行的方法(默认print在输出后会自动换行的呵!)

>>> for a in [1,2,3]:
...     print a,
...
1 2 3
>>> for a in [1,2,3]:
...     print a
...
1
2
3
>>>
1: for  循环中in后跟的只能是列表呵!注意别忘记了冒号:
2:注意print语句中有逗号和没有逗号的区别



列表解析,
>>> b = [1,2,3]
>>> for a in b:
...     print a
...
1
2
3
>>>
range(N)内建函数返回从0到N-1的一个列表
range(9)返回值是[0, 1, 2, 3, 4, 5, 6, 7, 8]

>>> for a in [1,2,3]:
... print a,
  File "<stdin>", line 2
    print a,
        ^
IndentationError: expected an indented block   <======这说明是一个缩进的问题,因为python是通过缩进来表示代码块的

当你创建了一个python源文件,模块的名字就是不带.py后缀的文件名,一个模块创建之后,你可以从另一个模块中使用import语句导入这个模块来使用

练习1 :输入字符串和数值,并显示出来,atof 是转换为浮点数

#!/usr/bin/env python
import string               用于转换数值为字符串用的
a=raw_input('please enter a string:')
print 'this is what your enter:', a
b=string.atof(raw_input('please enter a number:'))
print 'this is what number your enter:', b


练习2: 用while/for来输入0-10.注意是从0 开始;
[peter@lsl3s000 ~]$ cat 1a.py
#!/usr/bin/env python
a=0
while a<=10:
        print a
        a=a+1
print 'this is a while loop in above output:'
print
for a in range(11):
        print a

练习3: 判断用户输入的是一个数据是正,负或者0
[peter@lsl3s000 ~]$ cat 1b.py
#!/usr/bin/env python
a=int(raw_input('please enter a number:'))
if a > 0:
        print 'your number is bigger than 0 '
if a ==0:
        print 'your number is 0'
if a < 0 :
        print 'your number is less than 0'

练习4: 从用户里接受一个字符串,然后按字符循环显示,用while/for来做,都是通过下标来访问每一个字符


[peter@lsl3s000 ~]$ cat 1b.py
#!/usr/bin/env python
a=raw_input('please enter a string:')
b=len(a)
for c in range(b):
        print a[c]
print 'above line is use for [ for ] loop'
print
k=raw_input('please enter a string:')
i=0
while i<len(k):
        print k[i]
        i=i+1


[peter@lsl3s000 ~]$

练习5:接收用户输入,并计算总和
[peter@lsl3s000 ~]$ cat 1c.py
#!/usr/bin/env python
import string
b=[]
k=0
for a in range(5):                                                     为什么最后有冒号:? 用冒号是将代码块的头和体分开呵!(也说明了体的语句要缩进了)
        print 'the number a is ',a
        b.append(string.atof(raw_input('please enter a numb:')))
for d in range(5):
        k=k+b[d]
print 'ths sum of the 5 nmber is %f' %(k)
print 'above is ues for [for ] loop only\n\n'

a_list=[]
num=0
while num < 5:
        a_list.append(string.atof(raw_input('please enter a numb:')))
        num+=1
num1=0
e=0
while num1 <5:
        e=e+a_list[num1]
        num1=num1+1
print 'the sum of  the while loop is %f' % (e)                  ========注意不要在%f和%e间加什么标点符号,不然会报语法错误

练习6,计算平均值,用到平均值

class float(object)
 |  float(x) -> floating point number
 |
 |  Convert a string or number to a floating point number, if possible.



[peter@lsl3s000 ~]$ cat 1d.py
#!/usr/bin/env python
a_list=[]
for a in range(5):
        a_list.append(float(raw_input('please enter a number:')))
b=0
c=0
while b<5:
        c+=a_list[b]
        b+=1
d=c/5
print 'the average is %f' %d

[peter@lsl3s000 ~]$

练习7: 读取一个数,不符合要求则继续要求读数
[peter@lsl3s000 ~]$ cat 1d.py
#!/usr/bin/env python
while True:
        a=float(raw_input('please enter a number between 1 and 100:'))
        if 1<a<100:
                print 'this is a number we want.'
                break
        else:
                print 'the nubmer is incorrect,please try againt!'
                continue

if条件要有冒号,else也要有冒号,,break退出循环,continue继续循环

文档字符串,定义在模块,类或者函数的起始添加的一个字符串,起到在线文档的作用,注意只能是第一个字符串呵

[peter@lsl3s000 ~]$ cat m.py
def mylog(self):
        """this is a document for test"
        "peter create this function for test"                    mylog函数用三个双引号定义了一个字符串,作为文档字符串
        "do you like my function?"""

[peter@lsl3s000 ~]$ cat 1d.py
#!/usr/bin/env python
import m                                                                  python中的文件是以模块的形式组织的,因此m实际是m.py呵
print m.mylog.__doc__                                           文档字符串的引用通过模块.函数.__doc__来显示(注意点号呵)
[peter@lsl3s000 ~]$ ./1d.py
this is a document for test"
        "peter create this function for test"
        "do you like my function?

[peter@lsl3s000 ~]$


在python交互中获取帮助
[peter@lsl3s000 ~]$ python
Python 2.4.3 (#1, Jun 11 2009, 14:09:37)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys)       得到sys相关的属性
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__st                                                 din__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names'                                                 , 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_cle                                                 ar', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit',                                                  'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodi                                                 ng', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', '                                                 meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform',                                                  'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'set                                                 recursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_in                                                 fo', 'warnoptions']

>>> print sys.__doc__    得到sys模块的相关属性及函数说明
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
  Assigning to sys.exitfunc is deprecated; use the atexit module instead.

stdin -- standard input file object; used by raw_input() and input()
stdout -- standard output file object; used by the print statement
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

exc_type -- type of exception currently being handled
exc_value -- value of exception currently being handled

>>> sys.exit()        ===是除了crl+d外退出python解释器的另一种方法

实现菜单式功能,按不同数字执行不同的计算功能,按X退出,按其他继续

#!/bin/env python
#
#
alist=[]
mysum=0
myavg=0
while True:
        print 'press "1" to calc the sum of your number:'
        print 'press "2" to calc the average of your number:'
        print 'press "X" to exit this program:'
        a = raw_input('please enter a character:  ')                   <======a是字符串,因此在下面的比较中需要提供单此号呵
        if a=='1' or a=='2':
                for a1 in range(5):
                        alist.append(int(raw_input('enter a number:')))
                for b in range(5):
                        mysum += alist[b]
                myavg = float(mysum/5)
                if a=='1':
                        print 'the sum of your number is %d\n\n\n\n' % mysum
                        continue
                if a=='2':
                        print 'the average of your number is %f\n\n\n\n' % myavg
                        continue
        if a=='X':
                break
        else:
                continue

 

顶 12踩 12收藏
文章评论
    发表评论

    个人资料

    • 昵称: feng
    • 等级: 资深程序员
    • 积分: 1584
    • 代码: 8 个
    • 文章: 42 篇
    • 随想: 2 条
    • 访问: 85 次
    • 关注

    站长推荐