Python学习之路-python基础课 (day2)

 

 

本节内容:

  1. 变量
  2. 字符串
  3. 列表
  4. 条件判断(if.else)
  5. For循环
  6. While循环
  7. 流程控制(break、continue、pass 、exit)
  8. 运算符
  9. 编码操作
  10. 作业

 

 

1. 变量                                                                                     

 

变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变。基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。常量是一块只读的内存区域,常量一旦被初始化就不能被改变。

 

变量定义的规则:变量命名字母、数字、下划线组成,不能以数字开头,且以下关键字不能声明为变量名。

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is','lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

 

变量赋值

 

Python中的变量不需要声明,变量的赋值操作即是变量的声明和定义的过程。每个变量在内存中创建都包括变量的标识、名称、和数据这些信息。

 

 

Python中一次新的赋值,将创建一个新的变量。即使变量的名称相同,变量的标识并不同。
x = 1 #变量赋值定义一个变量x
print(id(x)) #打印变量x的标识
print(x+5)   #使用变量
print("=========华丽的分割线=========")
x = 2 #变量赋值定义一个变量x
print(id(x)) #此时的变量x已经是一个新的变量
print(x+5)   #名称相同,但是使用的是新的变量x

 

x = 'hello python'
print(id(x))
print(x)
x = ''
print(x)

此时x又将成为一个新的变量,而且变量类型也由于所赋值的数据类型改变而改变。
此处,id()为Python的内置函数。
如果变量没有赋值,Python将认为该变量不存在。

 

Python支持多个变量同时赋值(多重赋值)。

例如:

a = (1,2,3) #定义一个序列
x,y,z = a    #把序列的值分别赋x、y、z
print("a : %d, b: %d, z:%d"%(x,y,z)) #打印结果
a, b, c = 1, 2, "john"
print("a : %d, b: %d, z:%s"%(a,b,c)) #打印结果

 

dfdf

2. 字符串                                                                                    

 

定义: 

 它是一个有序的字符的集合,用于存储和表示基本的文本信息。''或""或''' '''中间包含的内容称之为字符串,在Python中的字符串被确定为一组连续的字符在引号之间,串的子       集,可以使用切片操作符可采用([]和[:]),索引从0开始的字符串的开始和结束(-1)。

  加号(+)符号的字符串连接操作符,而星号(*)表示重复操作。

特性:

  • 只能存放一个值
  • 不可变的数据类型
  • 按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

补充:

  • 字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l\thf'
  • unicode字符串与r连用必需在r前面,如name=ur'l\thf'

 

字符串创建

'hello python'
"hello python"
'''hello python'''

 

字符串常用操作

  • 字符串连接
# 字符串连接
#方法1: 用字符串的join方法
a = ['a','b','c','d']
content = ''
content = ''.join(a)
print (content)

#
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print (delimiter.join(mylist))

#方法2: 用字符串的替换占位符替换
a = ['a','b','c','d']
content = ''
content = '%s%s%s%s' % tuple(a)
print (content)

#方法3 用运算符的join方法
sStr1 = 'strcat'
sStr2 = 'append'
sStr1 += sStr2
print (sStr1)

 

  • 字符串截取
str = 'pneumonoultramicroscopicsilicovolcanoconiosis'
#print (str[开始:结束:步长])
print (str[0:3])    #截取第一位到第三位的字符
print (str[:])       #截取字符串的全部字符
print (str[6:])      #截取第七个字符到结尾
print (str[:-3])     #截取从头开始到倒数第三个字符之前
print (str[2])       #截取第三个字符
print (str[-1])      #截取倒数第一个字符
print (str[::-1])    #创造一个与原字符串顺序相反的字符串
print (str[-3:-1])  #截取倒数第三位与倒数第一位之前的字符
print (str[-3:])     #截取倒数第三位到结尾
print (str[:-5:-3]) #逆序截取,具体啥意思没搞明白?

 

  • 字符串替换
# 1.用字符串本身的replace方法:
a = 'hello word'
b = a.replace('word','python')
print (b)

# 2.用正则表达式来完成替换:
import re
a = 'hello word'
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print (b)

