第二章 快速入门

第二章 快速入门

1. 程序输出,print语句以及“Hello World!”
  • 在交互式解释器中显示变量的值:在交互式解释器中既可以用print显示变量的字符串表示,也可以直接利用变量名查看变量的原始值。
  • 注意print myString和myString在输出上的区别,后者会输出一个单引号。
  • 下划线(_)表示最后一个表达式的值,即会包含刚刚myString中的值。
  • print语句可以和字符串格式操作符结合使用(%)
>>>print "%s is number %d" % ("Python",1)
Python is number 1!
  • 符号>>表示重定向输出
    print >> sys.stderr, ‘Fatal error: invalid input!’
2. 程序输入和raw_input()内建函数
raw_input函数可以读取标准输入并将读取的数据赋值给指定的变量。
>>>user = raw_input('Enter login name:')
Enter login name: root
不过这个只能用于文本输入。如需要整型可以利用括号进行强制类型转换。 在交互式解释器中获得帮助:用函数名作为help()的参数
>>>help(raw_input)
3. 注释
利用#号标识注释(一行) 文档字符串注释:在模块、类或者函数的起始添加一个字符串,起到在线文档的功能 文档字符串可以在运行时访问,也可以用来自动生成文档。
4. 操作符
**两种除法操作符:** - 单斜杠:传统除法操作符(地板除,只去比商小的最大整数) - 双斜杠:浮点除法(对结果进行四舍五入,真正的除法) 查阅相关资料,书似乎这里写错了。单斜杠除法,只要除数和被除数有一个为浮点数,那么结果就是精确到16位小数的浮点数。而双斜杠除法则是地板除。
```python
>>>5/3
1
>>>5.0/3
1.6666666666666667
>>>5.0//3
1.0
```
**双星号(\*\*)乘方操作符** **三种逻辑操作符:and or not **
>>> 3 < 4 and 4 < 5
5. 变量和赋值
Python是动态型语言,不需要预先声明变量的类型。变量的类型和值在赋值的那一刻被初始化。 不支持c语言中的自减1或者自增1操作符
6. 数字
Python支持五种基本数字类型:有符号整型(长整型、布尔值)、浮点值、复数。
7. 字符串
  • 索引规则:第一个字符串的索引是0,最后一个字符串的索引是-1。
  • 加号(+)用于字符串连接运算,星号(*)用于字符串重复。
  • 索引操作符([])和切片操作符([:])可以得到子字符串:

    >>>pystr = 'Python'
    >>> iscool = 'is cool'
    >>> pystr [0]
    'P'
    >>> ptstr [2:5]
    'tho'
    >>> iscool [:2]
    'is'
    >>> iscool [-1]
    '!'
    >>> pystr*2
    'PythonPython'
  • 三引号可以包括特殊字符:

    >>>pystr = '''Python
    … is cool'''
    >>>pystr
    'Python\nis cool'
    >>>print pystr
    Python
    is cool
8. 列表和元组

可以将列表和元组当成普通的“数组”,他可以保存任意数量任意类型的Python对象。
列表和元组的区别:
列表元素用中括号包裹,元素的个数及元素的值可以改变。
元组元素用小括号包裹,不可以更改。元组可以看成是只读的列表。

9. 字典

字典是Python中的映射数据类型,工作原理类似关联数组或者哈希表,由键值对构成。
几乎所有类型的Python对象都可以用作键。
值也可以是任意类型的Python对象,字典元素用大括号({})包裹。

>>> aDict = {'name': 'Xieldy'}    #create dict
>>> aDict['age']=20                    #add to dict
>>> aDict
{'age':20,'name':'Xieldy'}
>>>aDict.keys()
['age','name']
>>> for key in aDict:
... print key,aDict[key]
  File "<stdin>", line 2
    print key,aDict[key]
        ^
IndentationError: expected an indented block

for语句等有冒号的语句,下一行往往都需要注意缩进,否则会产生错误

>>> for key in aDict:
...  print key,aDict[key]
...
age 20
name Xieldy
10. 代码块及缩进对齐

代码块通过缩进对齐来表示代码逻辑,而不是使用大括号。

11. if语句
If expression:
If_suite
If x<0:
    print "x must be atleast 0!"
if expression:
    if_suite
else:
    else_suite
if expression1:
    if_suite
elif expression2:
    elif_suite
else:
    else_suite
12. while循环
>>>counter=0
>>>while counter<3:
...     print 'loop #%d' % (counter)
...     counter +=1
...
loop #0
loop #1
loop #2
13. for循环和range()内建函数

for接受可迭代对象作为其参数,每次迭代其中一个元素

>>>print 'I like to use the Internet for:'

I like to use the Internet for:

>>>for item in ['e-mail', 'net-surfing', 'homework', 'chat']:
    print item

