标签:begin who python基础 长度 strong 因此 遍历 表之间 nba
1.起步message = "hello world python"
print(message)
name = ‘ada lovelace‘
print(name.title())
输出得到:
Ada Lovelace
title()以首字母大写的方式显示每个单词,即每个单词的首字母都改为大写
print(name.upper())
print(name.lower())
得到:
ADA LOVELACE
ada lovelace
用“+” 来拼接字符串
“\t,\n”来空格与换行
msg = ‘ python ‘
print(msg.rstrip())
print(msg.lstrip())
print(msg.strip())
得到
python
python
python
单引号与单引号一对,
双引号与双引号是一对,
一般要成对出现,且。
age = 23
msg = "Happy "+str(age)+" rd Birthday" # 必须使用str()否则python识别不了
print(msg)
bicycles = [‘trek‘,‘cannondale‘,‘redline‘,‘specialized‘]
print(bicycles)
print(bicycles[0])
得到
trek
names =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(names)
names[0] = ‘zhangsanfeng‘
print(names)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsanfeng‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
在列表末尾添加元素
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‘]
在列表中插入元素
cars.insert(0,‘honda0‘)
print(cars)
得到:
[‘honda0‘, ‘honda‘, ‘honda2‘, ‘honda3‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
del nicks[0]
print(nicks)
得到:
[‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
poped_nicks = nicks.pop();
print(nicks)
print(poped_nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘]
zhaoliu
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()
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.remove(‘lisi‘)
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsan‘, ‘wangwu‘, ‘zhaoliu‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.sort();
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘lisi‘, ‘wangwu‘, ‘zhangsan‘, ‘zhaoliu‘]
还可以按字母顺序相反的顺序排列列表元素,只需要向sort()方法传递参数reverse = True
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.sort(reverse = True);
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhaoliu‘, ‘zhangsan‘, ‘wangwu‘, ‘lisi‘]
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‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.reverse()
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhaoliu‘, ‘wangwu‘, ‘lisi‘, ‘zhangsan‘]
方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复原来的排列顺序,只需要再次调用reverse()
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(len(nicks))
得到:4
####4.使用列表时避免索引错误
注意元素的个数,另外访问最后一个元素时,都可使用索引-1,倒数第2个可以使用索引-2,依次类推
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks[-1])
得到:
zhaoliu
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick)
得到:
zhangsan
lisi
wangwu
zhaoliu
for cat in cats:
for dog in dogs
for item in list_of_items
使用单数和复数的式名称可帮助判断代码段处理的是单个列表元素还是整个列表。
在每条记录中打印一条消息。
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick.title()+", welcome to china")
得到:
Zhangsan, welcome to china
Lisi, welcome to china
Wangwu, welcome to china
Zhaoliu, welcome to china
执行多行代码,这里需要注意一下,接下来的代码都是需要缩进的
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick.title()+", welcome to china")
print("hello,python")
得到:
Zhangsan, welcome to china
hello,python
Lisi, welcome to china
hello,python
Wangwu, welcome to china
hello,python
Zhaoliu, welcome to china
hello,python
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 china
hello,python
Lisi, welcome to china
hello,python
Wangwu, welcome to china
hello,python
Zhaoliu, welcome to china
hello,python
print all message and print finish!
可以看到最后一条要打印的消息只打印一次,最后一条没有缩进,因此只打印一次
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 china
Lisi, welcome to china
Wangwu, welcome to china
Zhaoliu, welcome to china
hello,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 china
hello,python
print all message and print finish!
Lisi, welcome to china
hello,python
print all message and print finish!
Wangwu, welcome to china
hello,python
print all message and print finish!
Zhaoliu, welcome to china
hello,python
print all message and print finish!
函数range()让你能够轻松地生成一系列的数字。
for value in range(1,5):
print(value)
得到:
1
2
3
4
只打印了1?4 函数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]
最小值,最大值,求和
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
得到:
0
9
45
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‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks[0:3]:
print(nick.title())
得到:
Zhangsan
Lisi
Wangwu
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都指向同一个列表,所以都打印出了相同的列表,这里要特别注意
python将不能修改的值称为不可变的,而不可变的列表被称为元组。有的时候需要创建一系列不可修改的元素,元组可以满足这种需要。
元组看起来像列表,但使用圆括号而不是方括号来标识,定义元组后,就可以使用索引来访问其元素。
point = (200,50,300,90)
print(point[0])
print(point[1])
print(point[2])
print(point[-1])
得到:
200
50
300
90
points = (200,50,300,90)
for point in points:
print(point)
得到:
200
50
300
90
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 data
200
50
300
90
modify data
1
2
3
4
request_topping = [‘mushrooms‘,‘onions‘,‘pineapple‘]
print(‘mushrooms‘ in request_topping)
print(‘mush‘ in request_topping)
得到:
True
False
request_topping = [‘mushrooms‘,‘onions‘,‘pineapple‘]
print(‘mushrooms‘ not in request_topping)
print(‘mush‘ not in request_topping)
得到:
False
True
在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‘] = 250
alien_0[‘y_point‘] = 100
print(alien_0)
得到:
{‘color‘: ‘green‘, ‘point‘: 5}
{‘color‘: ‘green‘, ‘y_point‘: 100, ‘x_point‘: 250, ‘point‘: 5}
alien_0 = {}
alien_0[‘x_point‘] = 250
alien_0[‘y_point‘] = 100
print(alien_0)
得到:
{‘y_point‘: 100, ‘x_point‘: 250}
alien_0 = {}
alien_0[‘y_point‘] = 100
print(alien_0)
alien_0[‘y_point‘] = 1000
print(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‘}
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:1
value:one
key:3
value:three
key:2
value:two
key:4
value:four
values = {‘1‘:‘one‘,‘2‘:‘two‘,‘3‘:‘three‘,‘4‘:‘four‘}
for value in values.keys():
print(value)
得到:
1
3
2
4
values = {‘1‘:‘one‘,‘2‘:‘two‘,‘3‘:‘three‘,‘4‘:‘four‘}
for value in values.values():
print(value)
得到:
one
three
two
four
values = {‘first‘:‘one‘,‘second‘:‘two‘,‘three‘:‘three‘}
for value in sorted(values.keys()):
print(value)
得到:
first
second
three
完
注意:用户输入只能从终端运行,不能直接通过sublime来运行。
os x系统从终端运行python程序:
1. liukingdeMacBook-Pro:~ liuking$ cd Desktop
2. liukingdeMacBook-Pro:Desktop liuking$ ls
3. input.py
4. python3 input.py
5. 输出得到结果
6.
首先:写一段python 文件
name = input("Please enter your name: ")
print("Hello,"+name)
在终端中运行得到:
liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
Please enter your name: kobe bryant
Hello,kobe bryant
liukingdeMacBook-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.py
If you tell us who you are,we can personalize the message you see.
What is your first name?zhang
Hello,zhang
liukingdeMacBook-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.py
How tall are you ,in inches? 43
you‘re tall enought to ride
liukingdeMacBook-Pro:Desktop liuking$
注意这里使用了int()把数据类型转换了一下,
求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少
>>> 5%3
2
>>> 6%2
0
>>>
number = input("遍历你输入的数据:")
number = int(number)
begin = int(0)
while begin <= number:
print(begin)
begin += 1;
得到:
liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
遍历你输入的数据:10
0
1
2
3
4
5
6
7
8
9
10
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.py
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: NBA
NBA
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: CBA
CBA
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: quit
liukingdeMacBook-Pro:DeskTop liuking$
其它使用方式:
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: ")
for user in confirmed_users:
print(user.title())
得到:
verifying User:three
verifying User:two
verifying User:one
The following users have been confirmed:
Three
Two
One
#####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.py
What is your name?Kobe
Which mountain would you like to climb someday?武当山
would you like to let another person respond?(Y/N)Y
What 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$
完。
message = "hello world python"
print(message)
name = ‘ada lovelace‘
print(name.title())
输出得到:
Ada Lovelace
title()以首字母大写的方式显示每个单词,即每个单词的首字母都改为大写
print(name.upper())
print(name.lower())
得到:
ADA LOVELACE
ada lovelace
用“+” 来拼接字符串
“\t,\n”来空格与换行
msg = ‘ python ‘
print(msg.rstrip())
print(msg.lstrip())
print(msg.strip())
得到
python
python
python
#####4.使用字符串避免语法错误
单引号与单引号一对,
双引号与双引号是一对,
一般要成对出现,且。
####4.使用函数str()避免类型错误
age = 23
msg = "Happy "+str(age)+" rd Birthday" # 必须使用str()否则python识别不了
print(msg)
bicycles = [‘trek‘,‘cannondale‘,‘redline‘,‘specialized‘]
print(bicycles)
print(bicycles[0])
得到
trek
names =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(names)
names[0] = ‘zhangsanfeng‘
print(names)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsanfeng‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
在列表末尾添加元素
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‘]
在列表中插入元素
cars.insert(0,‘honda0‘)
print(cars)
得到:
[‘honda0‘, ‘honda‘, ‘honda2‘, ‘honda3‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
del nicks[0]
print(nicks)
得到:
[‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
poped_nicks = nicks.pop();
print(nicks)
print(poped_nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘]
zhaoliu
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()
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.remove(‘lisi‘)
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhangsan‘, ‘wangwu‘, ‘zhaoliu‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.sort();
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘lisi‘, ‘wangwu‘, ‘zhangsan‘, ‘zhaoliu‘]
还可以按字母顺序相反的顺序排列列表元素,只需要向sort()方法传递参数reverse = True
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks)
nicks.sort(reverse = True);
print(nicks)
得到:
[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhaoliu‘]
[‘zhaoliu‘, ‘zhangsan‘, ‘wangwu‘, ‘lisi‘]
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()
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(len(nicks))
得到:4
####4.使用列表时避免索引错误
注意元素的个数,另外访问最后一个元素时,都可使用索引-1,倒数第2个可以使用索引-2,依次类推
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print(nicks[-1])
得到:
zhaoliu
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick)
得到:
zhangsan
lisi
wangwu
zhaoliu
for cat in cats:
for dog in dogs
for item in list_of_items
使用单数和复数的式名称可帮助判断代码段处理的是单个列表元素还是整个列表。
在每条记录中打印一条消息。
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick.title()+", welcome to china")
得到:
Zhangsan, welcome to china
Lisi, welcome to china
Wangwu, welcome to china
Zhaoliu, welcome to china
执行多行代码,这里需要注意一下,接下来的代码都是需要缩进的
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks:
print(nick.title()+", welcome to china")
print("hello,python")
得到:
Zhangsan, welcome to china
hello,python
Lisi, welcome to china
hello,python
Wangwu, welcome to china
hello,python
Zhaoliu, welcome to china
hello,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 china
hello,python
Lisi, welcome to china
hello,python
Wangwu, welcome to china
hello,python
Zhaoliu, welcome to china
hello,python
print 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 china
Lisi, welcome to china
Wangwu, welcome to china
Zhaoliu, welcome to china
hello,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 china
hello,python
print all message and print finish!
Lisi, welcome to china
hello,python
print all message and print finish!
Wangwu, welcome to china
hello,python
print all message and print finish!
Zhaoliu, welcome to china
hello,python
print all message and print finish!
函数range()让你能够轻松地生成一系列的数字。
for value in range(1,5):
print(value)
得到:
1
2
3
4
只打印了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]
最小值,最大值,求和
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
得到:
0
9
45
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‘]
nicks =[‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
for nick in nicks[0:3]:
print(nick.title())
得到:
Zhangsan
Lisi
Wangwu
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])
得到:
200
50
300
90
points = (200,50,300,90)
for point in points:
print(point)
得到:
200
50
300
90
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 data
200
50
300
90
modify data
1
2
3
4
request_topping = [‘mushrooms‘,‘onions‘,‘pineapple‘]
print(‘mushrooms‘ in request_topping)
print(‘mush‘ in request_topping)
得到:
True
False
request_topping = [‘mushrooms‘,‘onions‘,‘pineapple‘]
print(‘mushrooms‘ not in request_topping)
print(‘mush‘ not in request_topping)
得到:
False
True
在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‘] = 250
alien_0[‘y_point‘] = 100
print(alien_0)
得到:
{‘color‘: ‘green‘, ‘point‘: 5}
{‘color‘: ‘green‘, ‘y_point‘: 100, ‘x_point‘: 250, ‘point‘: 5}
alien_0 = {}
alien_0[‘x_point‘] = 250
alien_0[‘y_point‘] = 100
print(alien_0)
得到:
{‘y_point‘: 100, ‘x_point‘: 250}
alien_0 = {}
alien_0[‘y_point‘] = 100
print(alien_0)
alien_0[‘y_point‘] = 1000
print(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‘}
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:1
value:one
key:3
value:three
key:2
value:two
key:4
value:four
values = {‘1‘:‘one‘,‘2‘:‘two‘,‘3‘:‘three‘,‘4‘:‘four‘}
for value in values.keys():
print(value)
得到:
1
3
2
4
values = {‘1‘:‘one‘,‘2‘:‘two‘,‘3‘:‘three‘,‘4‘:‘four‘}
for value in values.values():
print(value)
得到:
one
three
two
four
values = {‘first‘:‘one‘,‘second‘:‘two‘,‘three‘:‘three‘}
for value in sorted(values.keys()):
print(value)
得到:
first
second
three
完
注意:用户输入只能从终端运行,不能直接通过sublime来运行。
os x系统从终端运行python程序:
1. liukingdeMacBook-Pro:~ liuking$ cd Desktop
2. liukingdeMacBook-Pro:Desktop liuking$ ls
3. input.py
4. python3 input.py
5. 输出得到结果
6.
首先:写一段python 文件
name = input("Please enter your name: ")
print("Hello,"+name)
在终端中运行得到:
liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
Please enter your name: kobe bryant
Hello,kobe bryant
liukingdeMacBook-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.py
If you tell us who you are,we can personalize the message you see.
What is your first name?zhang
Hello,zhang
liukingdeMacBook-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.py
How tall are you ,in inches? 43
you‘re tall enought to ride
liukingdeMacBook-Pro:Desktop liuking$
注意这里使用了int()把数据类型转换了一下,
求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少
>>> 5%3
2
>>> 6%2
0
>>>
####2.Whil循环
#####1.使用While循环
number = input("遍历你输入的数据:")
number = int(number)
begin = int(0)
while begin <= number:
print(begin)
begin += 1;
得到:
liukingdeMacBook-Pro:Desktop liuking$ python3 input.py
遍历你输入的数据:10
0
1
2
3
4
5
6
7
8
9
10
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.py
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: NBA
NBA
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: CBA
CBA
Tell me something and I will repeat it back to you:
Enter ‘quit‘ to end the program: quit
liukingdeMacBook-Pro:DeskTop liuking$
其它使用方式:
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: ")
for user in confirmed_users:
print(user.title())
得到:
verifying User:three
verifying User:two
verifying User:one
The following users have been confirmed:
Three
Two
One
#####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.py
What is your name?Kobe
Which mountain would you like to climb someday?武当山
would you like to let another person respond?(Y/N)Y
What 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$
完。
标签:begin who python基础 长度 strong 因此 遍历 表之间 nba
原文地址:http://blog.51cto.com/7200087/2070275