Python入门教程

阅读: 评论:0

2024年1月26日发(作者:)

Python入门教程

Python 入门教程 1 ---- Python Syntax

1 Python是一个高效的语言,读和写的操作都是很简单的,就像普通的英语一样

2 Python是一个解释执行的语言,我们不需要去编译,我们只要写出代码即可运行

3 Python是一个面向对象的语言,在Python里面一切皆对象

4 Python是一门很有趣的语言

5 变量:一个变量就是一个单词,只有一个单一的值

练习:设置一个变量my_variable,值设置为10

[cpp]

#Write your code below!

my_variable = 10

3 第三节

1 Python里面有三种数据类型 interage , floats , booleans

2 Python是一个区分大小写的语言

3 练习

1 把变量my_int 值设置为7

2 把变量my_float值设置为1.23

3 把变量my_bool值设置为true

[python]

#Set the variables to the values listed in the instructions!

my_int = 7

my_float = 1.23

my_bool = True

1

6 Python的变量可以随时进行覆盖

2 练习:my_int的值从7改为3,并打印出my_int

[python]

#my_int is set to 7 below. What do you think

#will happen if we reset it to 3 and print the result?

my_int = 7

#Change the value of my_int to 3 on line 8!

my_int = 3

#Here's some code that will print my_int to the console:

#The print keyword will be covered in detail soon!

print my_int

7 Pyhton的声明和英语很像

8 Python里面声明利用空格在分开

3 练习: 查看以下代码的错误

[python]

def spam():

eggs = 12

return eggs

print spam()

9 Python中的空格是指正确的缩进

2 练习: 改正上一节中的错误

2

[python]

def spam():

eggs = 12

return eggs

print spam()

10 Python是一种解释执行的语言,只要你写完即可立即运行

2 练习:设置变量spam的只为True,eggs的值为False

[python]

spam = True

eggs = False

11 Python的注释是通过“#”来实现的,并不影响代码的实现

2 练习:给下面的代码加上一行注释

[python]

#this is a comments for Python

mysterious_variable = 42

12 Python的多行注释是通过“ """ """ ”来实现的

2 练习:把下面的代码加上多行

[python]

"""

this is a Python course

"""

a = 5

3

13 Python有6种算术运算符+,-,*,/,**(幂),%

2 练习:把变量count_to设置为1+2

[python]

#Set count_to equal to 1 plus 2 on line 3!

count_to = 1+2

print count_to

14 Python里面求x^m,写成x**m

2 练习:利用幂运算,把eggs的值设置为100

[python]

#Set eggs equal to 100 using exponentiation on line 3!

eggs = 10**2

print eggs

1 练习:

1 写一行注释

2 把变量monty设置为True

3 把变量python值设置为1.234

4 把monty_python的值设置为python的平方

[python]

#this is a Python

monty = True

python = 1.234

monty_python = python**2

4

Python 入门教程 2 ---- Tip Calculator

1 把变量meal的值设置为44.50

[python]

#Assign the variable meal the value 44.50 on line 3!

meal = 44.50

1 把变量tax的值设置为6.75%

[python]

meal = 44.50

tax = 6.75/100

1 设置tip的值为15%

[python]

#You're almost there! Assign the tip variable on line 5.

meal = 44.50

tax = 0.0675

tip = 0.15

1 把变量meal的值设置为meal+meal*tax

[python]

#Reassign meal on line 7!

meal = 44.50

tax = 0.0675

tip = 0.15

meal = meal+meal*tax

设置变量total的值为meal+meal*tax

[python]

#Assign the variable total on line 8!

meal = 44.50

5

tax = 0.0675

tip = 0.15

meal = meal + meal * tax

total = meal + meal * tip

print("%.2f" % total)

Python 入门教程 3 ---- Strings and Console

Output

15 Python里面还有一种好的数据类型是String

16一个String是通过'' 或者 ""包成的串

3 设置变量brian值为"Always look on the bright side of life!"

[python]

#Set the variable brian on line 3!

brian = "Always look on the bright side of life!"

1 练习

1 把变量caesar变量设置为Graham

2 把变量praline变量设置为john

3 把变量viking变量设置为Teresa

[python]

#Assign your variables below, each on its own line!

caesar = "Graham"

praline = "John"

viking = "Teresa"

#Put your variables above this line

print caesar

print praline

print viking

6

17 Python是通过来实现转义字符的

2 练习把'Help! Help! I'm being repressed!' 中的I'm中的'进行转义

[python]

#The string below is broken. Fix it using the escape backslash!

'Help! Help! 'm being repressed!'

18 我们可以使用""来避免转义字符的出现

2 练习: 把变量fifth_letter设置为MONTY的第五个字符

[python]

"""

The string "PYTHON" has six characters,

numbered 0 to 5, as shown below:

+---+---+---+---+---+---+

| P | Y | T | H | O | N |

+---+---+---+---+---+---+

0 1 2 3 4 5

So if you wanted "Y", you could just type

"PYTHON"[1] (always start counting from 0!)

"""

fifth_letter = "MONTY"[4]

print fifth_letter

19 介绍String的第一种方法,len()求字符串的长度

2 练习: 把变量parrot的值设置为"Norweigian Blue",然后打印parrot的长度

[python]

parrot = "Norwegian Blue"

7

print len(parrot)

20 介绍String的第二种方法,lower()把所有的大写字母转化为小写字母

2 练习: 把parrot中的大写字母转换为小写字母并打印

[python]

parrot = "Norwegian Blue"

print ()

21 介绍String的第三种方法,upper()把所有的大写字母转化为小写字母

2 练习: 把parrot中的小写字母转换为大写字母并打印

[python]

parrot = "norwegian blue"

print ()

第八节

1 介绍String的第四种方法,str()把非字符串转化为字符串,比如str(2)是把2转化为字符串"2"

2 练习: 设置一个变量pi值为3.14 , 把pi转化为字符串