e-mail
net-surfing
homework
chat

如果要这些内容在一行输出,则可以在print最后添加一个逗号

>>>print 'I like to use the Internet for:'

I like to use the Internet for:

>>>for item in ['e-mail', 'net-surfing', 'homework', 'chat']:
    print item,
print

最后一个print的作用是换行。

>>>for Num in [0, 1, 2]:
    print Num

0
1
2

>>>for Num in range(3):
    print Num

0
1
2

同样,字符串也可以迭代:

>>> foo = 'abc' 
>>> for c in foo:
    print c

a
b
c

range()函数经常和len()函数一起用于字符串索引。

>>> foo = 'abc' 
>>> for i in range(len(foo)):
    print foo[i], '(%d)' % i

a (0)
b (1)
c (2)

enumerate() 函数可以同时循环索引和元素

14. 列表解析

可以在一行中使用一个for循环将所有值放到一个列表当中。

>>> squard = [x ** 2 for x in range(4)]
>>> for i in squard:
    print i 

0
1
4
9

>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2 ]
>>> for i in sqdEvens:
    print i

0
4
16
36

15. 文件和内建函数open()、file()

如何打开文件

handle = open(file_name, access_mode = 'r' )

file_name变量包含我们希望打开的文件的字符串形式名字,access_mode 中’r’表示读取,’w’表示写入,’a’表示添加,’+’表示读写,’b’表示二进制访问。(默认为r)

>>> filename=raw_input('Enter the file name:')
Enter the file name:C:\Downloads\123.txt
>>> fobj=open(filename,'r')
>>> for eachLine in fobj:
...     print eachLine,
...

13
54
5611

如果在最后加上fobj.close()语句,则总是会报错。
此处我们又利用了逗号来抑制print自动产生换行符号

16. 错误和异常

只需要将可能产生错误及异常的代码添加到try-except语句当中。

17. 函数
  1. 如何定义函数

    def function_name([arguments]):
        "optional documentation string"
        function_suite

    定义一个函数的语法由def关键字和紧随其后的函数名,再加上函数需要的几个参数组成。

    def addMe(x):
        'apply+operation to argument'
        return (x+x)

    这个函数的作用是对于任何类型的参数x,都对其自身进行一个加法运算(不等于乘以2),然后返回和。

  2. 如何调用函数

    >>> def addMe(x):
    ...     'apply operation to argument'
    ...     return (x+x)
    ...
    >>> addMe(2)

    4

    >>> addMe('Python')

    ‘PythonPython’

    >>> addMe([1,'Python'])

    [1, ‘Python’, 1, ‘Python’]

  3. 默认参数
    函数的参数可以有一个默认值,表示若调用函数的时候没有提供参数,则使用默认值作为参数。

    >>> def foo(debug=True):
        'determine if in debug mode with default argument'
        if debug:
            print 'in debug mode'
        print 'done'
    >>> foo()

    in debug mode
    done

    >>> foo(False)

    done

18. 类

如何定义类?

class ClassName(base_class[es]):  #可以提供一个基类或者父类
    "optional documentation string"  #文档字符串
    static_member_declarations        #静态成员定义
    method_declarations                     #方法定义

init()方法可以被当做构造方法,当一个类实例被创建时,init()会自动执行。它的目的是执行一些该对象必要的出初始化工作。
self是类实例自身的引用。(JAVA中为this)
如何创建类实例

>>> fool = FooClass()
19. 模块

模块是一种组织形式。可以包含执行代码、函数和类。
当你创建了一个Python源文件,模块的名字就是不带.PY后缀的文件名。一个模块创建之后可以从另一个模块中使用import语句导入这个模块使用。
- 如何导入模块

import module_name
  • 如何访问一个模块函数或访问一个模块变量
    导入完成之后,可以通过句号属性标志法访问。
