小白的第一本python书_学习《编程小白的第一本python入门书》

---恢复内容开始---

open打开一个txt文件,如果不存在则创建

ContractedBlock.gif

ExpandedBlockStart.gif

1 file=open('/Users/Administrator/Desktop/file.txt','w')2 file.write('hellp world!')

View Code

字符串相连

ContractedBlock.gif

ExpandedBlockStart.gif

1 what_he_does="plays"

2 his_instrument = 'guitar'

3 his_name='Robert Johnson'

4 artist_intro=his_name+what_he_does+his_instrument5 print(artist_intro)

View Code

#Robert Johnson plays guitar

字符串重复

ContractedBlock.gif

ExpandedBlockStart.gif

1 word = 'a looooong word'

2 num = 12

3 string = 'bang!'

4 total = string * (len(word)-num)5 print(total)6 #bang!bang!bang!

View Code

字符串分片索引

ContractedBlock.gif

ExpandedBlockStart.gif

1 word = 'friend'

2 find_the_evil_in_your_friends = word[0] + word[2:4] + word[-3:-1]3 print(find_the_evil_in_your_friends)4 #fieen

View Code

字符串替换replace()

ContractedBlock.gif

ExpandedBlockStart.gif

1 phone_number = '1386-444-0044'

2 hiding_number = phone_number.replace(phone_number[:9],'*'*9)3 print(hiding_number)4 #*********0044

View Code

字符串位置查找.find()

ContractedBlock.gif

ExpandedBlockStart.gif

1 search = '168'

2 num_a = '1386-168-0006'

3 num_b = '1681-222-0006'

4 print(search + 'is at' + str(num_a.find(search)) + 'to' + str(num_a.find(search) + len(search)) + 'of num_a')5 print(search + 'is at' + str(num_b.find(search)) + 'to' + str(num_b.find(search) + len(search)) + 'of num_b')6 """

7 168 is at 5 to 8 of num_a8 168 is at 0 to 3 of num_b9 """

View Code

字符串格式化{} .format()

ContractedBlock.gif

ExpandedBlockStart.gif

1 print('{} a word con get what she {} for .' .format('With','came'))2 print('{prepositon} a word she can get what she {verb} for'.format(prepositon = 'With',verb = 'came'))3 print('{0} a word she can get what she {1} for.' .format('with','came'))4 """

5 With a word con get what she came for .6 With a word she can get what she came for7 with a word she can get what she came for.8 """

View Code

创建一个温度转换函数F=9/5*C+32

ContractedBlock.gif

ExpandedBlockStart.gif

1 deffahrenheit_converter(C):2 fahrenheit = C * 9/5 + 32

3 return str(fahrenheit) + 'F'

4 C2F = fahrenheit_converter(35)5 print(C2F)6 #95.0F

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 c_d = input("请输入C温度值:")2 f_d = (9 * int(c_d))/5 + 32

3 print(f_d)4 """

5 请输入C温度值:06 32.07 """

View Code

文件写入

ContractedBlock.gif

ExpandedBlockStart.gif

1 deftext_create(name,msg):2 desktop_path = 'C:/Users/Administrator/Desktop/'

3 full_path = desktop_path + name + '.txt'

4 file = open(full_path,'w')5 file.write(msg)6 file.close()7 print('Done')8 text_create('hip','我是你爸爸')

View Code

文件内容过滤、替换

ContractedBlock.gif

ExpandedBlockStart.gif

1 def text_filter(word,censored_word = 'lame',changed_word = '*'*3):2 returnword.replace(censored_word,changed_word)3 text_filter('Python is lame!')4 #'Python is ***!'

View Code

条件控制if-else 设置用户密码

ContractedBlock.gif

ExpandedBlockStart.gif

1 defaccount_login():2 password = input('Password:')3 if password == '12345':4 print('Login success!')5 else:6 print('Wrong password or invalid input!')7 account_login()8 account_login()9 """

10 Wrong password or invalid input!11 Password:1245612 Wrong password or invalid input!13 Password:1234514 Login success!15 """

View Code

加入bool类型

ContractedBlock.gif

ExpandedBlockStart.gif

1 defaccount_login():2 password = input('Password:')3 password_correct = password == '12345'