[python]

"""Declare and assign your variable on line 4,

then call your method on line 5!"""

pi = 3.14

print str(pi)

8

22 主要介绍“.” 的用处,比如上面的四个String的四个方法都是用到了点

2 练习: 利用“.”来使用String的变量ministry的函数len()和upper(),并打印出

[python]

ministry = "The Ministry of Silly Walks"

print len(ministry)

print ()

23 介绍print的作用

2 练习:利用print输出字符串"Monty Python"

[python]

"""Tell Python to print "Monty Python"

to the console on line 4!"""

print "Monty Python"

1 介绍print来打印出一个变量

2 练习:把变量the_machine_goes值赋值"Ping!",然后打印出

[python]

"""Assign the string "Ping!" to

the variable the_machine_goes on

line 5, then print it out on line 6!"""

the_machine_goes = "Ping!"

print the_machine_goes

24 介绍我们可以使用+来连接两个String

2 练习:利用+把三个字符串"Spam "和"and "和"eggs"连接起来输出

9

[python]

# Print the concatenation of "Spam and eggs" on line 3!

print "Spam " + "and " + "eggs"

25 介绍了str()的作用是把一个数字转化为字符串

2 练习:利用str()函数把3.14转化为字符串并输出

[python]

# Turn 3.14 into a string on line 3!

print "The value of pi is around " + str(3.14)

第十四节

1 介绍了字符串的格式化,使用%来格式化,字符串是%s

2 举例:有两个字符串,利用格式化%s来输出

[python]

string_1 = "Camelot"

string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

1 回顾之前的内容

2 练习

1 设置变量my_string的值

2 打印出变量的长度

3 利用upper()函数并且打印变量值

[python]

# Write your code below, starting on line 3!

my_string = "chenguolin"

10

print len(my_string)

print my_()

Python 入门教程 4 ---- Date and Time

26 介绍得到当前的时间()

2 练习

1 设置变量now的值为()

2 打印now的值

[python]

from datetime import datetime

now = ()

print now

27 介绍从得到的信息中提取出year,month等

2 练习: 从中得到的信息中提取出year,month,day

[python]

from datetime import datetime

now = ()

print

print

print

28 介绍把输出日期的格式转化为mm//dd//yyyy,我们利用的是+来转化

2 练习:打印当前的日期的格式为mm//dd//yyyy

[python]

11

from datetime import datetime

now = ()

print str()+"/"+str()+"/"+str()

29 介绍把输出的时间格式化为hh:mm:ss

2 练习:打印当前的时间的格式为hh:mm:ss

[python]

from datetime import datetime

now = ()

print str()+":"+str()+":"+str()

第五节

1 练习:把日期和时间两个连接起来输出

[python]

from datetime import datetime

now = ()

print str() + "/" + str() + "/" + str() + " "

+str() + ":" + str() + ":" + str()

Python 入门教程 5 ---- Conditionals

Control Flow

&

12

30 介绍Python利用有6种比较的方式 == , != , > , >= , < , <=

2 比较后的结果是True或者是False

3 练习

1 把bool_one的值设置为 17 < 118%100

2 把bool_two的值设置为 100 == 33*3 + 1

3 把bool_two的值设置为 19 <= 2**4

4 把bool_four的值设置为 -22 >= -18

5 把bool_five的值设置为 99 != 98+1

[python]

#Assign True or False as appropriate on the lines below!

bool_one = 17 < 118%100

bool_two = 100 == 33*3+1

bool_three = 19 <= 2**4

bool_four = -22 >= -18

bool_five = 99 != 98+1

31 介绍了比较的两边不只是数值,也可以是两个表达式

2 练习

1 把bool_one的值设置为 20 + -10*2 > 10%3%2

2 把bool_two的值设置为 (10+17)**2 == 3**6

3 把bool_two的值设置为 1**2**3 <= -(-(-1))

4 把bool_four的值设置为 40/20*4 >= -4**2

5 把bool_five的值设置为 100**0.5 != 6+4

[python]

# Assign True or False as appropriate on the lines below!

bool_one = 20+-10*2 > 10%3%2

bool_two = (10+17)**2 == 3**6

bool_three = 1**2**3 <= -(-(-1))

bool_four = 40/20*4 >= -4**2

bool_five = 100**0.5 != 6+4

13

32 介绍了Python里面还有一种数据类型是booleans,值为True或者是False

2 练习:根据题目的意思来设置右边的表达式

[python]

# Create comparative statements as appropriate on the lines below!

# Make me true!

bool_one = 1 <= 2

# Make me false!

bool_two = 1 > 2

# Make me true!

bool_three = 1 != 2

# Make me false!

bool_four = 2 > 2

# Make me true!

bool_five = 4 < 5

33 介绍了第一种连接符and的使用,只有and的两边都是True那么结果才能为True

2 练习

1 设置变量bool_one的值为False and False

2 设置变量bool_two的值为-(-(-(-2))) == -2 and 4 >= 16**0.5

3 设置变量bool_three的值为19%4 != 300/10/10 and False

4 设置变量bool_four的值为-(1**2) < 2**0 and 10%10 <= 20-10*2

5 设置变量bool_five的值为True and True

[python]

bool_one = False and False

14

bool_two = -(-(-(-2))) == -2 and 4 >= 16**0.5

bool_three = 19%4 != 300/10/10 and False

bool_four = -(1**2) < 2**0 and 10%10 <= 20-10*2

bool_five = True and True

34 介绍了第二种连接符or的使用,只要or的两边有一个True那么结果才能为True

2 练习

1 设置变量bool_one的值为2**3 == 108%100 or 'Cleese' == 'King Arthur'

2 设置变量bool_two的值为True or False

3 设置变量bool_three的值为100**0.5 >= 50 or False

4 设置变量bool_four的值为True or True

