Menu Close

python2 学习笔记之 表达式

1.赋值 就是将一个数字、字符串等赋值给一个变量

  1. 简单赋值
x = 1
  1. 多重赋值
#将1赋给x,2赋给y
x,y = 1,2
#以下表达式同上
x,y = (1,2)
x,y = [1,2]
#--分割线--
#将h赋给x,w赋给y
x,y = 'h','w'
#将b赋给x,j赋给y
x,y = 'bj'
#将bj赋值给x和y
x = y = 'bj'
  1. +=
x = 1
#x = 2
x +=1 

2.输入

2.1 raw_input 原始输入,不进行转换

x = raw_input("请输入你的名字")
#请输入你的名字 liuser
print('hello %s' % (x))
#hello liuser
x = raw_input("100*100 = ?")
# 100*100 = ?100*100
x
#输出x的时候原样输出,不做计算.
'100*100'
>>> 

2.2 input 输入的内容会做运算

x = input("100*100 = ?")
100*100 = ?100*100
>>> x
#已经做了计算100*100
10000
input("输入你的名字")
#输入你的名字liuser
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'liuser' is not defined
#liuser这个变量不存在,input的输入跟在python中的表达、语句是一样的。

3输出

先说一下python3和2的区别,3的话python是一个函数,如果使用 print "hello",会报错。python2中print是一个语句,重点是看下python2

3.1 普通输出

#普通输出
print "hello"

3.2 格式化符号

#格式化符号输出,下面输出结果为:"hello world" %s表示这个位置是一个字符串 后面的括号为实际的值
print "hello %s" % ("world")
#格式化输出,下面语句将输出:"hello liuser , welcome use python "
print "hello {0} , welcome use {1} " . format('liuser','python')
#也可以使用下面语句
print "hello {a} , welcome use {b} " . format(a = 'liuser',b = 'python')

4条件语句

4.1 if else语句
if语法

#如果表达式xxx为true,则执行statements1
if xxx:
    statements1
#如果表达式 yyy 为true,并且xxx为false,则执行statements2
elif yyy:
    statements2
#如果上述表达式都不满足,则执行下面表达式
else
    statements3
#一个栗子,输出结果为"x=10"
x = 10
if x > 10 :
    print "x > 10"
elif x < 10:
    print "x < 10"
else :
    print "x = 10"

5逻辑表达式,顺序上 not > and > or

5.1 not 取反

x = True
#输出x
x
#x=True
True
#取反
not x
#x=False
False
>>> 

5.2 and 从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值。

x,y,z = [1,0,4]
#返回 0 ,第一个假值
x and y
#返回4,两个都为真,返回右边的值(最后的值)
x and z

5.3 or 从左到有计算表达式,返回第一个为真的值。

x,y,z = [1,0,4]
# 返回x,因为x为真
x or y
#返回z,z为真
y or z

5.4 三元表达式,if的缩写形式

x,y = [3,5]
#这句话表示,如果x > y,则 a = x,否则,x = y
a = x  if x > y  else y

6循环语句

6.1 while/else

基本语法

#如果xxx为真,则一直执行while循环
while xxx:
    statements
    #如果要跳出循环,
    if yyy:
        #直接跳出整个循环
        break
        #跳出当前循环
        continue
举个例子1
x = 10
while x > 0 :
    print( 'x > 0,当前x为 % s' % (x))
    x = x-1
else:
    print("循环结束,当前x为 % s" % (x))
x > 0,当前x为 10
x > 0,当前x为 9
x > 0,当前x为 8
x > 0,当前x为 7
x > 0,当前x为 6
x > 0,当前x为 5
x > 0,当前x为 4
x > 0,当前x为 3
x > 0,当前x为 2
x > 0,当前x为 1
循环结束,当前x为 0
举个例子2
x = 10
#死循环
while True:
    print( 'x > 0,当前x为 % s' % (x))
    x = x-1
    #通过此处的条件中断循环
    if(x<=0):
        break
else:
    #此处不会执行,因为是手动停,并不是while循环的条件为False
    print("循环结束,当前x为 % s" % (x))
