1.变量和简单数据类型1.变量message = 'hello world python'print(message) 2.命名1.命名与使用2.使用变量时避免命名错误3.字符串1.使用方法修改字符串的大小写name = 'ada lovelace'print(name.title())输出得到:Ada Lovelace title()以首字母大写的方式显示每个单词,即每个单词的首字母都改为大写 print(name.upper())print(name.lower())得到:ADA LOVELACEada lovelace 2.拼接字符串用“+” 来拼接字符串 “\t,\n”来空格与换行 3.删除空白
msg = ' python 'print(msg.rstrip())print(msg.lstrip())print(msg.strip())得到 pythonpython python 4.使用字符串避免语法错误单引号与单引号一对, 4.使用函数str()避免类型错误age = 23msg = 'Happy '+str(age)+' rd Birthday' # 必须使用str()否则python识别不了print(msg) 3.列表简介1.列表是什么bicycles = ['trek','cannondale','redline','specialized']print(bicycles) 1.访问列表元素print(bicycles[0])得到trek 2.索引从0而不是1开始2.修改,添加和删除元素1.修改列表元素names =['zhangsan','lisi','wangwu','zhaoliu']print(names)names[0] = 'zhangsanfeng'print(names)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu'] 2.列表中添加元素
names.append('qianda') print(names) 得到: ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu', 'qianda'] cars = [] cars.append('honda') cars.append('honda2') cars.append('honda3') print(cars) 得到 ['honda', 'honda2', 'honda3']
nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)poped_nicks = nicks.pop(0)print('The first name is '+poped_nicks.title()+'.')得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']The first name is Zhangsan. 如果不确定使用del语句还是pop()方法,有一个简单的标准:如果你要从列表中删除的一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()
3.组织列表1.使用方法sort()对列表进行永久性排序—按字母排序nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)nicks.sort();print(nicks)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['lisi', 'wangwu', 'zhangsan', 'zhaoliu']还可以按字母顺序相反的顺序排列列表元素,只需要向sort()方法传递参数reverse = Truenicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)nicks.sort(reverse = True);print(nicks)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['zhaoliu', 'zhangsan', 'wangwu', 'lisi'] 2.使用方法sorted()对列表进行临时排序—按字母排序nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)print(sorted(nicks))print(nicks)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['lisi', 'wangwu', 'zhangsan', 'zhaoliu']['zhangsan', 'lisi', 'wangwu', 'zhaoliu']还可以相反顺序临时排序nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)print(sorted(nicks,reverse = True))print(nicks)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['zhaoliu', 'zhangsan', 'wangwu', 'lisi']['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] 3.倒着打印列表,按元素反转列表排序nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks)nicks.reverse()print(nicks)得到:['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['zhaoliu', 'wangwu', 'lisi', 'zhangsan']方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复原来的排列顺序,只需要再次调用reverse() 4.确定列表的长度nicks =['zhangsan','lisi','wangwu','zhaoliu']print(len(nicks))得到:4 4.使用列表时避免索引错误注意元素的个数,另外访问最后一个元素时,都可使用索引-1,倒数第2个可以使用索引-2,依次类推 nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks[-1])得到:zhaoliu 4.操作列表1.遍历整个列表nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick)得到:zhangsanlisiwangwuzhaoliufor cat in cats:for dog in dogsfor item in list_of_items使用单数和复数的式名称可帮助判断代码段处理的是单个列表元素还是整个列表。 1.在for循坏环中执行更多的操作在每条记录中打印一条消息。 nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick.title()+', welcome to china')得到:Zhangsan, welcome to chinaLisi, welcome to chinaWangwu, welcome to chinaZhaoliu, welcome to china 执行多行代码,这里需要注意一下,接下来的代码都是需要缩进的 nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick.title()+', welcome to china') print('hello,python')得到:Zhangsan, welcome to chinahello,pythonLisi, welcome to chinahello,pythonWangwu, welcome to chinahello,pythonZhaoliu, welcome to chinahello,python 2.在for循环结束后执行一些操作nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick.title()+', welcome to china') print('hello,python')print('print all message and print finish!')得到:Zhangsan, welcome to chinahello,pythonLisi, welcome to chinahello,pythonWangwu, welcome to chinahello,pythonZhaoliu, welcome to chinahello,pythonprint all message and print finish!可以看到最后一条要打印的消息只打印一次,最后一条没有缩进,因此只打印一次 2.避免缩进错误
nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks:print(nick.title()+', welcome to china')得到: File '/Users/liuking/Documents/python/python_learn/test.py', line 22 print(nick.title()+', welcome to china') ^IndentationError: expected an indented block
其实想打印两行的消息,结果只打印了一行,print('hello,python') 忘记缩进了,结果只是最后一条打印了这条消息nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick.title()+', welcome to china')print('hello,python')得到:Zhangsan, welcome to chinaLisi, welcome to chinaWangwu, welcome to chinaZhaoliu, welcome to chinahello,python
message = 'hello python world' print(message)得到: File '/Users/liuking/Documents/python/python_learn/test.py', line 20 print(message) ^IndentationError: unexpected indent
第三个打印的消息没有缩进,结果每一行都被打印出来了。nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks: print(nick.title()+', welcome to china') print('hello,python') print('print all message and print finish!')得到:Zhangsan, welcome to chinahello,pythonprint all message and print finish!Lisi, welcome to chinahello,pythonprint all message and print finish!Wangwu, welcome to chinahello,pythonprint all message and print finish!Zhaoliu, welcome to chinahello,pythonprint all message and print finish!
3.创建数值列表1.使用函数range()函数range()让你能够轻松地生成一系列的数字。 for value in range(1,5): print(value)得到:1234只打印了1〜4 函数range()从指定的第一个值开始数,并在到达你指定的你第二个值后停止。 2.使用range()创建数字列表要创建数字列表,可使用函数list()将range()的结果直接转换为列表,如果将range()作为list()的参数,输出将为一个数字列表。 numbers = list(range(1,6))print(numbers)得到:[1, 2, 3, 4, 5] 把10个整数的平方加入列表中,并打印出来 squares = []numbers = range(1,11)for number in numbers: squares.append(number**2)print(squares)得到:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 3.对数字列表执行简单的统计计算最小值,最大值,求和 digits = [1,2,3,4,5,6,7,8,9,0]print(min(digits))print(max(digits))print(sum(digits))得到:0945 4.使用列表的一部分1.切片nicks =['zhangsan','lisi','wangwu','zhaoliu']print(nicks[0:3]) 前一个数从0开始,后一个数从1开始数print(nicks[2:3]) 从2开始,截止到第4个元素print(nicks[2:]) 从2开始,没有指定截止数据,直接数到末尾print(nicks[:2]) 没有指定开始,默认从0开始print(nicks[:]) 没有指定开始,也没有指定结束的,直接复制整个列表print(nicks[-2:]) 从倒数第2个开始得到:['zhangsan', 'lisi', 'wangwu']['wangwu']['wangwu', 'zhaoliu']['zhangsan', 'lisi']['zhangsan', 'lisi', 'wangwu', 'zhaoliu']['wangwu', 'zhaoliu'] 2.遍历切片nicks =['zhangsan','lisi','wangwu','zhaoliu']for nick in nicks[0:3]: print(nick.title())得到:ZhangsanLisiWangwu 3.复制列表—-需要特别注意了nicks =['zhangsan','lisi','wangwu','zhaoliu']nicks_copy = nicks[:]print('original nicks')print(nicks)print('copy nicks')print(nicks_copy)得到:original nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu']copy nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] 为了核实我们确实有两个列表, nicks =['zhangsan','lisi','wangwu','zhaoliu']nicks_copy = nicks[:]nicks.append('zhangsanfeng')nicks_copy.append('zhangwuji')print('original nicks')print(nicks)print('copy nicks')print(nicks_copy)得到:original nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng']copy nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangwuji'] 如果我们只是简单的nicks赋值给nicks_copy就不能得到两个列表 nicks =['zhangsan','lisi','wangwu','zhaoliu']nicks_copy = nicks;nicks.append('zhangsanfeng')nicks_copy.append('zhangwuji')print('original nicks')print(nicks)print('copy nicks')print(nicks_copy)得到:original nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']copy nicks['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji']因为nicks和nicks_copy都指向同一个列表,所以都打印出了相同的列表,这里要特别注意 5.元组python将不能修改的值称为不可变的,而不可变的列表被称为元组。有的时候需要创建一系列不可修改的元素,元组可以满足这种需要。
元组看起来像列表,但使用圆括号而不是方括号来标识,定义元组后,就可以使用索引来访问其元素。 point = (200,50,300,90)print(point[0])print(point[1])print(point[2])print(point[-1])得到:2005030090
points = (200,50,300,90)for point in points: print(point)得到:2005030090
print('original data')points = (200,50,300,90)for point in points: print(point)print('\nmodify data')points = (1,2,3,4)for point in points: print(point)得到:original data2005030090modify data1234 5.if语句1.条件测试
request_topping = ['mushrooms','onions','pineapple']print('mushrooms' in request_topping)print('mush' in request_topping)得到:TrueFalse
request_topping = ['mushrooms','onions','pineapple']print('mushrooms' not in request_topping)print('mush' not in request_topping)得到:FalseTrue 2.if语句 主要注意的是代码缩进,
6.字典1.字典的简单使用在Python中字典是一系列的键值对,每一个键都与一个值相关联,与键相关联的值可以是数字,字符串,列表,乃至字典。
alien_0 = {'color':'green','point':5}print(alien_0['color'])得到:green
alien_0 = {'color':'green','point':5}print(alien_0)alien_0['x_point'] = 250alien_0['y_point'] = 100print(alien_0)得到:{'color': 'green', 'point': 5}{'color': 'green', 'y_point': 100, 'x_point': 250, 'point': 5}
alien_0 = {}alien_0['x_point'] = 250alien_0['y_point'] = 100print(alien_0)得到:{'y_point': 100, 'x_point': 250}
alien_0 = {}alien_0['y_point'] = 100print(alien_0)alien_0['y_point'] = 1000print(alien_0)得到:{'y_point': 100}{'y_point': 1000}
alien_0 = {'color':'green','point':5}print(alien_0)del alien_0['point']print(alien_0)得到:{'color': 'green', 'point': 5}{'color': 'green'} 2.遍历字典
values = {'1':'one','2':'two','3':'three','4':'four'}for value in values.items(): print(value)for key,value in values.items(): print('\nkey:'+key) print('value:'+value)得到:('1', 'one')('3', 'three')('2', 'two')('4', 'four')key:1value:onekey:3value:threekey:2value:twokey:4value:four 1.遍历字典中所有的键values = {'1':'one','2':'two','3':'three','4':'four'}for value in values.keys(): print(value)得到:1324 2.遍历字典中所有的值values = {'1':'one','2':'two','3':'three','4':'four'}for value in values.values(): print(value)得到:onethreetwofour 3.按顺序遍历字典中所有键values = {'first':'one','second':'two','three':'three'}for value in sorted(values.keys()): print(value)得到:firstsecondthree 完 7.用户输入和while循环1.函数input()工作原理注意:用户输入只能从终端运行,不能直接通过sublime来运行。 os x系统从终端运行python程序: 1. liukingdeMacBook-Pro:~ liuking$ cd Desktop2. liukingdeMacBook-Pro:Desktop liuking$ ls3. input.py4. python3 input.py5. 输出得到结果6. 首先:写一段python 文件 name = input('Please enter your name: ')print('Hello,'+name)在终端中运行得到:liukingdeMacBook-Pro:Desktop liuking$ python3 input.pyPlease enter your name: kobe bryantHello,kobe bryantliukingdeMacBook-Pro:Desktop liuking$ 多行输入展示: 多行展示可以用+=来追加字符串。 prompt = 'If you tell us who you are,we can personalize the message you see.'prompt += '\nWhat is your first name?'name = input(prompt)print('\n Hello,'+name)得到:liukingdeMacBook-Pro:Desktop liuking$ python3 input.pyIf you tell us who you are,we can personalize the message you see.What is your first name?zhang Hello,zhangliukingdeMacBook-Pro:Desktop liuking$ 注意以下几点:
height = input('How tall are you ,in inches? ')height = int(height)if height >= 36: print('\n you're tall enought to ride')else: print('\nyou'll be able to ride when you're a little older.')得到:liukingdeMacBook-Pro:Desktop liuking$ python3 input.pyHow tall are you ,in inches? 43 you're tall enought to rideliukingdeMacBook-Pro:Desktop liuking$ 注意这里使用了int()把数据类型转换了一下,
求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少 >>> 5%32>>> 6%20>>> 2.Whil循环1.使用While循环number = input('遍历你输入的数据:')number = int(number)begin = int(0)while begin <= number:="" ="" print(begin)="" ="" begin="" +="1;得到:liukingdeMacBook-Pro:Desktop" liuking$="" python3=""> 2.让用户选择何时退出promt = '\nTell me something and I will repeat it back to you:'promt += '\n Enter 'quit' to end the program.'message = ''while message != 'quit': message = input(promt) if message != 'quit': print(message)终端运行得到:liukingdeMacBook-Pro:DeskTop liuking$ python3 input.pyTell me something and I will repeat it back to you: Enter 'quit' to end the program: NBANBATell me something and I will repeat it back to you: Enter 'quit' to end the program: CBACBATell me something and I will repeat it back to you: Enter 'quit' to end the program: quitliukingdeMacBook-Pro:DeskTop liuking$ 其它使用方式:
3.使用While循环来处理列表和字典1.在列表之间移动元素unconfirmed_users = ['one','two','three']confirmed_users = []while unconfirmed_users: current_user = unconfirmed_users.pop() print('verifying User:'+current_user) confirmed_users.append(current_user)# 显示所有已验证用户 print(“\n The following users have been confirmed: “) 得到: The following users have been confirmed: #####2.使用用户输入来填充字典 responses = {} 设置一个标志,指出调查是否继续polling_active = True while polling_active: # 提示输入被调查者的名字和回答name = input('\nWhat is your name?')response = input('Which mountain would you like to climb someday?')# 将答案存在字典中responses[name] = response# 看看是否还有人要参加调查repeat = input('would you like to let another person respond?(Y/N)')if repeat == 'N': polling_active = False 调查结果,显示结果print('\n----Poll results-----')for name,response in responses.items(): print(name+' would like to climb '+ response+'.')在终端运行得到:liukingdeMacBook-Pro:Desktop liuking$ python3 input.pyWhat is your name?KobeWhich mountain would you like to climb someday?武当山 would you like to let another person respond?(Y/N)YWhat is your name?姚明Which mountain would you like to climb someday?灵山 would you like to let another person respond?(Y/N)N----Poll results-----Kobe would like to climb 武当山.姚明 would like to climb 灵山.liukingdeMacBook-Pro:Desktop liuking$ 完。 |
|