5 设置变量bool_five的值为1**100 == 100**1 or 3*2*1 != 3+2+1

[python]

bool_one = 2**3 == 108%100 or 'Cleese' == 'King Arthur'

bool_two = True or False

bool_three = 100**0.5 >= 50 or False

bool_four = True or True

bool_five = 1**100 == 100**1 or 3*2*1 != 3+2+1

35 介绍第三种连接符not , 如果是not True那么结果为False,not False结果为True

2 练习

1 设置变量bool_one的值为not True

15

2 设置变量bool_two的值为not 3**4 < 4**3

3 设置变量bool_three的值为not 10%3 <= 10%2

4 设置变量bool_four的值为not 3**2+4**2 != 5**2

5 设置变量bool_five的值为not not False

[python]

bool_one = not True

bool_two = not 3**4 < 4**3

bool_three = not 10%3 <= 10%2

bool_four = not 3**2+4**2 != 5**2

bool_five = not not False

36 介绍了由于表达式很多所以我们经常使用()来把一些表达式括起来,这样比较具有可读性

2 练习

1 设置变量bool_one的值为False or (not True) and True

2 设置变量bool_two的值为False and (not True) or True

3 设置变量bool_three的值为True and not (False or False)

4 设置变量bool_four的值为not (not True) or False and (not True)

5 设置变量bool_five的值为False or not (True and True)

[python]

bool_one = False or (not True) and True

bool_two = False and (not True) or True

bool_three = True and not (False or False)

bool_four = not (not True) or False and (not True)

16

bool_five = False or not (True and True)

第八节

1 练习:请至少使用and,or,not来完成以下的练习

[python]

# Use boolean expressions as appropriate on the lines below!

# Make me false!

bool_one = not ((1 and 2) or 3)

# Make me true!

bool_two = not (not((1 and 2) or 3))

# Make me false!

bool_three = not ((1 and 2) or 3)

# Make me true!

bool_four = not (not((1 and 2) or 3))

# Make me true!