# 3.用符串翻译来完成替换:
msg12 = 'my name is ab'
table = str.maketrans('ab','mo')  #字符串长度必须一致
print(msg12.translate(table))

 

  • 字符串查找
#python 字符串查找有4个方法,1 find,2 index方法,3 rfind方法,4 rindex方法。
#1. find()方法:
info = 'abca'
print (info.find('a'))      #从下标0开始,查找在字符串里第一个出现的子串,返回结果:0

info = 'abca'
print (info.find('a',1))    #从下标1开始,查找在字符串里第一个出现的子串:返回结果: 3

info = 'abca'
print (info.find('333'))    #返回-1,查找不到返回-1

#2. index()方法:
#python 的index方法是在字符串里查找子串第一次出现的位置,类似字符串的find方法,不过比find方法更好的是,如果查找不到子串,会抛出异常,而不是返回-1
info = 'abca'
print (info.index('a'))
print (info.index('33'))

 

  • 字符串长度
sStr1 = 'strlen'
print (len(sStr1))

 

  • 去除空格&特殊符号
# .strip()去除左右两边空格
msg11 = '   efdfd      '
msg12 = '   efdfd,,,,,,,,,,,'
print(msg11.strip())

# .strip()去除右边空格
print(msg11.rstrip())

# .strip()去除右边,
print(msg12.rstrip())

# .strip()去除左边空格
print(msg11.lstrip())

 

  • 字符串大小写转换
sStr1 = 'JCstrlwr'
sStr3 = 'Hello World' #首字母大写
sStr1 = sStr1.upper()
sStr2 = sStr1.lower()
print (sStr1,sStr2)    #大小写转换
print(sStr1.islower(),sStr1.isupper())  #判断首字母大小写
print(sStr1.istitle(),sStr3.istitle())  #判断是否是title

msg = 'hello world'
print(msg.capitalize())#首字母大写

 

 

  • 判断字母&数字&空格&关键字&开头&结尾
msg2 = ' '
msg3 = 'a123'
msg4 = 'a123_'
msg5 = 'abcddd'
msg6 = '1323'
msg7 = 'if'

print(msg3.isalnum(),msg4.isalnum())     #至少包含一个字符,且都是字母或数字或(字母+数字)才返回True
print(msg5.isalpha())     #都是字母
print(msg6.isdecimal())   #都是数字
print(msg6.isdigit())     #都是数字
print(msg6.isnumeric())   #都是数字
print(msg2.isspace())     #都是空格
print(msg7.isidentifier()) #字符串为关键字返回True
print(msg5.startswith('a'))#字符串以字母a开始
print(msg5.endswith('d'))  #字符串以字母d结束

 

 

  • 字符串填充
msg13 = 'MO'
print(msg13.zfill(20))        #语法str.zfill(width)
print(msg13.ljust(20,'0'))    #左填充
print(msg13.rjust(20,'0'))    #左填充
print(msg13.center(20,'*'))   #居中填充

 

  • 字符串统计
msg = 'hello world'

print(msg.count('l'))      #统计'l'出现多少次
print(msg.count('l',4,10))
print(msg.count('l',4))
print(msg.count('l',4,-1))

 

  • 字符串格式化
#扩展tab
msg1 = 'a\tb'
print(msg1)
print(msg1.expandtabs(10))

#格式化传参
print('{0} {1} {0}'.format('name','age'))
print('{name}'.format(name='alex'))
print('{} {}'.format('name','age'))

 

 

 

3.   列表                                                                                     

 

列表是Python中最具灵活性的有序集合对象类型,与字符串不同的是,列表可以包含任何种类的对象:数字,字符串,甚至是其他列表.并且列表都是可变对象,它支持在原处修改的操作.也可以通过指定的索引和分片获取元素.列表就可元组的可变版本.

定义一个列表使用一对中(方)括号” [ ] “.与元组不同的是, 列表有一些内置的函数对列表进行增加,修改和删除等操作.

 

常用列表操作:

  • list.append()     #追加成员,成员数据
  • list.pop()          #删除成员,删除第i个成员
  • list.count(x)      #计算列表中参数x出现的次数
  • list.remove()     #删除列表中的成员,直接删除成员i
  • list.extend(L)    #向列表中追加另一个列表L
  • list.reverse()     #将列表中成员的顺序颠倒
  • list.index(x)      #获得参数x在列表中的位置
  • list.sort()          #将列表中的成员排序
  • list.insert()        #向列表中插入数据insert(a,b)向列表中插入数据

 