module.function()
module.variable
20. 实用的函数
函数描述
dir([obj])显示对象的属性,若没有提供参数则显示全局变量的名字
help([obj])显示对象的文档字符串,如果没有提供任何参数,则会进入交互式帮助
int(obj)将一个对象转换为整型
len(obj)返回对象的长度
open(fn,mode)以mode模式打开一个文件
range([start,]stop[,step])返回一个整型列表。
raw_input等待用户输入一个字符串,可以提供一个可选的参数str用作提示信息
str(obj)将一个对象转换为字符串
type(obj)返回对象的类型
21. 练习
  1. 第一题
    源代码:

    a=1
    b='Python'
    c='is the best'
    print a 
    print b
    print c 
    print 'Pytohn is the NO.%d in the world!' % a
    print '%s is the NO.%d in the world!' % (b,a)

    1
    Python
    is the best
    Pytohn is the NO.1 in the world!
    Python is the NO.1 in the world!
    [Finished in 0.2s]

  2. 第二题
    (a)我认为这段脚本是用来进行计算的。
    (b)会输出这个式子的计算结果:9
    (c)不一样。脚本并不会显示计算结果
    (d)这段代码如果单独执行,不会有任何输出。但是如果在交互式解释器中运行则会有结果输出。
    (e) print 1+2*4

  3. 第三题

    >>>A=1+2*8+6/2
    >>>A
    20
    >>>B=5*6+3+9/2
    >>>B
    37
    >>>C=A%B
    >>>C
    20
    >>>D=A**B
    >>>D
    1374389534720000000000000000000000000000000000000L
  4. 第四题

    >>>s=raw_input('Please enter your string:')
    >>>print s
    >>>s2=raw_input('Please enter another string:')
    >>>num=int(s2)
    >>>print num

    Please enter your string:god
    god
    Please enter another string:2
    2

    注意Python中数据类型转换的格式 number=int(string)

  5. 第五题

    >>>a=0
    >>>while(a<=10):
            print a,
            a=a+1
    >>>print 
    >>>for b in range(11):
            print b,

    0 1 2 3 4 5 6 7 8 9 10
    0 1 2 3 4 5 6 7 8 9 10
    [Finished in 0.2s]

    注意range()函数的起止范围

  6. 第六题

    >>>s=raw_input('Please enter a number:')
    >>>a=float(s)
    >>>if a>0:
            print 'bigger than 0!'
    elif a==0:
            print 'It is 0'
    else:
            print 'smaller than 0!'
    
    Please enter a number:0.2
    bigger than 0!
  7. 第七题

    s = raw_input('Please enter a string:')
    a = 0
    while a< len(s):
            print s[a],
            a=a+1
    print
    for b in s:
            print b,

    Please enter a string:Python
    P y t h o n
    P y t h o n

  8. 第八题
    若定义了一个空列表,则应该通过append函数往里添加成员,不能通过下标来赋值。

    a=[]
    for i in range(5):
            b=int(raw_input())
            a.append(b)
    i=0
    S=0
    while i<5:
            S=S+a[i]
            i=i+1
    print S
    i=0
    S=0
    for i in range(5):
            S=S+a[i]
    print S

    1
    2
    3
    4
    5
    15
    15

  9. 第九题

    a = [3,2,9,8,5]
    S=0
    for i in range(5):
            S=S+a[i]
    S=float(S)
    avr=S/5
    print avr

    5.4

  10. 第十题

    import sys
    def num():
            x=float(raw_input('Please enter a number between 1 and 100:'))
            if x<=100 and x>=1:
                    print 'Enter successfully!'
                    return 1
            else:
                    return 0
    a=0
    while a!=1:
            a=num()
    sys.exit()

    Please enter a number between 1 and 100:102.2
    Please enter a number between 1 and 100:-100
    Please enter a number between 1 and 100:80
    Enter successfully!

  11. 第十一题

    import sys
    
    def addNum(a): 
            S=0
            for i in range(5):
                    S=S+a[i]
            return S
    
    def avrNum(a):
            avr=float(addNum(a))/5
            return avr 
    
    def main():
            func=int(raw_input('Please enter a number to determine the function:'))
            if func!=1 and func!=2:
                    print 'Exit!'
                    sys.exit()
            a=[]
            print 'Please enter five number:'
            for i in range(5):
                    a.append(float(raw_input()))
            if func==1:
                    SUM=addNum(a)
                    print 'the sum of the numbers is %f' % (SUM)
            else:
                    AVR=avrNum(a)
                    print 'the avr of the numbers is %f' % (AVR)
    
    while 1:
            main()

    Please enter a number to determine the function:2
    Please enter five number:
    1.2
    2.3
    3.9
    4.6
    5.3
    the avr of the numbers is 3.460000
    Please enter a number to determine the function:4
    Exit!

  12. 第十二题

    (a)

    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__']

    (b)

    >>> dir
    <built-in function dir>

    (c)

    >>> type(dir)
    <type 'builtin_function_or_method'>

    (d)

  13. 第十三题
    已完成
  14. 第十四题
    已完成
  15. 第十五题

    a = float(raw_input('Please enter the first number:'))
    b = float(raw_input('Please enter the second number:'))
    c = float(raw_input('Please enter the third number:'))
    
    if a>b:
        d=a
        a=b
        b=d
    if a>c:
        d=a
        a=c
        c=d 
    if b>c:
        d=b
        b=c 
        c=d 
    a = float(raw_input('Please enter the first number:'))
    b = float(raw_input('Please enter the second number:'))
    c = float(raw_input('Please enter the third number:'))
    
    if a<b:
        d=a
        a=b
        b=d
    if a<c:
        d=a
        a=c
        c=d 
    if b<c:
        d=b
        b=c 
        c=d 
    print a,b,c 
  16. 第十六题
    已完成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值