4 ifpassword_correct:5 print('Login success!')6 else:7 print('Wrong password or invalid input!')8 account_login()9 account_login()

View Code

条件控制if-elif-else 重置密码

ContractedBlock.gif

ExpandedBlockStart.gif

1 password_list = ['*#*#','12345']2 defaccount_login():3 password = input('Password:')4 password_correct = password == password_list[-1]5 password_reset = password ==password_list[0]6 ifpassword_correct:7 print('Login success!')8 elifpassword_reset:9 new_password = input('Enter a new password:')10 password_list.append(new_password)11 print('Your password has changed successfully')12 account_login()13 else:14 print('Wrong password or invalid input!')15 account_login()16 account_login()17 """

18 Password:12319 Wrong password or invalid input!20 Password:*#*#21 Enter a new password:12322 Your password has changed successfully23 Password:12324 Login success!25 """

View Code

for循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 for every_letter in 'Hello world':2 print(every_letter)3

4 for num in range(1,11):5 print('1 +' + str(num) + '=' + str(num+1))

View Code

for循环和if结合起来

ContractedBlock.gif

ExpandedBlockStart.gif

1 songslist = ['Holy Diver','Thunderstruck','Rebel Rebel']2 for song insongslist:3 if song == 'Holy Diver':4 print(song,'- Dio')5 elif song == 'Thunderstruck':6 print(song,'- AC/DC')7 elif song == 'Rebel Rebel':8 print(song,'- David Bowie')9 """

10 Holy Diver - Dio11 Thunderstruck - AC/DC12 Rebel Rebel - David Bowie13 """

View Code

嵌套for循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 for i in range(1,10):2 for j in range(1,10):3 print('{} X {} = {}' .format(i,j,i*j))

View Code

while循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 count =02 whileTrue:3 print('Repeat this line!')4 count = count + 1

5 if count == 5:6 break

View Code

while和if结合  密码输入三次错误禁止输入

ContractedBlock.gif

ExpandedBlockStart.gif

1 password_list = ['*#*#','12345']2 defaccount_login():3 tries=3

4 while tries >0:5 password = input('Password:')6 password_correct = password == password_list[-1]7 password_reset = password ==password_list[0]8

9 ifpassword_correct:10 print('Login success!')11 break

12 elifpassword_reset:13 new_password = input('Enter a new password:')14 password_list.append(new_password)15 print('Password has changed successfully!')16 account_login()17 else:18 print('Wrong password or invalis input!')19 tries = tries - 1

20 print(tries,'times left')21 else:22 print('Your account has been suspended!')23

24 account_login()

View Code

在桌面文件夹下创建10个文本,并以数字命名

摇骰子:摇三次,让用户输入猜大小:

ContractedBlock.gif

ExpandedBlockStart.gif

1 importrandom2

3

4 def roll_dice(numbers=3, points=None):5 print('<<<<<>>>>')6 if points isNone:7 points =[]8 while numbers >0:9 point = random.randrange(1, 7)10 points.append(point)11 numbers = numbers - 1

12 print(points)13 returnpoints14

15

16 defroll_result(total):17 isBig = 11 <= total <= 18

18 isSmall = 3 <= total <= 10

19 ifisBig:20 return 'big'

21 elifisSmall:22 return 'small'

23

24

25 defstart_game():26 print('<<<<<>>>>')27 choices = ['big', 'small']28

29 your_choice = input('you guess big or samll:')30 if your_choice inchoices:31 points =roll_dice()32 total =sum(points)33 you_win = your_choice ==roll_result(total)34 ifyou_win:35 print('the points are', points, 'you win')36 else:37 print('the points are', points, 'you lose')38 start_game()39 else:40 print('Invalid words')41 start_game()

View Code

在上一个项目基础上增加下注金额和赔率,初始金额为1000元,金额为0,赔率为1倍

ContractedBlock.gif

ExpandedBlockStart.gif

1 importrandom2

3

4 def roll_dice(numbers=3, points=None):5 print('<<<<<>>>>')6 if points isNone:7 points =[]8 while numbers >0:9 point = random.randrange(1, 7)10 points.append(point)11 numbers = numbers - 1