示例:

#定义一个列表
listA = ['北京', '上海', '广州', '深圳', '杭州', '天津']

# 向 list 中增加元素
# 1.使用append   向 list 的末尾追加单个元素。
listA.append('重庆')
print(listA)

# 2.使用 insert  将单个元素插入到 list 中。数值参数是插入点的索引
listA.insert(4, '郑州')   # 在下标为3处添加一个元素
print(listA)

# 3.使用 extend 用来连接 list
listA.extend(['大连','青岛','合肥','济南'])
print(listA)

'''
# extend 和 append 看起来类似,但实际上完全不同。
# extend 接受一个参数,这个参数总是一个 list,
# 并且把这个 list 中的每个元素添加到原 list 中。
# 另一方面,append 接受一个参数,这个参数可以是任何数据类型,并且简单地追加到 list 的尾部。
'''

# 获取列表的长度
print (len(listA))  # 10

#  在 list 中搜索
listA.index('深圳')       # index 在 list 中查找一个值的首次出现并返回索引值。
listA.index('石家庄')     # 如果在 list 中没有找到值,Python 会引发一个异常。
print ('青岛' in listA)   # 要测试一个值是否在 list 内,使用 in。如果值存在,它返回 True,否则返为 False 。


# 从 list 中删除元素
listA.remove(3)            # remove 从 list 中 仅仅 删除一个值的首次出现。如果在 list 中没有找到值,Python 会引发一个异常
print (listA.pop())        # pop 它会做两件事:删除 list 的最后一个元素,然后返回删除元素的值。
del listA[3]               # 下标方式删除列表值

# 遍历list
for item in listA:
    print (item)

 

 

4. 条件判断                                                                             

 

if语句用来检验一个条件, 如果条件为真,我们运行一块语句(称为 if-块 ), 否则 我们处理另外一块语句(称为 else-块 )。 else 从句是可选的。     

 

示例:

# 猜年龄小游戏
age = 23
guess_num = input("guess age:")
if guess_num.isdigit():
    guess_num = int(guess_num)
    if guess_num == age:
        print('you got it!')
    elif guess_num > age:
        print('think smaller!')
    else :
        print('think bigger!')
else:
    print('Invalid input')

 

 

4. For循环

 

Python for 和其他语言一样,也可以用来循环遍历对象。

 示例:

# 遍历一个列表

listA = ['I', 'love', 'you', '!', 'Do', 'you', 'love', 'me', '?']
for i in listA:
    print(i)

# 猜年龄小游戏(优化)
age = 23

for i in range(3):
    guess_num = input("guess age:")
    if guess_num.isdigit():
        guess_num = int(guess_num)
        if guess_num == age:
            print('you got it!')
        elif guess_num > age:
            print('think smaller!')
        else :
            print('think bigger!')
    else:
        print('Invalid input')

 

 

6.   While循环                                                                                     

                                                                                                                                                                           

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

 

while 判断条件:
    执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
执行流程图如下:

 

 

示例:

 

  • 无限循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

while True:
    print('hello python')

 

 

  • 循环使用 if.else

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO


# 猜年龄小游戏
age = 23
while True:
    guess_num = input("guess age:")
    if guess_num.isdigit():
        guess_num = int(guess_num)
        if guess_num == age:
            print('you got it!')
            exit()
        elif guess_num > age:
            print('think smaller!')
        else :
            print('think bigger!')
    else:
        print('Invalid input')

 

  • 循环使用 else 语句

 

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

counter = 0
while counter < 10:
    print('hello python')
    counter += 1
else:
    print('goodbye!')

 

 

 

7. 流程控制(break、continue、pass 、exit)                              

 

  • exit:       #结束整个程序
  • break:    #结束当前层循环
  • continue: #跳出本次循环,继续下挫循环
  • pass :      #不做任何事情,只起到占位的作用

 

示例:

 

exit示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

for i in range(10):
    for j in range(10):
        if j == 9:
            exit()      #退出整个程序
        print(i,j)

运行结果:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8