bool_five = not (not((1 and 2) or 3)

37 介绍了条件语句if

38 if的格式如下, 比如

[python]

if 8 < 9:

print "Eight is less than nine!"

3 另外还有这elif 以及else,格式如下

[python]

17

if 8 < 9:

print "I get printed!"

elif 8 > 9:

print "I don't get printed."

else:

print "I also don't get printed!"

4 练习:设置变量response的值为'Y'

[python]

response = 'Y'

answer = "Left"

if answer == "Left":

print "This is the Verbal Abuse Room, you heap of parrot droppings!"

# Will the above print statement print to the console?

# Set response to 'Y' if you think so, and 'N' if you think not.

第十节

1 介绍了if的格式

[python]

if EXPRESSION:

# block line one

# block line two

# et cetera

2 练习:在两个函数里面加入两个加入条件语句,能够成功输出

[python]

def using_control_once():

if 1 > 0:

return "Success #1"

def using_control_again():

18

if 1 > 0:

return "Success #2"

print using_control_once()

print using_control_again()

39 介绍了else这个条件语句

2 练习:完成函数里面else条件语句

[python]

answer = "'Tis but a scratch!"

def black_knight():

if answer == "'Tis but a scratch!":

return True

else:

return False # Make sure this returns False

def french_soldier():

if answer == "Go away, or I shall taunt you a second time!":

return True

else:

return False # Make sure this returns False

40 介绍了另外一种条件语句elif的使用

2 练习:在函数里面第二行补上answer > 5, 第四行补上answer < 5 , 从而完成这个函数

[python]

def greater_less_equal_5(answer):

if answer > 5:

return 1

19

elif answer < 5:

return -1

else:

return 0

print greater_less_equal_5(4)

print greater_less_equal_5(5)

print greater_less_equal_5(6)

第十三节

1 练习:利用之前学的比较以及连接符以及条件语句补全函数。所有的都要出现至少一次

[python]

def the_flying_circus():

# Start coding here!

if 1 < 2 and not False:

return True

elif 1 == 1 or 1 != 2 or 1 < 2 or 1 <= 2 or 1 > 2 or 1 >= 2:

return True

else:

return False

Python 入门教程 6 ---- PygLatin

1 练习:使用Python来输出这句话"Welcome to the English to Pig Latin translator!"

[python]

print "Welcome to the English to Pig Latin translator!"

20

41 介绍了Python的输入,Python里面我们可以通过raw_input来实现出入

2 比如我们使用name = raw_ijnput("what's your name") , 那么这里将会在what's your name提示我们输入,并把结果保存到name里面

3 练习:使用original变量来接受任何的输入

[python]

print "Welcome to the English to Pig Latin translator!"

original = raw_input("welcome to the Python:")

42 介绍了我们在输入的时候经常出现输入空字符串的情况,因此我们需要去检查是否是空字符串

2 练习:在上一节的输入的值进行判断,如果不是空字符串那么打印这个值,否则直接输出"empty"

[python]

print "Welcome to the English to Pig Latin translator!"

original = raw_input("welcome to the Python:")

if len(original) > 0:

print original

else:

print "empty"

43 介绍了怎样判断一个字符串是数字的方法,我们可以通过isalpha()来判断

如果是阿拉伯数字,则isalpha的值为false ,否则为TRUE

2 比如有一个变量为x = "123",那么a()是True

3 练习:通过变量original的输入值来判断是否是一个数字串

[python]

print "Welcome to the English to Pig Latin translator!"

original = raw_input("welcome to the Python:")

if a():

21

print "True"

else:

print "False"

第五节

1 练习:利用多次的输入来判断是否是数字串和非空字符串

[python]

print "Welcome to the English to Pig Latin translator!"

original = raw_input("welcome to the Python:")

if a():

print "True"

else:

print "False"

original = raw_input("welcome to the Python:")

if len(y) == 0:

print "empty"

else:

print "no empty"

第六节

1 回顾了一下之前的String的lower()函数

2 练习

1 设置变量word等于()

2 设置变量first等于word的第一个字符

[python]

pyg = 'ay'

original = raw_input('Enter a word:')

word = ()

first = word[0]

if len(original) > 0 and a():

print original

else:

print 'empty'

22

第六节

1 介绍了if语句里面还可以嵌套语句

2 练习:判断上一节里面的first字符是否是元音字符是的话输出"vowel",否则输出"consonant"

[python]

pyg = 'ay'

original = raw_input('Enter a word:')

word = ()

first = word[0]

if len(original) > 0 and a():

if first == 'a' or first == 'i' or first == 'o' or first == 'u' or first ==

'e':

print "vowel"

else:

print "consonant"

else:

print 'empty'

第七节

1 利用String的+操作,产生一个新的变量new_word等于word+pyg

2 练习:把print "vowel"替换成print new_word

[python]

pyg = 'ay'

original = raw_input('Enter a word:')

word = ()

first = word[0]

new_word = word+pyg

if len(original) > 0 and a():

if first == 'a' or first == 'i' or first == 'o' or first == 'u' or first ==

'e':

print new_word

23

else:

print "consonant"

else:

print 'empty'

44 介绍了String中得到子串的方法,比如我们有一个字符串s = "foo",现在s[0:2]就是"fo"

45 如果结束是末尾,那么可以直接写成这样s[i:],省略第二个数

2 练习:在嵌套的if语句里面设置new_word的值为word从第1位到最后一位+变量pyg

[python]

pyg = 'ay'

original = raw_input('Enter a word:')

word = ()

first = word[0]

new_word = word+pyg

if len(original) > 0 and a():

if first == 'a' or first == 'i' or first == 'o' or first == 'u' or first ==

'e':

new_word = word[1:]+pyg

print new_word

else:

print "consonant"

else:

print 'empty'

24

Python 入门教程 7 ---- PygLatin

46 介绍了Python的函数组成有三部份,函数头,函数体

2 函数的举例

[python]

def ni_sayer():

"""Prints 'Ni!' to the console."""

print "Ni!"

3 练习:写一个函数,输出字符串"Eggs!",函数体增加一行注释[python]

# Define your spam function starting on line 5. You

# can leave the code on line 11 alone for now--we'll

# explain it soon!

def spam():

"""this is a zhushi"""

print "Eggs!"

# Define the spam function above this line.

spam()

47 介绍了函数的调用,就是直接函数名

2 练习:调用函数spam(10)

[python]

def square(n):

"""Returns the square of a number."""

squared = n**2

print "%d squared is %d." % (n, squared)

return squared

25

# Call the square function on line 9! Make sure to

# include the number 10 between the parentheses.

square(10)

48 介绍了函数可以使用参数的传递

2 比如函数no_one(sentence)的使用,传入字符串作为参数

[python]

def no_one(sentence):

print sentence

no_one("The Spanish Inquisition")

3 练习:把函数的参数改为base,exponent。调用函数传入37和4

[python] view plaincopy

def power(base,exponent): # Add your parameters here!

result = base**exponent

print "%d to the power of %d is %d." % (base, exponent, result)

power(37,4) # Add your arguments here!

49 介绍了*的用法,比如我们传入一个字符串,那么我们可以使用*name接收,然后可以利用name来输出。不一定使用name,可以是任何的名字

2 练习

[python]

def favorite_actors(*name):

"""Prints out your favorite actorS (plural!)"""

print "Your favorite actors are:" , name

favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")

26

50 介绍了函数体里面还可以调用另外的函数

2 比如我们在第二个函数里面调用了第一个函数

[python]

def fun_one(n):

return n * 5

def fun_two(m):

return fun_one(m) + 7

3 练习:把第二个函数调用第一个函数并输出

[python]

def one_good_turn(n):

return n + 1

def deserves_another(n):

return n + one_good_turn(2)

第六节

1 练习

1 定义第一个函数cube(),有一个参数num,返回num的3次方

2 定义另外一个函数by_three(),有一个参数num,如果num能够被3整除那么调用cube并返回值,否则返回False

3 调用函数by_three(9) 和 by_three(4)

[python]

def cube(num):

return num**3

def by_three(num):

if(num%3 == 0):

return cube(num)

else:

27

return False

by_three(9)

by_three(4)

51 介绍了Python里面可以导入很多的系统的模块,就像c语言的include

2 假设我们没有导入math模块的时候,那么执行print sqrt(25)的时候会报错

3 练习

1 导入math模块,import math

2 执行print (25),加了一个math说明调用系统的库函数

[python]

# Ask Python to print sqrt(25) on line 3.

import math

print (25)

52 Import 我们还可以只是单独的导入模块里面的方法

2 比如from moduleimport

function

3 练习:从math模块里面值导入sqrt函数

[python]

# Import *just* the sqrt function from math on line 3!

from math import sqrt

print sqrt(25)

53 Import 使用from module import *来表示从模块里面导入所有的函数,这样调用的时候就直接调用即可

2 练习:从math模块里面导入所有的方法,然后随便选择一个函数来测试

[python]

28

# Import *everything* from the math module on line 3!

from math import *

print sqrt(25)

54 Import from module import *方法的缺点就是,如果我们导入了很多的模块,那么可能导致出现相同的函数名,因此我们最好是使用import module,然后使用

2 测试以下代码的结果

[python]

import math # Imports the math module

everything = dir(math) # Sets everything to a list of things from math

print everything # Prints 'em all!

第十一节

1 介绍了第一个函数max(),比如max(1,2,3)返回的是3 (min函数是类似的)

2 max()函数的参数是一个数组,返回数组中的最大值

3 练习:使用max函数来得到一个数组的最大值

[python]

# Set maximum to the max value of any set of numbers on line 3!

maximum = max(4,0,-3,78)

print maximum

55 介绍了第二个函数abs()返回的值永远是正数,比如abs(-5)返回的是5

2 练习:测试输出abs(-42)的值

[python]

absolute = abs(-42)

print absolute

29

56 介绍了type函数的使用,type函数返回的是当前这种数据的类型,比如int , float等

2 type函数的使用举例

[python]

print type(42)

print type(4.2)

print type('spam')

print type({'Name':'John Cleese'})

print type((1,2))

3 练习:使用type函数至少得到int,float,unicode三种类型

[python]

# Print out the types of an integer, a float,

# and a string on separate lines below.

print type(4)

print type(4.2)

print type('spam')

Python 入门教程 8 ---- Python Lists

Dictionaries

and

30

57 介绍了Python的列表list

2 列表的格式list_name = [item1 , item2],Python的列表和C语言的数组很像

3 列表可以为空,就是empty_list = [],比如数组为空

4 举例

[python]

zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];

