Python:语句表达式(code structure)

来源:互联网 发布:2015年网络歌曲 编辑:程序博客网 时间:2024/06/10 04:26

Python:语句表达式(code structure)

    • Python语句表达式code structure
      • 赋值
        • 普通赋值
        • 多重赋值
      • 输入语句
        • raw_input
        • input
      • 输出语句
        • python2
        • python3
      • 条件语句
        • 语法
        • 其他
      • 循环语句
        • whileelse语句
        • for语句
        • 一些循环体运用的例子
      • 列表解析
        • List Comprehensioins
        • Dictionary Compresion
        • Set Comprehensions
        • Generator Comprehensions
      • 异常处理
        • 基本形式为
      • 作业
      • 作业答案

1. 赋值

普通赋值

多重赋值

举一个多重赋值的列子:

a, b = b, a

简单的语句实现了变量值的交换,但是这里需要注意的是,这样的赋值其实是运用了元组的赋值,因为在python中,‘,’是生成元组的标志,而不是圆括号,下图可以说明:
这里写图片描述

2. 输入语句

raw_input()

输入的内容当作字符串复制给变量

input()

输入的内容为Python可执行的语句,从而将计算后的结果作为值赋给变量

3. 输出语句

python2

在python2中,print是一个语句
- print a,b
- print>>file,a,b:把a,b打印到文件中
- print '%d,%d,%s'%(a,b,c):和c中一样,a,b以数字的形式,c以字符串的形式打印
- print "{0} like {1}".format('we','python'):加强可读性
- print "{a} like {b}".format(a='we',b='python'):可读性更强

python3

在python3中,print是一个函数
- print([obj, ...] [,sep=''] [,end='\n'] [,file=sys.stdout])

4. 条件语句

语法:

#---------语句中的xxx代表逻辑表达式if xxx:    statements1elif xxx:    statements2else:    statements3

其他

- 逻辑表达式    - `not`    - `and`:返回第一个`false`或者最后一个`true`    - `or`:返回第一个`true`或者最后一个`false`- 三元表达式    - `a=y if x>o else z`

5. 循环语句

while/else语句

while xxx:    statements1    if xxx:        break/continueelse:    statements2   #如果上面的循环体是自然结束而不是break跳出的话就会执行这条else里的内容

for语句

for x in objects:    statements1    if xxx:break/continueelse:    statements2

一些循环体运用的例子

#!/usr/bin/env python# coding: utf-8#copyRight by heibanke# 打印[10-0]之间的偶数x = 10while x:    if x % 2 == 0: # Even?         print x    x = x-1# 判断是否素数(质数):大于1的自然数,除1和它本身外没有整数能够整除y=input()x = y // 2 while x > 1:    if y % x == 0:         print y, 'has factor', x        break    x -= 1else: # Normal exit    print y, 'is prime number'####################### for ###########################sum = 0for x in [1, 2, 3, 4]:    sum += xS = u"你在远方"T = (u"我", u"在", u"故乡")for x in S: print x, for x in T: print x,file = open('test.txt','w')D = {'a': 1, 'b': 2, 'c': 3}for key in D:    print >>file, key, '=>', D[key]file.close()#####################################################items = [u"小方", u"小白", u"小三", u"小王"] # A set of objectskey = u"小李" # Keys to search forfor item in items: # For all items    if item == key: # Check for match        print key, "was found"        breakelse:    print key, "not found!" #####################################################file = open('test.txt')while True:    line = file.readline() # Read line by line    if not line: break    print line.strip() # Line already has a \n file.close()for line in open('test.txt'):    print line.strip()

6. 列表解析

A comprehension is a compact way of creating a Python data structure from one or more iterators. Comprehensions make it possible for you to combine loops and conditional tests with a less verbose syntax. Using a comprehension is sometimes taken a sign that you know Python at more than a beginner’s level. In other words,it’s more Pythonic.

List Comprehensioins

  • 最简单的形式:[ expression for item in iterable ]
  • 可以加上条件语句:[ expression for item in iterable if condition]

举个列表解析的例子:

rows = range(1,4)cols = range(1,3)cells = [(row, col) for row in rows for col in cols]for cell in cells:    print(cell)#最后的输出结果:#(1,1)#(1,2)#(2,1)#...就不全列出来了

需要说明的是两个for循环都可以有自己的if条件

Dictionary Compresion

  • 最简单的形式:{key_expression: value_expression for expression in iterable}
  • 当然同样可以加上if条件

同样来看一个字典解析的例子:

word = 'letters'letter_counts = {letter :  word.count(letter) for letter in word}print letter_counts#结果是:{'l':1, 'e':2, 't':2, 'r':1, 's':1}

在这个程序里,我们遍历了'letters'这个字符串,统计了不同字母出现的次数,在字母e和字母t处我们重复使用了两次count()函数,造成了浪费,这是,我们可以对字典解析部分做点改动,使得程序更加的Pythonic

letter_counts = {letter :  word.count(letter) for letter in set(word)}#这时再打印letter_counts得到的结果是:{'t':2, 'l':1, 'e':2, 'r':1, 's':1}

