Python 学习中查询过的各种函数

input & raw_input

input

>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<type 'int'>               # 整型

>>> a = input("input:")    
input:"runoob"           # 正确,字符串表达式
>>> type(a)
<type 'str'>             # 字符串

>>> a = input("input:")
input:runoob               # 报错,不是表达式
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined

raw_input

>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串

>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串

列表副本

有时候,需要禁止函数修改列表。

为解决这个问题,可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

要将列表的副本传递给函数,可以像下面这样做:

function_name(list_name[:])

切片表示法 [:] 创建列表的副本。

传递任意数量的实参

在定义函数时,在形参前加入*可以让python创建一个空元组,用于存放数量不定的实参,如

def make_pizza(*toppings):
   print(toppings)

其中topping可以接受任意数量的实参。

Python先匹配位置实参和关键字实参,再将余下的实参收集到最后一个形参中。因此带*的形参应当放在最后一位。

在形参前加入**可以让python创建一个空字典,可以存放任意数量的键-值对:

def build_profile(first,last,**user_profile):
   profile = {}
   profile['first'] = first
   profile['last'] = last
   for key,value in user_profile.items:
      profile[key] = value
   return profile

user_profile = build_profile('albert','einstein',location='princeton',field='physics')

导入模块

from module_name import *
代表将模组中所有函数直接导入,使用时可以直接使用函数名,不用加点。如果是导入并非自己编写的大型模块时一般不这样用为了防止函数名出现重叠。
import module_name
使用时是module_name.function_name()

调用文件

with在不再需要访问文件后将其关闭。使用关键字with时,open()返回的文件对象只在with代码块内使用。若要在with代码块外使用,应先存储于变量中,再对变量中内容进行操作。如

with open('1.txt') as file_object

文件路径在Linux和OS中使用斜杠/,在Windows路径中使用反斜杠\。
读取文本文件时,python将所有文本解读为字符串。

处理异常

可以编写try-except代码块来处理可能发生的异常。
try-except-else代码块工作原理:Python尝试执行try代码块中的代码,只有可能引发异常的代码才需要放在try中,成功了后会运行else中的代码。当出现异常会执行except代码块中的代码。
eg:

while True:
   first_number = input("\nfirst number:")
   second_number = input("\nsecond number:")
   try:
      answer = int(first_number)/int(second_number)
   except ZeroDivisionError:
      print("You can't divide by 0!")
   else:
      print(answer)

pass 可以在代码块中什么都不做,异常发生时如果希望没有反应继续运行可以在except代码块中用pass。

存储数据

简单的存储数据的方法可以使用json模块来进行。eg:

"在numbers.json中存储一组数据"
import json

numbers = [2,3,5,7,9,10]

filename = 'numbers.json'
with open(filename,w) as f_obj:
   json.dump(numbers,f_obj)

"将这个列表读取到内存中"
with open(filename) as f_obj:
   numbers = json.load(f_obj)

单元测试

导入unittest模块,使用unittest后所有以test_打头的方法都将自动运行。
eg:
针对单个函数的测试:

import uinttest
from name_function import get_formatted_name

class NameTestCase(unittest.TestCase):
   """测试name_function.py"""
   def test_first_last_name(self):
      """能够正确处理像Jains Joplin这样的姓名吗?"""
      formatted_name = get_formatted_name('jains','joplin')
      self.assertEqual(formatted_name,'Jains Joplin')
unittest.main()

if name == 'main’的意思是:当.py文件被直接运行时,if name == 'main’之下的代码块将被运行;当.py文件以模块形式被导入时,if name == 'main’之下的代码块不被运行。

unittest.TestCase中有很多种断言方法如下:
在这里插入图片描述

针对类的测试:

import unittest
from city import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    def test_store_single_response(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')

        self.assertIn('English',my_survey.responses)

unittest.main()

unittest中setUp()可以创建一个供测试使用的实例,在测试时python会先运行setUp()之后再运行test_打头的代码块。eg

"""在TestAnonymousSurvey类中修改setUp函数"""
   def setUp(self):
      question = "What language did you first learn to speak?"
      self.my_survey = AnonymousSurvey(question)
      self.responses = ['English','Spanish','Madarin']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值