# One animal is missing!

if len(zoo_animals) > 3:

print "The first animal at the zoo is the " + zoo_animals[0]

print "The second animal at the zoo is the " + zoo_animals[1]

print "The third animal at the zoo is the " + zoo_animals[2]

print "The fourth animal at the zoo is the " + zoo_animals[3]

58 介绍了我们可以使用下标来访问list的元素,就像数组一样

2 下标从0开始,比如list_name[0]是第一个元素

3 练习:输出列表numbers的第二个和第四个数的和

[python]

numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 "

print numbers[0] + numbers[2]

print "Adding the numbers at indices 1 "

# Your code here!

print numbers[1] + numbers[3]

59 介绍了我们可以使用下标来对第几个元素进行赋值

2 比如lisy_name[2] = 2,就是把列表的第三个值赋值为2

3 练习:把列表zoo_animals中的tiger换成其它的动物

31

[python]

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]

# Last night our zoo's sloth brutally attacked

#the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.

zoo_animals[2] = "hyena"

# What shall fill the void left by our dear departed tiger?

# Your code here!

zoo_animals[3] = "dog"

60 介绍了list中添加一个item的方法append()

2 比list_(item),求列表list_name中有几项就是利用len(list_name)

3 练习:在列表suitcase在增加三项,然后求出它的元素的个数

[python]

suitcase = []

("sunglasses")

# Your code here!

("a")

("b")

("c")

# Set this to the length of suitcase

list_length = len(suitcase)

print "There are %d items in the suitcase." % (list_length)

print suitcase

32

61 介绍了list列表怎样得到子列表list_name[a:b],将得到下标a开始到下标b之前的位置

2 比如列表my_list = [1,2,3,4],那么my_list[1:3]得到的将是[2,3]

[python]

my_list = [0, 1, 2, 3]

my_slice = my_list[1:3]

print my_list

# Prints [0, 1, 2, 3]

print my_slice

# Prints [1, 2]

3 如果我们默认第二个值,那么将会直接到末尾那个位置。如果默认第一个值,值是从头开始

[python]

my_list[:2]

# Grabs the first two items

my_list[3:]

# Grabs the fourth through last

4 练习:把first列表设置为suitcase的前两项,把middle列表设置为suitcase的中间两项,把last列表设置为suitcase的后两项

[python]

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# The first two items

first = suitcase[0:2]

# Third and fourth items

middle = suitcase[2:4]

# The last two items

last = suitcase[4:]

33

62 介绍了不仅列表可以得到子串,字符串也满足

2 比如string[a:b]是得到从下标a开始到b之前的子串

3 练习:把三个变量分别设置为对应的子串

[python]

animals = "catdogfrog"

# The first three characters of animals

cat = animals[:3]

# The fourth through sixth characters

dog = animals[3:6]

# From the seventh character to the end

frog = animals[6:]

63 介绍了列表的两种方法index(item)和insert(index , item)

2 index(item)方法是查找item在列表中的下标,使用方法list_(item)

3 insert(index,item)是在下标index处插入一个item,其余的后移,使用方法list_(index , item)

4 练习:使用index()函数找到列表中的"duck",然后在当前位置插入"cobra"

如果我们使用print list_name,就是直接输出列表的所有元素

[python]

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

# Use index() to find "duck"

duck_index = ("duck")

# Your code here!

(duck_index,"cobra")

# Observe what prints after the insert operation

print animals

34

64 介绍我们可以使用for循环来遍历列表的每一个元素

2 比如for variable in list_name:

statement

这样我们可以枚举列表的每一个元素

3 练习:打印列表的每一个元素的值*2

[python]

my_list = [1,9,3,8,5,7]

for number in my_list:

# Your code here

print 2*number

65 介绍了列表的另外一种方法sort(),可以对列表进行排序,默认是从小到打排序

2 使用的方法是list_()

3 列表中删除一个item的方法list_(item)

[python]

beatles = ["john","paul","george","ringo","stuart"]

("stuart")

print beatles

>> ["john","paul","george","ringo"]

4 练习:利用for循环把没一项的值的平方加入列表square_list,然后对square_list排序输出

[python]

start_list = [5, 3, 1, 2, 4]

square_list = []

# Your code here!

for numbers in start_list:

square_(numbers**2)

35

print square_()

66 介绍了Python中的字典,字典的每一个item是一个键值对即key:value

注意:字典是无序的,所以for I in dec:中 i指的是Key值,而dec[i]则是value值

2 比如字典d = {'key1' : 1, 'key2' : 2, 'key3' : 3},有三个元素

3 Python的字典和C++里面的map很像,我们可以使用d["key1"]来输出key1对应的value

4 练习:打印出'Sloth'和'Burmese Python'对应的value

注意在脚本语言里面可以使用单引号也可以使用双引号来表示字符串

[python]

# Assigning a dictionary with three key-value pairs to residents:

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

# Prints Puffin's room number

print residents['Puffin']

# Your code here!

print residents['Sloth']

