---恢复内容开始---
open打开一个txt文件,如果不存在则创建

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

1 what_he_does=" plays" 2 his_instrument = ' guitar' 3 his_name=' Robert Johnson' 4 artist_intro=his_name+what_he_does+his_instrument 5 print(artist_intro)
#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!
字符串分片索引

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
字符串替换replace()

1 phone_number = '1386-444-0044' 2 hiding_number = phone_number.replace(phone_number[:9],'*'*9) 3 print(hiding_number) 4 #*********0044
字符串位置查找.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_a 8 168 is at 0 to 3 of num_b 9 """
字符串格式化{} .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 for 7 with a word she can get what she came for. 8 """
创建一个温度转换函数F=9/5*C+32

1 def fahrenheit_converter(C): 2 fahrenheit = C * 9/5 + 32 3 return str(fahrenheit) + 'F' 4 C2F = fahrenheit_converter(35) 5 print(C2F) 6 #95.0F

1 c_d = input("请输入C温度值:") 2 f_d = (9 * int(c_d))/5 + 32 3 print(f_d) 4 """ 5 请输入C温度值:0 6 32.0 7 """
文件写入

1 def text_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','我是你爸爸')
文件内容过滤、替换

1 def text_filter(word,censored_word = 'lame',changed_word = '*'*3): 2 return word.replace(censored_word,changed_word) 3 text_filter('Python is lame!') 4 #'Python is ***!'
条件控制if-else 设置用户密码

1 def account_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:12456 12 Wrong password or invalid input! 13 Password:12345 14 Login success! 15 """
加入bool类型

1 def account_login(): 2 password = input('Password:') 3 password_correct = password == '12345' 4 if password_correct: 5 print('Login success!') 6 else: 7 print('Wrong password or invalid input!') 8 account_login() 9 account_login()
条件控制if-elif-else 重置密码

1 password_list = ['*#*#','12345'] 2 def account_login(): 3 password = input('Password:') 4 password_correct = password == password_list[-1] 5 password_reset = password == password_list[0] 6 if password_correct: 7 print('Login success!') 8 elif password_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:123 19 Wrong password or invalid input! 20 Password:*#*# 21 Enter a new password:123 22 Your password has changed successfully 23 Password:123 24 Login success! 25 """
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))
for循环和if结合起来

1 songslist = ['Holy Diver','Thunderstruck','Rebel Rebel'] 2 for song in songslist: 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 - Dio 11 Thunderstruck - AC/DC 12 Rebel Rebel - David Bowie 13 """
嵌套for循环

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

1 count = 0 2 while True: 3 print('Repeat this line!') 4 count = count + 1 5 if count == 5: 6 break
while和if结合 密码输入三次错误禁止输入

1 password_list = ['*#*#','12345'] 2 def account_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 if password_correct: 10 print('Login success!') 11 break 12 elif password_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()
在桌面文件夹下创建10个文本,并以数字命名
摇骰子:摇三次,让用户输入猜大小:

1 import random 2 3 4 def roll_dice(numbers=3, points=None): 5 print('<<<<<<ROLL THE DICE!>>>>>') 6 if points is None: 7 points = [] 8 while numbers > 0: 9 point = random.randrange(1, 7) 10 points.append(point) 11 numbers = numbers - 1 12 print(points) 13 return points 14 15 16 def roll_result(total): 17 isBig = 11 <= total <= 18 18 isSmall = 3 <= total <= 10 19 if isBig: 20 return 'big' 21 elif isSmall: 22 return 'small' 23 24 25 def start_game(): 26 print('<<<<<<GAME STARTS>>>>>') 27 choices = ['big', 'small'] 28 29 your_choice = input('you guess big or samll:') 30 if your_choice in choices: 31 points = roll_dice() 32 total = sum(points) 33 you_win = your_choice == roll_result(total) 34 if you_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()
在上一个项目基础上增加下注金额和赔率,初始金额为1000元,金额为0,赔率为1倍

1 import random 2 3 4 def roll_dice(numbers=3, points=None): 5 print('<<<<<<ROLL THE DICE!>>>>>') 6 if points is None: 7 points = [] 8 while numbers > 0: 9 point = random.randrange(1, 7) 10 points.append(point) 11 numbers = numbers - 1 12 return points 13 14 15 def roll_result(total): 16 isBig = 11 <= total <= 18 17 isSmall = 3 <= total <= 10 18 if isBig: 19 return 'big' 20 elif isSmall: 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 if you_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 def start_game(): 36 gamble_sum = 1000 37 print('<<<<<<GAME STARTS>>>>>') 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 in choices: 44 points = roll_dice() 45 total = sum(points) 46 you_win = your_choice == roll_result(total) 47 if you_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()
输入一个手机号,查询是移动?联通?电信?

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 in CN_mobile: 11 print('mobile') 12 elif a in CN_telecom: 13 print('telecom') 14 elif a in CN_union: 15 print('union')
---恢复内容结束---
open打开一个txt文件,如果不存在则创建

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

1 what_he_does=" plays" 2 his_instrument = ' guitar' 3 his_name=' Robert Johnson' 4 artist_intro=his_name+what_he_does+his_instrument 5 print(artist_intro)
#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!
字符串分片索引

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
字符串替换replace()

1 phone_number = '1386-444-0044' 2 hiding_number = phone_number.replace(phone_number[:9],'*'*9) 3 print(hiding_number) 4 #*********0044
字符串位置查找.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_a 8 168 is at 0 to 3 of num_b 9 """
字符串格式化{} .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 for 7 with a word she can get what she came for. 8 """
创建一个温度转换函数F=9/5*C+32

1 def fahrenheit_converter(C): 2 fahrenheit = C * 9/5 + 32 3 return str(fahrenheit) + 'F' 4 C2F = fahrenheit_converter(35) 5 print(C2F) 6 #95.0F

1 c_d = input("请输入C温度值:") 2 f_d = (9 * int(c_d))/5 + 32 3 print(f_d) 4 """ 5 请输入C温度值:0 6 32.0 7 """
文件写入

1 def text_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','我是你爸爸')
文件内容过滤、替换

1 def text_filter(word,censored_word = 'lame',changed_word = '*'*3): 2 return word.replace(censored_word,changed_word) 3 text_filter('Python is lame!') 4 #'Python is ***!'
条件控制if-else 设置用户密码

1 def account_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:12456 12 Wrong password or invalid input! 13 Password:12345 14 Login success! 15 """
加入bool类型

