Python学习笔记(二) 代码练习

这篇博客主要介绍了Python编程的基础知识,包括列表操作、字典处理、循环控制、异常处理和文件读写。此外,还深入探讨了类的定义和继承,如车类、电动车类和电池类,以及使用unittest进行测试。同时,讲解了如何使用json模块进行数据的存储和读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单列表以及简单处理函数

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

标准库—有序字典

import collections
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'

d2 = collections.OrderedDict()
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'

print(d1 == d2)

测试文件:ni_digits.txt

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

测试用例中可以使用setUp方法,unittest.TestCase中包含这个方法,这个方法会优先于test

开头的方法运行,可以在该方法中初始化一些类,属性,这些都可以在所有的test方法中使用

 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值