Process finished with exit code 0
View Code

 

break示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

for i in range(10):
    for j in range(10):
        if j == 9:
            break      #退出当前层循环
        print(i,j)

运行结果:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
2 0
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
3 0
3 1
3 2
3 3
3 4
3 5
3 6
3 7
3 8
4 0
4 1
4 2
4 3
4 4
4 5
4 6
4 7
4 8
5 0
5 1
5 2
5 3
5 4
5 5
5 6
5 7
5 8
6 0
6 1
6 2
6 3
6 4
6 5
6 6
6 7
6 8
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7 7
7 8
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
8 8
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8

Process finished with exit code 0
View Code

 

continue示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

counter = 0
while counter <= 10:
    counter += 1
    if counter % 2 >0:
        continue
    print(counter)

运行结果:

2
4
6
8
10

Process finished with exit code 0
View Code

 

pass示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

counter = 0
while counter <= 20:
    counter += 1
    if counter < 10:
        pass
    else:
        print(counter)

运行结果:

10
11
12
13
14
15
16
17
18
19
20
21

Process finished with exit code 0
View Code

 

 

 

7. 运算符                                                                   

 

1、算数运算:

 

 

2、比较运算:

 

 

 

3赋值运算:

 

 

 4、位运算:                                                                                                              

 

注: ~  举例: ~5 = -6  解释: 将二进制数+1之后乘以-1,即~x = -(x+1),-(101 + 1) = -110

按位反转仅能用在数字前面。所以写成 3+~5 可以得到结果-3,写成3~5就出错了

 

5、逻辑运算:    

     

 

and注解:

  1. 在Python 中,and 和 or 执行布尔逻辑演算,如你所期待的一样,但是它们并不返回布尔值;而是,返回它们实际进行比较的值之一。
  2. 在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。
  3. 如果布尔上下文中的某个值为假,则 and 返回第一个假值

or注解:

  1. 使用 or 时,在布尔上下文中从左到右演算值,就像 and 一样。如果有一个值为真,or 立刻返回该值
  2. 如果所有的值都为假,or 返回最后一个假值
  3. 注意 or 在布尔上下文中会一直进行表达式演算直到找到第一个真值,然后就会忽略剩余的比较值

and-or结合使用:

  1. 结合了前面的两种语法,推理即可。
  2. 为加强程序可读性,最好与括号连用,例如:
    (1 and 'x') or 'y'

 6、成员运算:

 

 

 7身份运算:

 

   

 

 8、运算符优先级:自上而下,优先级从高到低:

 

 

 

9. 编码操作                                                                                     

 

详细文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

 

需知:

1.在python2默认编码是ASCII, python3里默认是utf-8

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-8就是unicode

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

 

 

#-*-coding:utf-8-*-
__author__ = 'Alex Li'

import sys
print(sys.getdefaultencoding())


msg = "我爱北京天安门"
msg_gb2312 = msg.decode("utf-8").encode("gb2312")
gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk")

print(msg)
print(msg_gb2312)
print(gb2312_to_gbk)

in python2
in python2
#-*-coding:gb2312 -*-   #这个也可以去掉
__author__ = 'Alex Li'

import sys
print(sys.getdefaultencoding())


msg = "我爱北京天安门"
#msg_gb2312 = msg.decode("utf-8").encode("gb2312")
msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔
gb2312_to_unicode = msg_gb2312.decode("gb2312")
gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")

print(msg)
print(msg_gb2312)
print(gb2312_to_unicode)
print(gb2312_to_utf8)

in python3
in python3

 

 

10. 作业                                                                                    

 

1、简易购物车

  • 流程图:

 

  • 代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: MO

# 导入系统模块
import time,pickle,os
# 初始化购物车、账户余额
if  os.path.exists('status.txt'):
    buy_list = pickle.load(open('status.txt', 'rb'))
    balance = buy_list['balance']
else:
    buy_list = {}
    balance = 0
# 定义资金变量
salary = 0
# 定义商品列表
goods =[["iphone",5800],['macbook',12800],['coffee',30],['bike',2000]]

