Python:语句表达式(code structure)
2016-11-23 21:13
417 查看
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: statements1 elif xxx: statements2 else: statements3
其他
- 逻辑表达式 - `not` - `and`:返回第一个`false`或者最后一个`true` - `or`:返回第一个`true`或者最后一个`false` - 三元表达式 - `a=y if x>o else z`
5. 循环语句
while/else
语句
while xxx: statements1 if xxx: break/continue else: statements2 #如果上面的循环体是自然结束而不是break跳出的话就会执行这条else里的内容
for
语句
for x in objects: statements1 if xxx:break/continue else: statements2
一些循环体运用的例子
#!/usr/bin/env python # coding: utf-8 #copyRight by heibanke # 打印[10-0]之间的偶数 x = 10 while 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 -= 1 else: # Normal exit print y, 'is prime number' ####################### for ########################### sum = 0 for x in [1, 2, 3, 4]: sum += x S = 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 objects key = u"小李" # Keys to search for for item in items: # For all items if item == key: # Check for match print key, "was found" break else: 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 1 except: statements 2
这里单单用了一个
expect,没有传递任何参数,将会响应任何异常,如果需要指定一些异常,并且向要得到关于异常的细节,那我们可以这样写:
expect expectiontype as name
8. 作业
设计一个小游戏-猜数字:随机产生要猜的数字
输入,用于接收用户输入的数字
循环,如果没猜对则循环接收输入,并打出提示信息
猜到数字或猜测次数达到一定次数后(6次)打印失败并推出
改进猜数字游戏,防作弊,错误输入判断
利用上次用户密码作业,请模拟注册过程:用户输入用户民之后进行检测用户名是否在文件中的过程。并返回合理的错误提示。如果不在则输入密码,成功则增加用户信息到文件中,密码进行md5加密处理
增加用户名,密码的合法化判断和错误提示
用户名:字母,数字,下划线和横线的组合,且首字符应是字母,长度不小于4
密码:字母,数字,下划线和横线的组合,且长度不小于6
继续上一课的公交系统作业,利用循环语句将所有线路的linenum和stations保存到一个字典对象;执行后提示输入公交站名字,在所有公交线路的stations里查询该名字,并将包含有该名字的公交线路存到一个字典进行返回
9. 作业答案
Solution:#!/usr/bin/python #coding:utf-8 import random num = random.randint(0, 100) count = 6 flag = True while 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 -= 1 else: print 'it a pity! game over~~ and secret number is ', num
Solution:
#!/usr/bin/python #coding:utf-8 #copyRight by TristanHuang import random num = random.randint(0, 100) count = 6 while 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 -= 1 else: print 'it a pity! game over~~ and secret number is ', num
Solution:
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 data character = '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
相关文章推荐
- Python学习笔记(八):Python语句简介、赋值、表达式和打印
- Python<5>赋值、表达式、打印语句
- Learning Python Part II 之 表达式语句(Expression)
- Python学习(13)--Lambda表达式和switch语句的实现
- python学习手册笔记--第10章--语句简介--第11章--复制_表达式_打印
- python 表达式和语句及for、while循环练习实例
- Python(三)之Python的表达式和语句概述
- python之基础篇(六)——表达式、语句和运算符
- Python 程序;模块;语句;表达式;对象
- python学习笔记8(表达式和语句)
- python正则表达式匹配sql语句中的表名
- 第12课 Python中if分支语句表达式结构
- Python学习入门基础教程(learning Python)--3.3 分支语句的条件表达式详解 .
- Python学习笔记 - 1.变量.表达式.语句
- python笔记4 - 索引,切片,字符编码转换函数,字符串的属性方法,字符串格式化表达式,占位符,基于字典的字符串格式化,循环语句
- python笔记5 - 字符串格式化表达式,while语句嵌套,for循环,break,continue,死循环
- python语句、表达式、对象、变量、赋值、函数传参
- python语句表达式——黑板客老师课程学习
- 语句乎?表达式乎?(Python/C)
- Python表达式和语句的区别