"Python programming from entry to practice," the study notes finishing 2: Basics articles (under) Chapter 7-11

Chapter 7 user input and the while loop (in conjunction with the preparation of an interactive program)

7.1 function input () works

message = input ( "lucid prompt")
to halt the program, waiting for user input, returns the string (available int () conversion, etc.)
* while loop may be combined to fill a large number of dictionary data structure such as

About 7.2 while loop

while the specified conditions:
continue to run until a specified condition is not satisfied; the need to avoid an endless loop
meet a number of requirements before if conditions continue to run, you can define a Boolean variable ( " Flag "), to determine whether active
break statement : exit for / while loop
continue statement : ignore the rest of the code, return to the beginning of the cycle, to determine whether to continue

7.3 Use while loop to process lists and dictionaries (collect, store and organize a large number of inputs)

the list should not be modified for loop, while loop may be modified to traverse +

  • Binding pop () list of the mobile element
  • Combined with remove () to delete all specified values
  • Binding input () is filled using the user input dictionary

Chapter 8 Functions

Function : the code block with a name, improved code efficiency, easier maintenance and troubleshooting, and can be reused in different programs

8.1 Defined Functions

Defined : DEF function name (parameter):
call : the function name (arguments)
* using the descriptive name of the function, increase the readability

8.2 pass arguments

(1) the position arguments : the same arguments parameter order
(2) Keyword argument : without regard to order, passing the name - value pairs, such as type = "dog"
parameter can specify a default value , a lower priority than Explicit argument provided; with default values need to be placed last parameter listed
when the default value set to the empty string, the parameter may be considered optional value , so that the function of different situations simplified
number of arguments provided or when the type does not meet the requirements, it will lead to error

8.3 Return Value return (simplified main routine)

The return value can be of any type, including lists and dictionaries

8.4 transfer list

Permanent modification, efficient handling of large amounts of data; transfer [:] can not modify copy, but will reduce the efficiency of caution
* Each function should only be responsible for a specific job, it helps to complex tasks into a series of steps

8.5 pass any number of arguments

* Parameter name: Create an empty tuple receive any number of arguments value
** parameter name: Create an empty dictionary, any number of arguments received key - the value of
the two required on the last, the remaining arguments package

8.6 The function stored in the module (independent file)

Import the entire module (dot notation to call):

  • import module name (as Alias)

Importing a specific function (direct call):

  • import module name from the function name (as alias)

All import function module ( not recommended ):

  • import * from module name

8.7 guidelines for the preparation function

Descriptive name; only lowercase letters and underscores; documenting the string; keyword = default and do not need the space on both sides of
the code sequence :( program comment +) import statements subject code +

Chapter 9 class

Oriented Object Programming: Writing class, define a general behavior, and then create a class-based objects (instances of)

9.1 Creating and using classes

# 类名称首字母大写
# 实例名首字母小写
class Dog():
'''类的说明'''
	
	# 方法:类中的函数
	# 属性:类中以self为前缀的变量
	# __init__特殊方法,实例化时自动运行;__默认方法前后均有两个下划线__
	# self是指向实例本身的引用,自动传递,让实例访问类中的属性和方法(句点表示法)
	def __init__(self, name):
	    self.name = name
	
	def other_method(self):

# 创建实例
my_dog = Dog(“a”)
# 访问属性,无括号
my_dog.name
# 调用方法,有括号
my_dog.other_method()

9.2 classes and instances

Attribute must specify the initial value (0 or a null value may also be, and variables a reason):
(1) passing the argument assignment instantiation, __ the init __ () parentheses must include the corresponding parameter
(2) specify a default within the class value, __ __ the init () without brackets comprise corresponding parameter directly self.attr = value to
modify the values of properties: direct access modification; revised update properties prepared by the method

9.3 Inheritance

Subclasses = parent (superclass) + new attributes and methods , similar to the parent and the parent file prior