print residents['Burmese Python']

67 字典和列表一样可以是空的,比如d = {}就是一个空的字典

68 字典里面添加一个键值对或者是改变已有key的value,使用这种方法 dict_name[key]

= value

69 我们也可以使用len(dict_name)求出字典的元素的个数

2 练习:至少添加3个键值对到字典menu中

[python]

# Empty dictionary

36

menu = {}

# Adding new key-value pair

menu['Chicken Alfredo'] = 14.50

print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!

menu["a"] = 1

menu["b"] = 2

menu["c"] = 3

# print you code

print "There are " + str(len(menu)) + " items on the menu."

print menu

70 介绍了我们可以删除字典中的键值对

2 我们使用del dict_name[key],这样将删除键值为key的键值对

3 练习:删除key为"Sloth"和"Bengal Tiger",并且设置key为"Rockhopper

Penguin"的val和之前的不一样

[python]

# key - animal_name : value - location

zoo_animals = { 'Unicorn' : 'Cotton Candy House',

'Sloth' : 'Rainforest Exhibit',

'Bengal Tiger' : 'Jungle House',

'Atlantic Puffin' : 'Arctic Exhibit',

'Rockhopper Penguin' : 'Arctic Exhibit'}

# A dictionary (or list) declaration may break across multiple lines

# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)

del zoo_animals['Unicorn']

37

# Your code here!

del zoo_animals["Sloth"]

del zoo_animals["Bengal Tiger"]

zoo_animals["Rockhopper Penguin"] = "aa"

# print you code

print zoo_animals

71 介绍了字典中一个key可以对应不止一个的value

2 比如my_dict = {"hello":["h","e","l","l","o"]},那么key为"hello"对应的value有5个,我们可以使用my_dict["hello"][index]来取得下标为index的value,比如index为1的时候是"e"

3 对于一个key对应多个value的话,我们应该要用list来保存这些value

4 对于一个key对应多个value的话,我们还可以对这个key的val进行排序,比如my_dict["hello"].sort()

4 练习

1 在字典inventory中添加一个key为'pocket',值设置为列表["seashell" ,

"strange berry" , "lint"]

2 对key为'pocket'的value进行排序

3 删除字典inventory中key为'backpack'的键值对

4 把字典inventory中key为'gold'的value加一个50

[python]

# Assigned a new list to 'pouch' key