12 returnpoints13

14

15 defroll_result(total):16 isBig = 11 <= total <= 18

17 isSmall = 3 <= total <= 10

18 ifisBig:19 return 'big'

20 elifisSmall:21 return 'small'

22

23

24 def gamble(n=1000, you_win=True):25 wager = input('please take your wager<=1000:')26 while n >0:27 ifyou_win:28 gamble_sum = n + int(wager) * 2

29 print(gamble_sum)30 else:31 gamble_sum = n - int(wager) * 2

32 print(gamble_sum)33

34

35 defstart_game():36 gamble_sum = 1000

37 print('<<<<<>>>>')38 choices = ['big', 'small']39 while gamble_sum >0:40 your_choice = input('you guess big or samll:')41 wager = input('please take your wager<=1000:')42

43 if your_choice inchoices:44 points =roll_dice()45 total =sum(points)46 you_win = your_choice ==roll_result(total)47 ifyou_win:48 print('the points are', points, 'you win')49 gamble_sum = gamble_sum + int(wager) * 2

50 print(gamble_sum)51

52 else:53 print('the points are', points, 'you lose')54 gamble_sum = gamble_sum - int(wager) * 2

55 print(gamble_sum)56

57 else:58 print('Invalid words')59 start_game()60

61

62 start_game()

View Code

输入一个手机号,查询是移动?联通?电信?

ContractedBlock.gif

ExpandedBlockStart.gif

1 CN_mobile = [134, 135, 135, 137, 138, 139, 150, 151, 157, 158, 159, 182, 183, 184, \2 187, 188, 147, 178, 1705]3 CN_union = [130, 131, 132, 155, 156, 185, 186, 145, 176, 1709]4 CN_telecom = [133, 153, 180, 181, 189, 177, 1700]5 phone_number = input('Enter Your number:')6 if len(phone_number) < 11:7 print('Invalid length,your number should be in 11 digits')8 else:9 a = int(phone_number[0:3])10 if a inCN_mobile:11 print('mobile')12 elif a inCN_telecom:13 print('telecom')14 elif a inCN_union:15 print('union')

View Code

---恢复内容结束---

open打开一个txt文件,如果不存在则创建

ContractedBlock.gif

ExpandedBlockStart.gif

1 file=open('/Users/Administrator/Desktop/file.txt','w')2 file.write('hellp world!')

View Code

字符串相连

ContractedBlock.gif

ExpandedBlockStart.gif

1 what_he_does="plays"

2 his_instrument = 'guitar'

3 his_name='Robert Johnson'

4 artist_intro=his_name+what_he_does+his_instrument5 print(artist_intro)

View Code

#Robert Johnson plays guitar

字符串重复

ContractedBlock.gif

ExpandedBlockStart.gif

1 word = 'a looooong word'

2 num = 12

3 string = 'bang!'

4 total = string * (len(word)-num)5 print(total)6 #bang!bang!bang!

View Code

字符串分片索引

ContractedBlock.gif

ExpandedBlockStart.gif

1 word = 'friend'

2 find_the_evil_in_your_friends = word[0] + word[2:4] + word[-3:-1]3 print(find_the_evil_in_your_friends)4 #fieen

View Code

字符串替换replace()

ContractedBlock.gif

ExpandedBlockStart.gif

1 phone_number = '1386-444-0044'

2 hiding_number = phone_number.replace(phone_number[:9],'*'*9)3 print(hiding_number)4 #*********0044

View Code

字符串位置查找.find()

ContractedBlock.gif

ExpandedBlockStart.gif

1 search = '168'

2 num_a = '1386-168-0006'

3 num_b = '1681-222-0006'

4 print(search + 'is at' + str(num_a.find(search)) + 'to' + str(num_a.find(search) + len(search)) + 'of num_a')5 print(search + 'is at' + str(num_b.find(search)) + 'to' + str(num_b.find(search) + len(search)) + 'of num_b')6 """

7 168 is at 5 to 8 of num_a8 168 is at 0 to 3 of num_b9 """

View Code

字符串格式化{} .format()

ContractedBlock.gif

ExpandedBlockStart.gif

