names = ['ada','tom','jerry','boby','clala']
for name in names:
print('Hello, ' + name.title() + ', Welcome !')
print('Have a good time!\n')
print('The party is beginning now!')
digits = []
digits.append(digit)
print(min(digits))
print(max(digits))
print(sum(digits))
odds = list(range(1,21,2))
for odd in odds:
print(odd)
列表解析方式以及for循环方式处理列表
three_list = []
for num in range(3,31,3):
print(num)
lifang = [num**3 for num in range(1,11)]
print(lifang)
lifang=[]
for num in range(1,11):
lifang.append(num**3)
print(num**3)
列表切片处理
lf = lifang[-3:-1]
print(lf)
if条件控制语句
age = 24
if age<5:
price = '0$'
elif age<18:
price = '5$'
elif age<24:
price = '10$'
else:
price = '15$'
print('The ticket price is ' + str(price))
字典及相关增删改操作
alien_0 = {'name':'ada' , 'point':5 , 'color':'green'}
print(alien_0['name'])
print(alien_0['point'])
print(alien_0['color'])
print(alien_0)
alien_0['address'] = 'Mars'
print(alien_0)
del alien_0['name']
print(alien_0)
favorite_languages = {
'Ada':'C',
'Bobo':'Java',
'Cindy':'Python',
}
person_info = {
'first_name':'wang',
'last_name':'kai',
'age':'32',
'city':'Beijing',
'address':'Beijing',
}
print(person_info)
for key,value in person_info.items():
print(str(key) + ' : ' + str(value))
for key in person_info.keys():
print(key)
for value in set(sorted(person_info.values())):
print(value)
嵌套处理,字典与列表嵌套
alien_0 = {'color':'red','point':'5'}
alien_1 = {'color':'green','point':'10'}
alien_2 = {'color':'blue', 'point':'15'}
aliens = [alien_0,alien_1,alien_2]
print(aliens[0]['color'])
alien_list = []
for num in range(30):
if num % 2:
alien_new = {'color':'red','point':'5'}
else:
alien_new = {'color':'white','point':'10'}
alien_list.append(alien_new)
print(alien_new)
while循环,带表示控制以及退出循环命令break
active = True
dict = {}
while active:
key = input('Please input the key : ')
if key != 'exit':
value = input('please input the value : ')
dict[key] = value
else:
active = False
break
print('\n')
print(dict)
函数
def print_models(unprinted_models,printed_models):
while unprinted_models:
printed_model = unprinted_models.pop()
printed_models.append(printed_model)
def show_models(printed_models):
print(printed_models)
unprinted_models = ['Yuwen','Shuxue','Yingyu','Lishi']
printed_models = []
print_models(unprinted_models,printed_models)
show_models(printed_models)
print(unprinted_models)
def make_pizza(size,*toppings):
print(toppings)
print('make a ' + str(size) +'-inch pizza with the following toppings: ')
for topping in toppings:
print(' - ' + str(topping))
print('\n')
make_pizza(16,'onion')
make_pizza(30,'apple','banana','orange')
类相关操作
车类
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer = 0
def get_desc(self):
desc = str(self.year) + '-' + self.make + '-' +self.model
return desc.title()
电动车类,继承自车类,并使用电池类作为属性
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery(100)
def increase_odometer(self,mileage):
if mileage>0:
self.odometer +=mileage
else:
print("You can't roll back odometer !")
电池类
class Battery():
def __init__(self,battery_size=80):
self.battery_size = battery_size
def desc_battery(self):
print('This car has a ' + str(self.battery_size) +
'-kwh battery')
def get_range(self):
current_range = self.battery_size * 3
print('This car can go approximately ' + str(current_range) +
' miles on a full charge !')
类的导入
from module.ElectricCar import ElectricCar
new_car = ElectricCar('byd','model e',2018)
print(new_car.get_desc())
<html>
<head>
network
</head>
<body>
<h1>
some content for network
</h1>
</body>
</html>
读取文件内容(整个文件一起读)
with open(r'module\ni_digits.txt') as file_object:
path = r'C:\Users\admin\Desktop\module\ni_digits.txt'
with open(path) as file_object:
contents = file_object.read()
print(contents.rstrip())
按行读取文件,并处理其中某一行内容
web_title = ''
flag = False
with open(r'module\ni_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())
if flag:
web_title = str(line.strip())
flag = False
if str(line.rstrip())=='<head>':
flag = True
print('The Web Title is ' + web_title)
创建一个包含文件各行内容的列表
lines = []
with open(r'module\ni_digits.txt') as file_object:
第一种方式
lines = file_object.readlines()
第二种方式
for line in file_object:
lines.append(line.rstrip())
for line in lines:
print(line.rstrip())
learning.txt文件
I love python !
I love C++ !
I love python too
I love python three
replace方法
message_string = ''
with open('module\learning.txt') as file_object:
languages = file_object.readlines()
for language in languages:
message_string += str(language)
print(message_string + '\n')
new_message_string = message_string.replace('Python','Java')
new_message_string = message_string.replace('python','Java')
print(new_message_string)
写入文件, r:可读 , w:可写入(覆盖) , a:增量写入
with open('module\learning.txt','a') as file_object:
file_object.write('\nI love action script 3.0 !')
message = input('请输入您的名字:')
with open(r'module\mname.txt','w') as file_object:
file_object.write(message)
try—except—else异常处理之ZeroDivisionError
print('Give me two numbers, and I\'ll divide them')
print('Enter q to quit')
while True:
first_num = input('\nFirst number: ')
if first_num == 'q':
break
second_num = input('\nSecond number: ')
if second_num == 'q':
break
try:
answer = float(first_num) / float(second_num)
except ZeroDivisionError:
print('You can\'n divide by 0 !')
else:
result = '计算结果为:'+str(first_num) + ' / ' + str(second_num)
result += ' = ' + str(answer)
print(result)
FileNotFoundError异常处理
file_root = 'module'
file_path = ''
contents = ''
file_names = ['alice.txt', 'Battery.py', 'Car.py', 'ElectricCar.py',
'learning.txt', 'name.txt', 'ni_digits.txt']
def word_count(file_path,file_name):
try:
with open(file_path) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = 'file ' + file_name + ' not found !'
print(msg)
else:
print('file ' + file_name + ' have ' + str(len(files)) + ' words !')
for name in file_names:
file_path = file_root + '\\' + name
word_count(file_path,name)
问候用户,存储和读取json村取用户名
import json
def greet_user():
username = get_stored_name()
if username:
print('welcome back ' + username)
else:
get_new_name()
print('we will remember you !')
def get_stored_name():
try:
with open('username.json') as file_object:
username = json.load(file_object)
except FileNotFoundError:
return None
else:
return username
def get_new_name():
username = input('Please input your name: ')
with open('username.json','w') as f_obj:
json.dump(username,f_obj)
return username
greet_user()
json存取字符串练习
import json
def stored_json():
country = input('Input your country: ')
with open('country.json','w') as f_obj:
json.dump(country,f_obj)
def read_json():
with open('country.json') as f_obj:
country = json.load(f_obj)
print('Your county name is ' + country)
stored_json()
read_json()
json存取列表字典联系
import json
digits = [1,3,5,7,9]
user_info ={'username':'wangkai', 'country':'China', 'age':'32'}
def json_store_list():
with open('digit_list.json','w') as f_obj:
json.dump(user_info,f_obj)
def json_read_list():
with open('digit_list.json') as f_obj:
digit_list = json.load(f_obj)
print(digit_list)
json_store_list()
json_read_list()
待测试的类
class AnoySurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print('Survey Result:')
for response in self.responses:
print('-' + response)
测试用例
import unittest
from anoy_survey import AnoySurvey
class TestAnoySurvey(unittest.TestCase):
def setUp(self):
question = 'What language did you first learn to speak?'
self.my_survey = AnoySurvey(question)
self.responses = ['English', 'Chinese', 'Spanish', 'French',]
def test_store_single_response(self):
question = 'What language did you first learn to speak?'
my_survey = AnoySurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_responses(self):
question = 'What is your favorite language ?'
my_survey = AnoySurvey(question)
responses = ['English', 'Chinese', 'Spanish', 'French', 'Gemany']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response,my_survey.responses)
unittest.main()