利用set()我们避免了重复计数,但是细心地查看输出结果可以发现打印出来的Key的顺序变了,这是由于set()之后存储方式变了。

Set Comprehensions

  • 一般形式为:{expression for expression in iterable}

Generator Comprehensions

  • 需要注意的是并没有元组解析,虽然Generator Comprehensions看起来像是

举个例子:

number_thing = (number for number in range(1, 6))

以上就是Generator Comprehension的形式,注意这不是元组解析,因为当你使用type(number_thing)之后你会得到类型为<class 'generator'>。Generator Comprehension是想遍历器提供数据的一种方式。

A generator can be run only once. Lists, sets, strings, and dictionaries exists in menory, but a generator creates its values on the fly and hands them out one at a time through an iterator. It doesn’t remember them,so you can’t restart or back up a generator.

7. 异常处理

基本形式为:

try:    statements 1except:    statements 2

这里单单用了一个expect,没有传递任何参数,将会响应任何异常,如果需要指定一些异常,并且向要得到关于异常的细节,那我们可以这样写:

expect expectiontype as name

8. 作业

  1. 设计一个小游戏-猜数字:

    • 随机产生要猜的数字
    • 输入,用于接收用户输入的数字
    • 循环,如果没猜对则循环接收输入,并打出提示信息
    • 猜到数字或猜测次数达到一定次数后(6次)打印失败并推出
  2. 改进猜数字游戏,防作弊,错误输入判断

  3. 利用上次用户密码作业,请模拟注册过程:用户输入用户民之后进行检测用户名是否在文件中的过程。并返回合理的错误提示。如果不在则输入密码,成功则增加用户信息到文件中,密码进行md5加密处理

  4. 增加用户名,密码的合法化判断和错误提示

    • 用户名:字母,数字,下划线和横线的组合,且首字符应是字母,长度不小于4
    • 密码:字母,数字,下划线和横线的组合,且长度不小于6
  5. 继续上一课的公交系统作业,利用循环语句将所有线路的linenum和stations保存到一个字典对象;执行后提示输入公交站名字,在所有公交线路的stations里查询该名字,并将包含有该名字的公交线路存到一个字典进行返回

9. 作业答案

  1. Solution:
#!/usr/bin/python#coding:utf-8import randomnum = random.randint(0, 100)count = 6flag = Truewhile count:    flag = True    while flag:        try:            input_num = input("0-100,please choose a number[q to quit]\n")            flag = False        except:            print 'something wrong,you should input a number'            continue    if input_num > num:        print 'you num is too big,', 'chances left: ', count-1    elif input_num < num:        print 'you num is too small,', 'chances left: ', count-1    elif str(input_num) == r'num':        print 'please do not cheat, ', 'chances left: ', count-1    else:        print 'you did a good job'        break    count -= 1else:    print 'it a pity! game over~~ and secret number is ', num
  1. Solution:
#!/usr/bin/python#coding:utf-8#copyRight by TristanHuangimport randomnum = random.randint(0, 100)count = 6while count:    try:        input_num_str = raw_input("0-100,please choose a number[q to quit]\n")        if input_num_str == 'q':            break        input_num=int(input_num_str)    except:        print 'something wrong,you should input a number'        continue    if input_num > num:        print 'you num is too big,', 'chances left: ', count-1    elif input_num < num:        print 'you num is too small,', 'chances left: ', count-1    else:        print 'you did a good job'        break    count -= 1else:    print 'it a pity! game over~~ and secret number is ', num
  1. Solution:
  2. Solution:
#!/usr/bin/env python#coding: utf-8#__author__ = 'Tristan'#初始化账号数据缓存data = list()#先读取账号文件的所有记录f = open('account.txt', 'r')for line in f:    a = line.split(',')   #读取一行的账号和密码    data.append(a[0])     #记录账号到缓存中print datacharacter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'first_c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'while True:    print u"--------注册--------\n"\        + u"请输入用户名(首字母必须为字母,最小长度为4, 大小写字母,数字,_,-,的组合)\n"    name =raw_input()    accountValid = True    #核查用户名的有效性    if len(name) < 4:        print u"你的输入%s不够4位, 请重新输入!" % (name)        accountValid = False    elif not name[0] in first_c:        print u"你的输入%s首字符必须是字母, 请重新输入!" % (name)        accountValid = False    else:        #检查是否已存在        if name in data:            print u"这个用户名%s已经存在,请重新输入!"%(name)            valid = False    flag = True    # 密码是否有效    while flag and accountValid:        print u"该用户名可以使用,请输入密码(最小长度为6, 大小写字母,数字,_,-,的组合):\n"        password = raw_input()        #检查是否有效        if len(password)<6:            print u"你的输入密码%s不够6位, 请重新输入!"%(password)            continue        for a in password:            if not a in character:                print u"你的输入密码%s有非法字符, 请重新输入!"%(password)                flag=True                break            else:                flag = False    #写入账号信息    if accountValid and (not flag):        file = open('account.txt', 'a')        #md5数据加密        import hashlib        password_md5 = hashlib.md5(password).hexdigest()        file.write(name+','+password_md5+'\n')        file.close()        print u"恭喜你,注册成功"        break
0 0