1 print('{} a word con get what she {} for .' .format('With','came'))2 print('{prepositon} a word she can get what she {verb} for'.format(prepositon = 'With',verb = 'came'))3 print('{0} a word she can get what she {1} for.' .format('with','came'))4 """

5 With a word con get what she came for .6 With a word she can get what she came for7 with a word she can get what she came for.8 """

View Code

创建一个温度转换函数F=9/5*C+32

ContractedBlock.gif

ExpandedBlockStart.gif

1 deffahrenheit_converter(C):2 fahrenheit = C * 9/5 + 32

3 return str(fahrenheit) + 'F'

4 C2F = fahrenheit_converter(35)5 print(C2F)6 #95.0F

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 c_d = input("请输入C温度值:")2 f_d = (9 * int(c_d))/5 + 32

3 print(f_d)4 """

5 请输入C温度值:06 32.07 """

View Code

文件写入

ContractedBlock.gif

ExpandedBlockStart.gif

1 deftext_create(name,msg):2 desktop_path = 'C:/Users/Administrator/Desktop/'

3 full_path = desktop_path + name + '.txt'

4 file = open(full_path,'w')5 file.write(msg)6 file.close()7 print('Done')8 text_create('hip','我是你爸爸')

View Code

文件内容过滤、替换

ContractedBlock.gif

ExpandedBlockStart.gif

1 def text_filter(word,censored_word = 'lame',changed_word = '*'*3):2 returnword.replace(censored_word,changed_word)3 text_filter('Python is lame!')4 #'Python is ***!'

View Code

条件控制if-else 设置用户密码

ContractedBlock.gif

ExpandedBlockStart.gif

1 defaccount_login():2 password = input('Password:')3 if password == '12345':4 print('Login success!')5 else:6 print('Wrong password or invalid input!')7 account_login()8 account_login()9 """

10 Wrong password or invalid input!11 Password:1245612 Wrong password or invalid input!13 Password:1234514 Login success!15 """

View Code

加入bool类型

ContractedBlock.gif

ExpandedBlockStart.gif

1 defaccount_login():2 password = input('Password:')3 password_correct = password == '12345'

4 ifpassword_correct:5 print('Login success!')6 else:7 print('Wrong password or invalid input!')8 account_login()9 account_login()

View Code

条件控制if-elif-else 重置密码

ContractedBlock.gif

ExpandedBlockStart.gif

1 password_list = ['*#*#','12345']2 defaccount_login():3 password = input('Password:')4 password_correct = password == password_list[-1]5 password_reset = password ==password_list[0]6 ifpassword_correct:7 print('Login success!')8 elifpassword_reset:9 new_password = input('Enter a new password:')10 password_list.append(new_password)11 print('Your password has changed successfully')12 account_login()13 else:14 print('Wrong password or invalid input!')15 account_login()16 account_login()17 """

18 Password:12319 Wrong password or invalid input!20 Password:*#*#21 Enter a new password:12322 Your password has changed successfully23 Password:12324 Login success!25 """

View Code

for循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 for every_letter in 'Hello world':2 print(every_letter)3

4 for num in range(1,11):5 print('1 +' + str(num) + '=' + str(num+1))

View Code

for循环和if结合起来

ContractedBlock.gif

ExpandedBlockStart.gif

1 songslist = ['Holy Diver','Thunderstruck','Rebel Rebel']2 for song insongslist:3 if song == 'Holy Diver':4 print(song,'- Dio')5 elif song == 'Thunderstruck':6 print(song,'- AC/DC')7 elif song == 'Rebel Rebel':8 print(song,'- David Bowie')9 """

10 Holy Diver - Dio11 Thunderstruck - AC/DC12 Rebel Rebel - David Bowie13 """

View Code

嵌套for循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 for i in range(1,10):2 for j in range(1,10):3 print('{} X {} = {}' .format(i,j,i*j))

View Code

while循环

ContractedBlock.gif

ExpandedBlockStart.gif

1 count =02 whileTrue:3 print('Repeat this line!')4 count = count + 1

5 if count == 5:6 break

View Code

while和if结合  密码输入三次错误禁止输入

ContractedBlock.gif

ExpandedBlockStart.gif