1 def account_login(): 2 password = input('Password:') 3 password_correct = password == '12345' 4 if password_correct: 5 print('Login success!') 6 else: 7 print('Wrong password or invalid input!') 8 account_login() 9 account_login()
条件控制if-elif-else 重置密码

1 password_list = ['*#*#','12345'] 2 def account_login(): 3 password = input('Password:') 4 password_correct = password == password_list[-1] 5 password_reset = password == password_list[0] 6 if password_correct: 7 print('Login success!') 8 elif password_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:123 19 Wrong password or invalid input! 20 Password:*#*# 21 Enter a new password:123 22 Your password has changed successfully 23 Password:123 24 Login success! 25 """
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))
for循环和if结合起来

1 songslist = ['Holy Diver','Thunderstruck','Rebel Rebel'] 2 for song in songslist: 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 - Dio 11 Thunderstruck - AC/DC 12 Rebel Rebel - David Bowie 13 """
嵌套for循环

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

1 count = 0 2 while True: 3 print('Repeat this line!') 4 count = count + 1 5 if count == 5: 6 break
while和if结合 密码输入三次错误禁止输入

1 password_list = ['*#*#','12345'] 2 def account_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 if password_correct: 10 print('Login success!') 11 break 12 elif password_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()
在桌面文件夹下创建10个文本,并以数字命名

1 file_path = 'C:/Users/Administrator/Desktop/' 2 for i in range(1,10): 3 f = open(file_path + str(i) + '.txt','w')
打印1-100的偶数

1 for i in range(1,100): 2 if i % 2 == 0: 3 print(i)
摇骰子:摇三次,让用户输入猜大小:

1 import random 2 3 4 def roll_dice(numbers=3, points=None): 5 print('<<<<<<ROLL THE DICE!>>>>>') 6 if points is None: 7 points = [] 8 while numbers > 0: 9 point = random.randrange(1, 7) 10 points.append(point) 11 numbers = numbers - 1 12 print(points) 13 return points 14 15 16 def roll_result(total): 17 isBig = 11 <= total <= 18 18 isSmall = 3 <= total <= 10 19 if isBig: 20 return 'big' 21 elif isSmall: 22 return 'small' 23 24 25 def start_game(): 26 print('<<<<<<GAME STARTS>>>>>') 27 choices = ['big', 'small'] 28 29 your_choice = input('you guess big or samll:') 30 if your_choice in choices: 31 points = roll_dice() 32 total = sum(points) 33 you_win = your_choice == roll_result(total) 34 if you_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()
在上一个项目基础上增加下注金额和赔率,初始金额为1000元,金额为0,赔率为1倍

1 import random 2 3 4 def roll_dice(numbers=3, points=None): 5 print('<<<<<<ROLL THE DICE!>>>>>') 6 if points is None: 7 points = [] 8 while numbers > 0: 9 point = random.randrange(1, 7) 10 points.append(point) 11 numbers = numbers - 1 12 return points 13 14 15 def roll_result(total): 16 isBig = 11 <= total <= 18 17 isSmall = 3 <= total <= 10 18 if isBig: 19 return 'big' 20 elif isSmall: 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 if you_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 def start_game(): 36 gamble_sum = 1000 37 print('<<<<<<GAME STARTS>>>>>') 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 in choices: 44 points = roll_dice() 45 total = sum(points) 46 you_win = your_choice == roll_result(total) 47 if you_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()
输入一个手机号,查询是移动?联通?电信?

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 in CN_mobile: 11 print('mobile') 12 elif a in CN_telecom: 13 print('telecom') 14 elif a in CN_union: 15 print('union')
列表(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))
列表元素逆排序

1 num_list = [6,24,2,2,4,3] 2 print(sorted(num_list,reverse=True))
同时使用两个列表zip()

1 num=[1,2,3,4] 2 str=['1','2','3','4'] 3 for a,b in zip(num,str): 4 print(b,'is',a)
列表解析式

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

1 b = [i for i in range(1,11)] 2 print(b)
列表推导式对比 list = [item for item in iterable]

1 import time 2 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 time 14 0.002357347740790874 seconds process time 15 """

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 """
循环列表时获取元素的索引 enumerate

1 letters = ['a','b','c','d','e','f','g'] 2 for num,letter in enumerate(letters): 3 print(letter,'is',num+1) 4 """ 5 a is 1 6 b is 2 7 c is 3 8 d is 4 9 e is 5 10 f is 6 11 g is 7 12 """
字符串分开 .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 """
词频统计