# 账户充值模块
print('账户充值'.center(50,'*'))
print('您当前的账户余额为:\033[31;1m[%s]\033[0m' % balance)
salary_choose = input('账户充值 [yes or no]:')
while True:
    if salary_choose == 'yes':
        balance = int(balance)
        salary = int(salary)
        salary_input = input("请输入充值金额:")
        if salary_input.isdigit():
            salary_input = int(salary_input.strip())
            salary = balance + salary_input + salary
            print('您充值的金额是:\033[31;1m[%d]\033[0m' % salary_input,'您当前账户总金额是:\033[31;1m[%d]\033[0m' % salary)
            #break
        else:
            print("无效的输入,请输入数字!!!")
        select_input = input('是否继续充值[yes or no]:')
        if select_input == 'yes':
            continue
        else:
            print('您当前账户总金额是:\033[31;1m[%d]\033[0m' % salary)
            break

    elif salary_choose == 'no':
        salary = balance + salary
        print('您当前账户总金额是:\033[31;1m[%d]\033[0m' % salary)
        break
    else:
        print('无效的输入!')

# 商品购买模块
while True:
    print('商品列表'.center(50, '*'))
    for i,j in enumerate(goods):
        print(i,j[0],j[1])
    choose = input("请选择您要购买的商品编号: 或[quit]退出:")
    if choose.isdigit():
        choose = int(choose)
        if choose >=0 and choose <len(goods):
            goods_price = goods[choose][1]
            goods_name = goods[choose][0]
            if goods_price < salary:
                order_time =time.ctime()
                salary -= goods_price
                # buy_list.append([goods_name,goods_price])
                if goods_name in buy_list.keys():
                    buy_list[goods_name]['goods_nums'] += 1
                    buy_list[goods_name]['order_time'] = order_time
                else:
                    buy_list[goods_name] = {'goods_price':goods_price,'goods_nums':1,'order_time':order_time}
                print('\033[32;1m[%s]\033[0m商品已加入购物车' %goods_name,'您当前余额是:\033[31;1m[%d]\033[0m' %salary)
            else:
                print('余额不足,您当前余额是:\033[31;1m[%d]\033[0m' %salary)
        else:
            print('暂无此商品,请输入正确的商品编号!')
    elif choose == 'quit':
        print('您已购买的商品'.center(50,'*'))
        print(buy_list)
        print('您当前余额是:\033[31;1m[%d]\033[0m' %salary)
        buy_list['balance'] = salary
        pickle.dump(buy_list, open('status.txt', 'wb'))
        exit()
    else:
        print('无效的输入,商品编号为数字!')
View Code

 

2、三级菜单

  • 流程图:

 

  • 代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auth: Mo

city_dict = {'广州': {'天河': ['天河体育馆', '金山大夏'],
                    '越秀': ['越秀公园', '光孝寺'],
                    '番禺': ['长隆欢乐世界', '大夫山']},
             '深圳': {'福田': ['莲花山', '赛格'],
                    '龙华': ['元山公园', '龙城广场'],
                    '南山': ['世界之窗', '欢乐谷']},
             '佛山': {'禅城': ['梁园', '孔庙'],
                    '南海': ['千灯湖', '南国桃园'],
                    '顺德': ['清晖园', '西山庙']}}



while True:
    print(''.center(50,'*'))
    for i in city_dict:
        print(i)
    province_input = input('请输入省份名称: 或[quit]退出:')
    if province_input.strip() in city_dict:
        province_name = province_input.strip()
        while True:
            print(''.center(50, '*'))
            for i in city_dict[province_name]:
                print(i)
            city_input = input('请输入城市名称: 或[back]返回:')
            if city_input.strip() in city_dict[province_name]:
                city_name = city_input.strip()
                while True:
                    print(''.center(50, '*'))
                    for i in city_dict[province_name][city_name]:
                        print(i)
                    town_input = input('请输入[back]返回:')
                    if town_input == 'back':
                        break
                    else:
                        print('无效的输入,请按提示输入!')
            elif city_input == 'back':
                break
            else:
                print('无效的输入,请输入城市名称!')
    elif province_input == 'quit':
        print('退出查询系统。')
        exit()
    else:
        print('无效的输入,请输入省份名称!')
View Code

 

posted @ 2016-10-21 13:40  MoPy  阅读(309)  评论(0编辑  收藏  举报