举个例子3 ,判断10以内的偶数
x = 10
while x > 0:
    if(x % 2 == 0):
        print('打印偶数 %d' % (x))
    x = x-1
举个例子4,判断一个数是不是质数(素数)
#coding:utf-8
number = input("请输入一个数字")
#差不多是一个数的一半
half   = number // 2
flag = False
while(half>1):
    if(number % half ==0):
    flag = True
        print "不是质数,可以被 % s 除" % (half)
    half = half -1
else :
    if(flag == False):
        print("%s是质数" % (number))

6.2 for/else循环

用法

#o表示字符串  元组 列表 字典等
for x in o:
    #do something1
    if(False):
        #跳出和上面是一样的
        break
else:
    #do something2
举个小栗子:
for x in [1,2,3,4,5,6]:
    print "x = %s" % (x)
#输入 x=1 x=2..... x=6
再举一个小栗子,循环字典,并保存到文件
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import codecs
file = codecs.open('for.txt','w','utf-8')
dict = {'name':u'得青','age':'20','sex':'1','address':'北京'}
for key in dict:
    print >> file ,key,"=>",dict[key]
file.close()

7列表解析和异常

7.1 列表解析
例:去除列表中重复的元素

L1 = ['a','b','c','d','b','a']
L2 = []
#这句的执行顺序是 for i in L1 ,然后判断 if not i in L2 ,也就是i是否在L2中,如果不在则L2.append(i)
[L2.append(i) for i in L1  if not i  in L2]
print L2
>>> ['a', 'b', 'c', 'd']
等同于:
>>> for i in L1:
...     if(i not in L2):
...         L2.append(i)
...
>>> L2
['a', 'b', 'c', 'd']
>>> 

例2:生成器,算出10以内偶数的平方

#会产生一个生成器 <generator object <genexpr> at 0x1058deaa0>
iter = (i ** 2 for i in range(10) if i%2 ==0)
#然后迭代遍历一下
for i in iter:
    print i

7.2异常

7.1 常见异常

#i未定义
print i
#会产生一个NameError
>>> NameError: name 'n' is not defined
#i为整型,访问下标会产生TypeError
i = 1
i[1]
#list只有一个元素,下表为0,访问1越界,会产生IndexError
list = [1]
list[2]

7.2 抛出异常 raise

#上面可知,访问一个未定义的变量会产生NameError,详细信息是" name 's' is not defined",我们也抛出这个异常,并修改异常信息
raise NameError("抛出异常")
#结果为
NameError: 抛出异常

7.3 异常拦截
异常会终端操作,导致一些未知的清空,我们可以使用except捕捉到异常,并处理

try:
    #访问一个不存在的x,产生NameError异常
    print x
    #拦截NameError异常,使用Exception拦截所有异常
except NameError,e:
    #此处也可以print e,e保存着错误信息
    print "发生异常" 

7.4 完整的异常demo

try:
    raise NameError("抛出一个异常")
#拦截异常
except NameError,e:
#打印错误信息
    print e
#不管是否有异常都会执行finally
finally:
    print "结束"

8习题

8.1 猜数字
除了猜数字,还有两个问题,
第一个是,input如果接受到一个未定义字符串,会发生异常。
第二个是,如果在input中直接输入rand_number会直接判对。

#coding:utf-8
import random
#产生随机数字
rand_number     =   random.randint(0,100)
count = 6
while count > 0:
    try:
        input_number    =   raw_input("请输出你要猜的数字")
        input_number    =   int(input_number)
    except ValueError ,e:
        print "请输入有效的数字"
        break
    if(input_number == rand_number):
        #如果猜对了,则跳出循环
        print "恭喜你猜对了,数字就是 % s" % (rand_number)
        break
    elif(input_number < rand_number):
            print "数太小了"
    elif(input_number > rand_number):
            print "数太大了"
    count = count - 1
else:
    print "很抱歉,超时!"
    print "正确答案是 % s" % (rand_number)

其他作业都不太难,就全略过了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注