inventory = {'gold' : 500,

'pouch' : ['flint', 'twine', 'gemstone'],

'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it

inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'

38

inventory['pouch'].sort()

# Here the dictionary access expression takes the place of a list name

# Your code here

inventory['pocket'] = ["seashell" , "strange berry" , "lint"]

inventory['pocket'].sort()

del inventory['backpack']

inventory['gold'] = [500 , 50]

外记1:sort()函数的深度使用

Python语言内置了sort方法,可以很方便地对某个List进行排序:

L = [6, 5, 1, 3, 4, 2]

()

print L

———- Run Python Program ———-

[1, 2, 3, 4, 5, 6]

某些时候,我们希望按照自己定义的排序规则来排序(例如,按关键词的权重排序,按人的年龄排序,等等)。在Java语言中,我们可以自定义Comparator来实现,Python中也提供了类似的办法。

若List中每个元素都是2-tuple,tuple中第一个元素为String类型的keyword,第二个元素为该字符串对应的权重(int类型),希望按照权重排序(从高到低),则可以这样:

def my_cmp(E1, E2):

return -cmp(E1[1], E2[1]) #compare weight of each 2-tuple

#return the negative result of built-in cmp function

#thus we get the descend order

L = [('a', 0), ('b', 1), ('c', 2), ('d', 3)]

(my_cmp)

print L

39

———- Run Python Program ———-

[('d', 3), ('c', 2), ('b', 1), ('a', 0)]

正因为可以自定义cmp方法,我们不妨探究一下,built-in的sort方法,到底是采用的哪一种排序算法:

from random import shuffle

def my_cmp(E1, E2):

print ‘E1:’, E1, ‘E2:’, E2

return cmp(E1, E2)

L = range(0, 10)

shuffle(L)

print L

(my_cmp)

———- Run Python Program ———-

[5, 3, 7, 6, 2, 8, 9, 4, 1, 0]

E1: 3 E2: 5

E1: 7 E2: 3

E1: 7 E2: 5

E1: 6 E2: 5

E1: 6 E2: 7

E1: 2 E2: 6

E1: 2 E2: 5

E1: 2 E2: 3

E1: 8 E2: 5

E1: 8 E2: 7

E1: 9 E2: 6

E1: 9 E2: 8

E1: 4 E2: 6

E1: 4 E2: 3

E1: 4 E2: 5

E1: 1 E2: 6

E1: 1 E2: 4

E1: 1 E2: 3

E1: 1 E2: 2

E1: 0 E2: 5

E1: 0 E2: 3

E1: 0 E2: 2

E1: 0 E2: 1

可以看到,每次调用my_cmp,E1依次是List中的第2、3、4……直到最后一个元素,可以肯定sort不是采用的分治法(devide-and-conqure)

看前三次调用,可以发现sort采用的是典型的插入排序——也就是说,将新元素插入已排序部40

分的合适位置,查找位置时采用的似乎是从后向前线形探察的办法。从元素6开始,新元素不再直接与已排序部分的最后元素比较,而是先与中间值比较,采用二分检索探察合适位置,这样,可以把时间代价从n缩小到log(n)。

至此,我们可以认为,built-in的sort方法,采用的是“二分法插入排序”(binary insertion)的算法。

为了检测这个结论,可以输入一个已排序的数组,看看结果。

L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(my_cmp)

———- Run Python Program ———-

E1: 1 E2: 0

E1: 2 E2: 1

E1: 3 E2: 2

E1: 4 E2: 3

E1: 5 E2: 4

E1: 6 E2: 5

E1: 7 E2: 6

E1: 8 E2: 7

E1: 9 E2: 8

E1: 10 E2: 9

结果发现,比较的次数非常少,插入每个元素的时候,只会与它之前紧邻的元素比较,而不是二分检索。这真是个有意思的现象。

改一改程序

L = [0, 1, 2, 3, 4, 5, 6, 8, 7, 9, 10]

(my_cmp)

———- Run Python Program ———-

E1: 1 E2: 0

E1: 2 E2: 1

E1: 3 E2: 2

E1: 4 E2: 3

E1: 5 E2: 4

E1: 6 E2: 5

E1: 8 E2: 6

E1: 7 E2: 8

E1: 7 E2: 4

E1: 7 E2: 6

E1: 7 E2: 8

E1: 9 E2: 4

E1: 9 E2: 7

E1: 9 E2: 8

E1: 10 E2: 5

41

E1: 10 E2: 8

E1: 10 E2: 9

可以看到,在数字8以前,List中的元素都是有序的,于是sort算法也只比较欲插入元素和已排序序列的最后一个元素;一旦发现输入序列不是自然有序之后,就采用二分插入排序算法。

这样的混合排序算法,相对单纯的插入排序,保证了最好条件下时间代价最低,也减小了一般情况下的时间代价。

p.s.

写完之后查阅Python的文档,发现sort采用的是混合(hybrid)排序,规模小的时候采用binary

insertion,规模大的时候采用samplesort(据说是quicksort的一个变种,我没接触过,汗….)

外记2:Python的url编码函数使用的一个小问题

python的url编码函数是在类urllib库中,使用方法是:

编码:(string[, safe]),除了三个符号“_.-”外,将所有符号编码,后面的参数safe是不编码的字符,使用的时候如果不设置的话,会将斜杠,冒号,等号,问号都给编码了。

print ("/?id=1")

print ("/?id=1",":?=/")

结果如下:

http%3A///%3Fid%3D1

/?id=1

外记3:python对文件进行读写操作

python进行文件读写的函数是open或file

file_handler = open(filename,,mode)

Table mode

42

模式

描述

r 以读方式打开文件,可读取文件信息。

w 以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容

a

以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建

r+ 以读写方式打开文件,可对文件进行读和写操作。

w+ 消除文件内容,然后以读写方式打开文件。

a+ 以读写方式打开文件,并把文件指针移到文件尾。

b

Table 文件对象方法

以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。

方法

()

()

()

()

([count])

ne()

nes()

描述

关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。

获得文件描述符,是一个数字

刷新输出缓存

如果文件是一个交互终端,则返回True,否则返回False。

读出文件,如果有count,则读出count个字节。

读出一行信息。

读出所有行,也就是读出整个文件的信息。

把文件指针移动到相对于where的offset位置。(offset[,where]) where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。

()

te([size])

(string)

ines(list)

获得文件指针位置。

截取文件,使文件的大小为size。

把string字符串写入文件。

把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

例子如下:

读文件

Python代码

43

1. read = open(result)

2. line=ne()

3. while line:

4. print line

5. line=ne()#如果没有这行会造成死循环

6.

写文件

Python代码

1. read = file(result,'a+')

2. ("rn")

3. ("thank you")

4.

其它

Python代码

1. #-*- encoding:UTF-8 -*-

2. filehandler = open('c:','r') #以读方式打开文件,rb为二进制方式(如图片或可执行文件等)

3.

4. print 'read() function:' #读取整个文件

5. print ()

6.

7. print 'readline() function:' #返回文件头,读取一行

8. (0)

9. print ne()

10.

11. print 'readlines() function:' #返回文件头,返回所有行的列表

12. (0)

13. print nes()

14.

15. print 'list all lines' #返回文件头,显示所有行

16. (0)

17. textlist = nes()

18. for line in textlist:

19. print line,

20. print

21. print

22.

23. print 'seek(15) function' #移位到第15个字符,从16个字符开始显示余下内容

24. (15)

25. print 'tell() function'

26. print () #显示当前位置

44

27. print ()

28.

29. () #关闭文件句柄

6

外记4:python数组的使用

python数组的使用

2010-07-28 17:17

1、Python的数组分三种类型:

(1) list 普通的链表,初始化后可以通过特定方法动态增加元素。

定义方式:arr = [元素]

(2) Tuple 固定的数组,一旦定义后,其元素个数是不能再改变的。

定义方式:arr = (元素)

(2) Dictionary 词典类型, 即是Hash数组。

定义方式:arr = {元素k:v}

2、下面具体说明这些数组的使用方法和技巧:

(1) list 链表数组

a、定义时初始化

a = [1,2,[1,2,3]]

b、定义时不初始化

一维数组:

arr = []

多维数组:

arr = [i for i in range(10), 1,[]] #注意, i for in xx 这个必须放在第一个位置,否则要先定义i,

如:

arr = [i for i in range(5), j for j in range(5), []]

这是错误的

i = 0

j = 0

arr = [i for i in range(5), j for j in range(5), []]

45

这是正确的

c、del 语句 和 : 的用法

可以用 start : end 表示数组里的一个区间 ( i >= start and i < end)

del 删除数组里的指定元素

如: del arr[0]

del arr[0, 2]

newarr = arr[0, 2]

d、遍历数组:

for k, v in enumerate(arr):

print k, v

e、增加元素:

一维

('aaa')

二维

arr[0].append('aaa')

如果要在任意位置插入用 (n, 值)

此外还有一种特殊的用法是:

arr += [数组元素]

在不指定下标的情况下,是允许用 += 增加数组元素的。

(2) Tuple 固定数组

Tuple 是不可变 list,一旦创建了一个 tuple 就不能以任何方式改变它。

下面拿具体示例说明:

>>> t = ("a", "b", "c", "d", "e") #[1] 用小括号包围来定义

>>> t

('a', 'b', 'c', 'd', 'e')

>>> t[0] #[2] 直接列出某下标的元素

'a'

>>> t[-1] #[3] 负数表示,从后面倒数的索引 -1 为倒数第一个, 0是顺数第一个

'example'

>>> t[1:3] #[4] 这里 1:3 是 i>=1 and i<3 的区间

('b', 'mpilgrim')

Tuple 没有的方法:

[1] 不能向 tuple 增加元素,没有 append 、 extend 、insert 等方法。

[2] 不能从 tuple 删除元素,没有 remove 或 pop 方法。

[3] 不能在 tuple 中查找元素,没有 index 方法(index是查找而不是索引,索引直接用下标即可,如:t[0])。

使用 tuple 的好处:

46

* Tuple 比 list 操作速度快。如果您定义了一个值的常量集, 并且唯一要用它做的是不断地遍历它, 请使用 tuple 代替 list。

* 如果对不需要修改的数据进行 “写保护”, 可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句, 说明这一数据是常量。如果必须要改变这些值, 则需要执行

tuple 到 list 的转换 (需要使用一个特殊的函数)。

* 还记得我说过 dictionary keys 可以是字符串, 整数和 “其它几种类型”吗? Tuples 就是这些类型之一。 Tuples 可以在 dictionary 中被用做 key, 但是 list 不行。实际上, 事情要比这更复杂。Dictionary key 必须是不可变的。Tuple 本身是不可改变的, 但是如果您有一个

list 的 tuple, 那就认为是可变的了, 用做 dictionary key 就是不安全的。只有字符串, 整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key。

Tuple 可以转换成 list, 反之亦然。

转换方式为:

t = list( t )

反之:

arr = tuple( arr )

(2) Dictionary (哈希数组)词典数组

#Dictionary 的用法比较简单,它可以存储任意值,并允许是不同类型的值,下面实例来说明:

#下面例子中 a 是整数, b 是字符串, c 是数组,这个例子充分说明哈希数组的适用性。

dict_arr = {'a': 100, 'b':'boy', 'c':['o', 'p', 'q']}

#可以直接增加一个元素,如果同名,则会改变原来的key的元素的值

dict_arr['d'] = 'dog'

#输出所有的key

print dict_()

#输出所有的value

print dict_()

#遍历数组

import types

for k in dict_arr:

v = dict_(k)

if type(v) is pe: #如果数据是list类型,继续遍历

print k, '---'

for kk, vv in enumerate(v):

print kk, vv

print '---'

else:

print dict_(k)

list的方法

47

(var) #追加元素

(index,var)

(var) #返回最后一个元素,并从list中删除之

(var) #删除第一次出现的该元素

(var) #该元素在列表中出现的个数

(var) #该元素的位置,无则抛异常

(list) #追加list,即合并list到L上

() #排序

e() #倒序

list 操作符:,+,*,关键字del

a[1:] #片段操作符,用于子list的提取

[1,2]+[3,4] #为[1,2,3,4]。同extend()

[2]*4 #为[2,2,2,2]

del L[1] #删除指定下标的元素

del L[1:3] #删除指定下标范围的元素

list的复制

L1 = L #L1为L的别名,用C来说就是指针地址相同,对L1操作即对L操作。函数参数就是这样传递的

L1 = L[:] #L1为L的克隆,即另一个拷贝。

list comprehension

[ for k in L if ]

2、dictionary: 字典(即C++标准库的map)

dict = {‘ob1′:’computer’, ‘ob2′:’mouse’, ‘ob3′:’printer’}

每一个元素是pair,包含key、value两部分。key是Integer或string类型,value 是任意类型。

键是唯一的,字典只认最后一个赋的键值。

dictionary的方法

(key, 0) #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常

_key(key) #有该键返回TRUE,否则FALSE

() #返回字典键的列表

()

()

(dict2) #增加合并字典

m() #得到一个pair,并从字典中删除它。已空则抛异常

() #清空字典,同del dict

() #拷贝字典

(dict1,dict2) #比较字典,(优先级为元素个数、键大小、键值大小)

#第一个大返回1,小返回-1,一样返回0

dictionary的复制

48

dict1 = dict #别名

dict2=() #克隆,即另一个拷贝。

3、tuple:元组(即常量数组)

tuple = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)