1 import string 2 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 in text.read().split()] 7 words_index = set(words) 8 conuts_dict = {index:words.count(index) for index in words_index} 9 for word in sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True): 10 print('{} -- {} times'.format(word,counts_dict[word]))
类的实例属性

1 class Cocacola: 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 #可口可乐
类的实例方法

1 class Cocacola: 2 formula = ['caffeine','sugar','water','soda'] 3 def drink(self): 4 print('Energy!') 5 coke = Cocacola() 6 coke.drink()
类的方法更多参数

1 class Cocacola: 2 formula = ['caffeine','sugar','water','soda'] 3 def drink(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')
类的“魔术方法”__init__()

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

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

1 class Cocacola: 2 formula = ['caffeine','sugar','water','soda'] 3 def __init__(self,logo_name): 4 self.local_logo = logo_name 5 def drink(self): 6 print('Energy') 7 coke = Cocacola('可口可乐') 8 coke.local_logo
类的继承

1 class CocaCola: 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_name 17 def drink(self): 18 print('You got {} cal energy!'.format(self.calories)) 19 20 class CaffeineFree(CocaCola): 21 caffeine = 0 22 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!
父类子类 起名

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(' ')[0]) 11 print(fn) 12 with open(ln_path, 'r') as f: # 打开名的文本 13 for line in f.readlines(): 14 if len(line.split(' ')[0]) == 1: # 单名 15 ln1.append(line.split(' ')[0]) 16 else: # 双名多名 17 ln2.append(line.split(' ')[0]) 18 print(ln1) 19 print('=' * 70) # 分割线 20 print(ln2) 21 22 import random 23 24 25 class FakeUser: 26 def fake_name(self, amount=1, one_word=False, two_words=False): 27 n = 0 28 while n <= amount: 29 if one_word: 30 full_name = random.choice(fn) + random.choice(ln1) 31 elif two_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 = 0 40 while n <= amount: 41 gender = random.choice(['男', '女', '未知']) 42 yield gender 43 n += 1 44 45 46 class SnsUser(FakeUser): 47 def get_followers(self, amount=1, few=True, a_lot=False): 48 n = 0 49 while n <= amount: 50 if few: 51 followers = random.randrange(1, 50) 52 elif a_lot: 53 followers = random.randrange(200, 10000) 54 yield followers 55 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)