1 password_list = ['*#*#','12345']2 defaccount_login():3 tries=3

4 while tries >0:5 password = input('Password:')6 password_correct = password == password_list[-1]7 password_reset = password ==password_list[0]8

9 ifpassword_correct:10 print('Login success!')11 break

12 elifpassword_reset:13 new_password = input('Enter a new password:')14 password_list.append(new_password)15 print('Password has changed successfully!')16 account_login()17 else:18 print('Wrong password or invalis input!')19 tries = tries - 1

20 print(tries,'times left')21 else:22 print('Your account has been suspended!')23

24 account_login()

View Code

在桌面文件夹下创建10个文本,并以数字命名

ContractedBlock.gif

ExpandedBlockStart.gif

1 file_path = 'C:/Users/Administrator/Desktop/'

2 for i in range(1,10):3 f = open(file_path + str(i) + '.txt','w')

View Code

打印1-100的偶数

ContractedBlock.gif

ExpandedBlockStart.gif

1 for i in range(1,100):2 if i % 2 ==0:3 print(i)

View Code

摇骰子:摇三次,让用户输入猜大小:

ContractedBlock.gif

ExpandedBlockStart.gif

1 importrandom2

3

4 def roll_dice(numbers=3, points=None):5 print('<<<<<>>>>')6 if points isNone:7 points =[]8 while numbers >0:9 point = random.randrange(1, 7)10 points.append(point)11 numbers = numbers - 1

12 print(points)13 returnpoints14

15

16 defroll_result(total):17 isBig = 11 <= total <= 18

18 isSmall = 3 <= total <= 10

19 ifisBig:20 return 'big'

21 elifisSmall:22 return 'small'

23

24

25 defstart_game():26 print('<<<<<>>>>')27 choices = ['big', 'small']28

29 your_choice = input('you guess big or samll:')30 if your_choice inchoices:31 points =roll_dice()32 total =sum(points)33 you_win = your_choice ==roll_result(total)34 ifyou_win:35 print('the points are', points, 'you win')36 else:37 print('the points are', points, 'you lose')38 start_game()39 else:40 print('Invalid words')41 start_game()

View Code

在上一个项目基础上增加下注金额和赔率,初始金额为1000元,金额为0,赔率为1倍

ContractedBlock.gif

ExpandedBlockStart.gif

1 importrandom2

3

4 def roll_dice(numbers=3, points=None):5 print('<<<<<>>>>')6 if points isNone:7 points =[]8 while numbers >0:9 point = random.randrange(1, 7)10 points.append(point)11 numbers = numbers - 1

12 returnpoints13

14

15 defroll_result(total):16 isBig = 11 <= total <= 18

17 isSmall = 3 <= total <= 10

18 ifisBig:19 return 'big'

20 elifisSmall:21 return 'small'

22

23

24 def gamble(n=1000, you_win=True):25 wager = input('please take your wager<=1000:')26 while n >0:27 ifyou_win:28 gamble_sum = n + int(wager) * 2

29 print(gamble_sum)30 else:31 gamble_sum = n - int(wager) * 2

32 print(gamble_sum)33

34

35 defstart_game():36 gamble_sum = 1000

37 print('<<<<<>>>>')38 choices = ['big', 'small']39 while gamble_sum >0:40 your_choice = input('you guess big or samll:')41 wager = input('please take your wager<=1000:')42

43 if your_choice inchoices:44 points =roll_dice()45 total =sum(points)46 you_win = your_choice ==roll_result(total)47 ifyou_win:48 print('the points are', points, 'you win')49 gamble_sum = gamble_sum + int(wager) * 2

50 print(gamble_sum)51

52 else:53 print('the points are', points, 'you lose')54 gamble_sum = gamble_sum - int(wager) * 2

55 print(gamble_sum)56

57 else:58 print('Invalid words')59 start_game()60

61

62 start_game()

View Code

输入一个手机号,查询是移动?联通?电信?

ContractedBlock.gif

ExpandedBlockStart.gif