可以用list的 [],:操作符提取元素。就是不能直接修改元素。

4、string: 字符串(即不能修改的字符list)

str = “Hello My friend”

字符串是一个整 体。如果你想直接修改字符串的某一部分,是不可能的。但我们能够读出字符串的某一部分。

子字符串的提取

str[:6]

字符串包含 判断操作符:in,not in

“He” in str

“she” not in str

string模块,还提供了很多方法,如

(substring, [start [,end]]) #可指范围查找子串,返回索引值,否则返回-1

(substring,[start [,end]]) #反向查找

(substring,[start [,end]]) #同find,只是找不到产生ValueError异常

(substring,[start [,end]])#同上反向查找

(substring,[start [,end]]) #返回找到子串的个数

ase()

lize() #首字母大写

() #转小写

() #转大写

se() #大小写互换

(str, ‘ ‘) #将string转list,以空格切分

(list, ‘ ‘) #将list转string,以空格连接

处理字符串的内置函数

len(str) #串长度

cmp(“my friend”, str) #字符串比较。第一个大,返回1

max(‘abcxyz’) #寻找字符串中最大的字符

min(‘abcxyz’) #寻找字符串中最小的字符

string的转换

oat(str) #变成浮点数,float(“1e-1″) 结果为0.1

int(str) #变成整型, int(“12″) 结果为12

int(str,base) #变成base进制整型数,int(“11″,2) 结果为2

49

Python入门教程

本文发布于:2024-01-26 04:34:46,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/1706214886743.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:文件   函数   使用   元素   字符串   变量   练习
留言与评论(共有 0 条评论)
   
验证码:
排行榜

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23