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

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

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

View Code

字符串相连

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

字符串重复

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

字符串分片索引

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()

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()

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()

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

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

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

文件写入

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

文件内容过滤、替换

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 设置用户密码

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类型

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 重置密码

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循环

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结合起来

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循环

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循环

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

5 if count == 5:6 break

View Code

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

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个文本,并以数字命名

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

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倍

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

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

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文件,如果不存在则创建

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

View Code

字符串相连

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

字符串重复

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

字符串分片索引

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()

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()

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()

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

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

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

文件写入

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

文件内容过滤、替换

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 设置用户密码

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类型

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 重置密码

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循环

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结合起来

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循环

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循环

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

5 if count == 5:6 break

View Code

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

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个文本,并以数字命名

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的偶数

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

View Code

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

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倍

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

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

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)

列表元素排序

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

View Code

列表元素逆排序

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

View Code

同时使用两个列表zip()

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

列表解析式

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

View Code

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

View Code

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

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

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

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()

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

词频统计

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

类的实例属性

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

类的实例方法

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

View Code

类的方法更多参数

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__()

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

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

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

类的继承

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

父类子类 起名

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

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

  1. 没学过编程可以学python吗_没编程基础可以学python吗

    Python是一门高级编程语言,而且Python语言适合零基础人员学习,也是初学者的首选. 如何学习好Python: 1. 要有决心 做任何事情,首先要有足够的决心和坚持,才能做好事情.学好Pytho ...

  2. python编程第四版_清华编程教授强力推荐《Python编程》,指导你如何学习python

    Python编程真的那么容易吗?仅仅是看理论就可以学以致用吗? 今天我给你介绍的这本书,也许会让你开始改变这种想法,因为这本书上的练习和案例以及指导本身就足够学好Python了. 清华编程教授强力推荐 ...

  3. 计算机小白可以学python吗_非计算机专业小白如何系统学Python语言

    零基础小白该如何学习python语言呢?对于菜鸟而言,非计算机专业成为他们学习的拦路虎,没有基础是不是真就学不会了呢?无论是实用性还是易用性,Python都是学习编程最具性价比的选择.在今年,Pyth ...

  4. 《趣学Python——教孩子学编程》——第1部分 学习编程 第1章 Python不是大蟒蛇 1.1 关于计算机语言...

    本节书摘来自异步社区<趣学Python--教孩子学编程>一书中的第1章,第1.1节,作者[美]Jason R. Briggs,尹哲 译,更多章节内容可以访问云栖社区"异步社区&q ...

  5. 清华大学python基础_清华大学出版社-图书详情-《Python基础入门-微课视频版》

    前言 Python语言自从20世纪90年代初诞生至今,逐渐被广泛应用于处理系统管理任务和科学计算,是最受欢迎的程序设计语言之一. 学习编程是工程专业学生学习的重要部分.除了直接的应用外,学习编程还是了 ...

  6. python高阶学习之一:c++调用python

    python高阶学习之一:c++调用python python已经成为当今人工智能和数据分析的主流语言,掌握python就好像拿到了进入AI分析殿堂的门票一样,无论如何任何事情都要从一点一滴做起,不要 ...

  7. python开发cad教程视频_我是编程小白,我想视频学习Python会不会能学会?

    其实Python入门并不难,只要你有足够的自信心,明确学习目标,循序渐进就能不断享受到python带给你创新的乐趣. 之前我也是看了很多python入门视频教程,个人觉得有几个还是很不错的,大家可以学 ...

  8. 编程入门python java和c语言_学习编程适不适合从Python入门?哪种语言更适合入门?...

    本文对比了C语言和Python语言,分析它们作为编程入门语言各自的利弊,并给出了我推荐的编程学习道路. 我本身已经入门了Python脚本语言,在进阶C语言和JAVA语言后,Python重学就轻松很多, ...

  9. 编写python程序、计算账户余额_《易学Python》——第1章 为何学习Python 1.1 学习编程...

    本节书摘来自异步社区<易学Python>一书中的第1章,第1.1节,作者[澳]Anthony Briggs,王威,袁国忠 译,更多章节内容可以访问云栖社区"异步社区"公 ...

  10. python编程要懂英语吗_学习编程必须要会英语吗?

    原标题:学习编程必须要会英语吗? 很多刚开始想学编程的人都问这问那,比如"我英文差能学编程吗?"."我数学差能学编程吗?". 之前给大家分析了数学与编程之间的关 ...

最新文章

  1. Logger PatternLayout 格式
  2. 《操作系统》实验报告——主存空间的分配与回收
  3. FFMPEG分析比较细的文章
  4. 不止 Windows 10!Windows 7/8 也能免费升级到 Windows 11
  5. mysql表主键类型_mysql表结构主键类型
  6. js中小数取整数(向上、向下取整数,四舍五入取整数的实现)
  7. Java通过反射机制修改类中的私有属性的值
  8. eclipse部署web没部署成功的问题
  9. coreldraw快速撤回_CorelDRAW操作技巧,教你CDR撤销操作方法与设置技巧
  10. 安卓ps模拟器_电脑安装模拟器配置要求
  11. 人物故事 | 回顾美人建筑师,致世界建筑日
  12. printf输出格式化
  13. 左神算法:找到二叉树中的最大搜索二叉子树(树形dp套路,Java版)
  14. Java Foreach拉姆达表达式
  15. 青蛙跳台阶问题(超详解)
  16. 12306抢票工具的使用
  17. 为什么说体验即设计?
  18. 无法打开Win10计算机管理,win10系统我的电脑管理打不开怎么办
  19. 对360沙盒的驱动的一点逆向分析
  20. AD学习笔记(一)基础认识

热门文章

  1. regionserver.HRegionServer: error telling master we are up
  2. RSA加密算法介绍及Java工具类
  3. 数据分析方法01对比分析法
  4. Linux系统点歌机
  5. HP LaserJet MFP M227-M231 scan use manual
  6. 为什么会有跨域的问题出现,如何解决跨域问题
  7. Design Compiler (八)——DC的逻辑综合与优化
  8. 美容仪小白必看|ShowYoung秀漾微电流祛皱美容仪种草~
  9. 如果我定义了一个函数,该函数会弹出一个选项框,用户只能选择其中一个选项,那么这个函数的名字应该叫selec好还是choice好?...
  10. 【JaveWeb】JavaWeb