class 父类名():
class 其他类():
class 子类名(父类名):
	def __init__(self,形参):
		# super()将父类与子类关联起来
	    super().__init__(形参)
		self.新属性=初始值
		# 将实例用作属性,便于将大类拆分为多个协同工作的小类
		self.other_attri=其他类()
	
	def 新方法(self):
	
	# 重写方法
	def 父类同名方法(self):

* Class can simulate physical modeling method no right or wrong, only the high and low points of efficiency

9.4 Class introduced (stored in the module, similar to the import function):

Import the entire module (dot notation to call):

  • import module name (as Alias)

Import specific classes (direct call):

  • import module name from a class name (name of the class 2, ......)

All classes import module ( not recommended ):

  • import * from module name

9.5 Python standard library: a set of modules

Such as:
collections.OrderedDict: Record key - value pair sequence (using OrderedDict () call, rather than curly brackets)
Random Module: generates a random number
math mathematics module

9.6 Class Coding Style

Class name : OrderedDict (hump nomenclature)
instance name / module name : ordered_dict
functions, classes, modules required documentation string
to import standard library module, and then empty row + custom module

Chapter 10 Files and exceptions

10.1 reads data from a file (Returns a string)

# 使用任何文件前均需打开
# 使用with可在无需访问后自动关闭文件,比手动open()+close()方便
# open()返回的对象仅在with代码块内可用
# filename=当前目录下的文件名/相对or绝对文件路径(Windows系统需使用r+反斜杠\)
# 当字符串较长或较复杂时,往往先将其存储在一个变量中,再将变量传递给函数
with open(filename) as f: 
	data = f.read().rstrip() # read()返回包含全部内容的字符串,且末尾有空行
	for line in f: # for循环逐行读取
	lines = f.readlines() # 逐行读取并存入列表

10.2 to write the file (string format)

# mode包括:r读取,w写入,a附加,r+读写,省略=默认只读
with open(filename, mode) as f: 
    f.write(data) # 需手动添加换行符\n等设置格式

10.3 anomaly (a management error special category)

Using the try-except (-else) block processing

try:
    # 可能引发异常的代码
except 异常名:
    # 处理异常的代码
    # 或直接pass(什么也不做;或充当占位符,留待之后编写)
else:
    # try没问题后才能执行的代码

Abnormal : ZeroDivisionError, FileNotFoundError etc.
advantage : the program from collapse, can continue to run and more robust; the degree of control share an error message to the user

10.4 storing data (JSON module)

The JSON (the JavaScript Object Notation), during programming language common
memory : json.dump (data, f_obj)
reads : the json.load (f_obj)
* Reconstruction : into a series of code handles the details of the function, simplify the structure of the code to make the code more clear and easy to understand, easy to maintain expansion

Chapter 11 test code (unittest module)

11.1 test function

Unit Testing : one aspect of the verification function no problem
test case : a set of unit tests, no problem under a variety of situations to verify the function; full coverage is difficult, generally for important behavioral written test to

import unittest
from 模块名 import 需测试的函数名

class 最好与测试函数相关且包含Test的类名(unittest.TestCase):
    # 必须test_开头,方法才将自动调用;长没事,描述清楚即可
	def test_测试内容(self): 
	    a = 需测试的函数()
	    # 断言方法之一
	    self.assertEqual(实际值a,期望值b)

# 运行测试
unittest.main()

Output Results :
(1) dot / E / F = a pass / test initiator error / cause assertion failure test
(2) OK (FAILED) = ( un) pass all the tests

11.2 Test class

Similar tests with test function class, the class is the behavior of the test method

Six kinds of assertions :

  • assertEqual(a,b)、assertNotEqual(a,b)
  • assertTrue(x)、assertFalse(x)
  • assertIn(item,list)、assertNotIn(item,list)

We need to create a test class instance of each test method; using setUp () can be created only once, and in all methods; the Python first run setUp (), and then starts operating method test_

def setUp(self):
    # 可一次性创建一系列实例并设置属性
	self.实例名=()
	self.属性名=value
Released four original articles · won praise 0 · Views 111

Guess you like

Origin blog.csdn.net/qq_33440285/article/details/104560528