1 CN_mobile = [134, 135, 135, 137, 138, 139, 150, 151, 157, 158, 159, 182, 183, 184, \2 187, 188, 147, 178, 1705]3 CN_union = [130, 131, 132, 155, 156, 185, 186, 145, 176, 1709]4 CN_telecom = [133, 153, 180, 181, 189, 177, 1700]5 phone_number = input('Enter Your number:')6 if len(phone_number) < 11:7 print('Invalid length,your number should be in 11 digits')8 else:9 a = int(phone_number[0:3])10 if a inCN_mobile:11 print('mobile')12 elif a inCN_telecom:13 print('telecom')14 elif a inCN_union:15 print('union')

View Code

列表(list)

1.列表中的每一个元素都是可变的;

2.列表中的元素是有序的,也就是说每 一个元素都有一个位置;

3.列表可以容纳python中的任何对象

字典(Dictionary) key-value

1.字典中数据必须是以键值对的形式出现的

2.逻辑上讲,键是不能重复的,而值可以重复

3.字典中的键(key)是不可变的,也就是无法修改的,而值(value)是可变的,可修改的,可以是任何对象

元组(Tuple)

元组不可修改

集合(Set)

列表元素排序

ContractedBlock.gif

ExpandedBlockStart.gif

1 num_list = [6,24,2,2,4,3]2 print(sorted(num_list))

View Code

列表元素逆排序

ContractedBlock.gif

ExpandedBlockStart.gif

1 num_list = [6,24,2,2,4,3]2 print(sorted(num_list,reverse=True))

View Code

同时使用两个列表zip()

ContractedBlock.gif

ExpandedBlockStart.gif

1 num=[1,2,3,4]2 str=['1','2','3','4']3 for a,b inzip(num,str):4 print(b,'is',a)

View Code

列表解析式

ContractedBlock.gif

ExpandedBlockStart.gif

1 a =[]2 for i in range(1,11):3 a.append(i)4 print(a)

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 b = [i for i in range(1,11)]2 print(b)

View Code

列表推导式对比  list = [item for item in iterable]

ContractedBlock.gif

ExpandedBlockStart.gif

1 importtime2

3 a =[]4 t0 =time.clock()5 for i in range(1,20000):6 a.append(i)7 print(time.clock()-t0,"seconds process time")8

9 t0 =time.clock()10 b = [i for i in range(1,20000)]11 print(time.clock() - t0,"seconds process time")12 """

13 0.008940021162717623 seconds process time14 0.002357347740790874 seconds process time15 """

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 a = [i**2 for i in range(1,10)]2 c = [j+1 for j in range(1,10)]3 k = [n for n in range(1,10) if n %2 ==0]4 z = [letter.lower() for letter in 'ABCDEFGHIGKLMN']5 d = {i:i+1 for i in range(4)}6 g = {i:j for i,j in zip(range(1,6),'abcde')}7 m = {i:j.upper() for i,j in zip(range(1,6),'abcde')}8 print(a)9 print(c)10 print(k)11 print(z)12 print(d)13 print(g)14 print(m)15 """

16 [1, 4, 9, 16, 25, 36, 49, 64, 81]17 [2, 3, 4, 5, 6, 7, 8, 9, 10]18 [2, 4, 6, 8]19 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm', 'n']20 {0: 1, 1: 2, 2: 3, 3: 4}21 {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}22 {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}23 """

View Code

循环列表时获取元素的索引  enumerate

ContractedBlock.gif

ExpandedBlockStart.gif

1 letters = ['a','b','c','d','e','f','g']2 for num,letter inenumerate(letters):3 print(letter,'is',num+1)4 """

5 a is 16 b is 27 c is 38 d is 49 e is 510 f is 611 g is 712 """

View Code

字符串分开 .split()

ContractedBlock.gif

ExpandedBlockStart.gif

1 lyric = 'the night begin to shine,the night begin to shine'

2 words =lyric.split()3 print(words)4 """

5 ['the', 'night', 'begin', 'to', 'shine,the', 'night', 'begin', 'to', 'shine']6 """

View Code

词频统计

ContractedBlock.gif

ExpandedBlockStart.gif

1 importstring2

3 path = '/Users/Administer/Desktop/Walden.txt'

4

5 with open(path,'r') as text:6 words = [raw_word.strip(string.punctuation).lower() for raw_word intext.read().split()]7 words_index =set(words)8 conuts_dict = {index:words.count(index) for index inwords_index}9 for word in sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True):10 print('{} -- {} times'.format(word,counts_dict[word]))

View Code

类的实例属性

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 coke_for_China =Cocacola()4 coke_for_China.local_logo = '可口可乐' #创建实例属性

5

6 print(coke_for_China.local_logo) #打印实例属性引用结果

7 #可口可乐

View Code

类的实例方法

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 defdrink(self):4 print('Energy!')5 coke =Cocacola()6 coke.drink()

View Code

类的方法更多参数

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 defdrink(self,how_much):4 if how_much == 'a sip':5 print('cool--')6 elif how_much == 'whole bottle':7 print('headache')8

9 ice_coke =Cocacola()10 ice_coke.drink('a sip')

View Code

类的“魔术方法”__init__()

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 def __init__(self):4 self.local_logo = '可口可乐'

5 defdrink(self):6 print('Energy')7 coke =Cocacola()8 print(coke.local_logo)

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 def __init__(self):4 for element inself.formula:5 print('Coke has {}'.format(element))6 defdrink(self):7 print('Energy')8 coke = Cocacola()

View Code

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocacola:2 formula = ['caffeine','sugar','water','soda']3 def __init__(self,logo_name):4 self.local_logo =logo_name5 defdrink(self):6 print('Energy')7 coke = Cocacola('可口可乐')8 coke.local_logo

View Code

类的继承

ContractedBlock.gif

ExpandedBlockStart.gif

1 classCocaCola:2 calories = 140

3 sodium = 45

4 total_carb = 39

5 caffeine =34

6 caffeine = 34

7 ingredients =[8 'High fructose Corn Syrup',9 'Carbonated Water',10 'Phosphoric Acid',11 'Natural Flavors',12 'Caramel Color',13 'Caffeine'

14 ]15 def __init__(self,logo_name):16 self.local_logo =logo_name17 defdrink(self):18 print('You got {} cal energy!'.format(self.calories))19

20 classCaffeineFree(CocaCola):21 caffeine =022 ingredients =[23 'High fructose Corn Syrup',24 'Carbonated Water',25 'Phosphoric Acid',26 'Natural Flavors',27 'Caramel Color',28 ]29 coke_a = CaffeineFree('Cocacola-FREE')30

31 coke_a.drink()32

33 #You got 140 cal energy!

View Code

父类子类 起名

ContractedBlock.gif

ExpandedBlockStart.gif

1 ln_path = '/Users/Administrator/Desktop/last_name.txt' #名文件

2 fn_path = '/Users/Administrator/Desktop/first_name.txt' #姓文件

3

4 fn =[]5 ln1 = [] #单字名

6 ln2 = [] #双字名

7

8 with open(fn_path, 'r') as f: #打开姓的文本

9 for line in f.readlines(): #读取文本的每行

10 fn.append(line.split('\n')[0])11 print(fn)12 with open(ln_path, 'r') as f: #打开名的文本

13 for line inf.readlines():14 if len(line.split('\n')[0]) == 1: #单名

15 ln1.append(line.split('\n')[0])16 else: #双名多名

17 ln2.append(line.split('\n')[0])18 print(ln1)19 print('=' * 70) #分割线

20 print(ln2)21

22 importrandom23

24

25 classFakeUser:26 def fake_name(self, amount=1, one_word=False, two_words=False):27 n =028 while n <=amount:29 ifone_word:30 full_name = random.choice(fn) +random.choice(ln1)31 eliftwo_words:32 full_name = random.choice(fn) +random.choice(ln2)33 else:34 full_name = random.choice(fn) + random.choice(ln1 +ln2)35 yield(full_name)36 n += 1

37

38 def fake_gender(self, amount=1):39 n =040 while n <=amount:41 gender = random.choice(['男', '女', '未知'])42 yieldgender43 n += 1

44

45

46 classSnsUser(FakeUser):47 def get_followers(self, amount=1, few=True, a_lot=False):48 n =049 while n <=amount:50 iffew:51 followers = random.randrange(1, 50)52 elifa_lot:53 followers = random.randrange(200, 10000)54 yieldfollowers55 n += 1

56

57

58 user_a =FakeUser()59 user_b =SnsUser()60 for name in user_a.fake_name(30):61 print(name)62 for gender in user_b.get_followers(30):63 print(gender)

View Code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 《小白的第一本Python》是一本针对初学者而设计的Python编程入门籍。这本以浅显易懂的语言和生动的例子引导读者迈出编程的第一步。 首先,这本会从Python的基础知识开始讲解。它会解释Python的基本语法和常用数据类型,如整数、浮点数、字符串等。读者会学习到如何声明变量、使用运算符和控制流程语句来编写简单的程序。 此外,这本还会介绍Python的常用模块和库。读者会学习到如何利用这些模块和库来进行文件操作、网络编程、数据处理、图形绘制等常见任务。例如,读者会学习到如何使用NumPy进行科学计算,使用Pandas进行数据分析,使用Matplotlib进行数据可视化。 除了基础知识和常用模块外,这本还会教授一些编程的实践技巧。例如,如何编写函数和类来组织代码,如何进行调试和错误处理,如何与数据库进行交互等。通过这些实践技巧的学习,读者将能够写出更加规范和可维护的程序。 最后,这本还会引导读者完成一些小项目和练习,以帮助巩固所学知识。通过实战的方式,读者将能够更好地理解和应用Python编程。同时,这些项目和练习还将提供一些启发,帮助读者发现编程的乐趣和潜力。 综上所述,《小白的第一本Python》是一本循序渐进、内容丰富的Python编程入门籍。它通过简单易懂的讲解、丰富的实例以及实践项目,帮助读者掌握Python编程的基础知识和实践技巧。无论是对于初学者还是对于想要系统学习Python的人来说,这本都是一本不容错过的好。 ### 回答2: 小白的第一本Python是一本针对初学者编写的Python编程入门籍。这本以简单易懂的语言和实例,为初学者提供了全面且系统的学习Python的指南。 首先,这本Python的基础知识开始介绍,如数据类型、变量、运算符等。通过清晰的解释和实例演示,帮助读者理解这些概念,并通过实践练习巩固所学知识。 其次,这本深入探讨了Python的核心特性和功能,如条件语句、循环结构、函数、文件操作等。每个主题都有详细的解释和相关的编程实例,读者可以通过实践掌握这些概念,并将其应用于实际项目中。 此外,这本还介绍了面向对象编程(OOP)的基本概念和Python中的类和对象的使用。小白可以通过学习面向对象编程来构建更加复杂和可扩展的应用程序。 最后,这本还提供了一些实际应用案例,如网页爬虫、数据分析和简单的游戏开发等。通过这些案例,小白可以将所学知识应用于实际场景中,加深对Python的理解和掌握。 总之,小白的第一本Python是一本循序渐进、易于理解和实践的Python编程入门籍。通过系统学习这本小白可以打下坚实的Python基础,为进一步深入学习和应用Python编程奠定基础。 ### 回答3: 《小白的第一本Python》是一本专门为初学者设计的Python编程入门籍。本通过简明易懂的语言和生动的例子,帮助读者快速上手Python编程。 首先,本Python的基础知识进行了系统化的介绍。读者可以了解Python的发展历程、特点以及安装和配置等基本操作。通过对变量、数据类型、运算符、流程控制语句等的详细讲解,读者可以掌握Python基础知识,并能够编写简单的程序。 其次,本注重实践操作和编程实例的讲解。每个章节都包含大量的实例代码,通过实际案例的演示,读者可以更深入地理解Python的应用场景和编程技巧。同时,中还包含了一些项目实战,如简单的数据分析、Web爬虫等,读者可以通过实践提高编程能力。 此外,本还介绍了Python的常用库和框架,如NumPy、Pandas、Django等。这些工具可以帮助读者更高效地开发程序,提高编程效率。同时,本还对Python的调试技巧和代码优化进行了讲解,帮助读者提高程序的质量和性能。 总而言之,《小白的第一本Python》是一本适合初学者的Python编程入门籍。无论是对于零基础的读者,还是对于已有其他编程语言基础的读者,本都能够提供一种简单易懂、系统全面的学习方式,帮助读者快速入门Python编程

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值