import traceback try: raise Exception('This is an error message.') except: errorFile = open('errorInfo.txt', 'w') errorFile.write(traceback.format_exc()) ## 116个字符被写入到文件中 errorFile.close() print('The traceback info was written to errorInfo.txt.') # The traceback info was written to errorInfo.txt.
1 2 3 4
Traceback (most recent call last): File "<ipython-input-42-3cf24af55dca>", line 3, in <module> raise Exception('This is an error message.') Exception: This is an error message.
{'ns': 'yellow', 'ew': 'green'} --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-51-bc61311a1f1e> in <module> 11 assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight) 12 ---> 13 switchLights(market_2nd)
<ipython-input-51-bc61311a1f1e> in switchLights(stoplight) 9 stoplight[key] = 'green' 10 print(stoplight) ---> 11 assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight) 12 13 switchLights(market_2nd)
AssertionError: Neither light is red! {'ns': 'yellow', 'ew': 'green'}
在运行 Python 时传入-O 选项,可以禁用断言。
日志logging
启用Python的 logging 模块,可以在程序运行时,将日志信息显示在屏幕上。
比如你编写了阶乘函数,但结果不对,所以你需要输入一些日志信息,来帮助你弄清楚哪里出了问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') ## 写入文本 # logging.basicConfig(filename='Log.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') logging.debug('Start of program') deffactorial(n): logging.debug('Start of factorial(%s%%)' % (n)) total = 1 for i in range(n + 1): total *= i logging.debug('i is ' + str(i) + ', total is ' + str(total)) logging.debug('End of factorial(%s%%)' % (n)) return total print(factorial(5))
logging.debug('End of program')
然后把for i in range(n + 1)改为for i in range(1, n + 1)即可。
Celsius To Fahrenheit and Fahrenheit to Celsius conversion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
whileTrue: CF = input("Plz input temperature in celsius(e.g. 25c) / Fahrenheit(e.g. 52f): ") try: if CF.endswith("C") or CF.endswith("c"): fcelsius = float(CF[:-1]) fahrenheit = (fcelsius * 1.8) + 32 print('%.2f°C = %0.2f°F' %(fcelsius, fahrenheit)) break elif CF.endswith("F") or CF.endswith("f"): ffahrenheit = float(CF[:-1]) celsius = (ffahrenheit - 32) / 1.8 print('%.2f°F = %0.2f°C' %(ffahrenheit, celsius)) break else: print("Invalid Format Error, plz check your input! ") except ValueError: print("Invalid Format Error, plz check your input! ")
1 2 3 4
Plz input temperature in celsius(e.g. 25c) / Fahrenheit(e.g. 52f): 0x6f Invalid Format Error, plz check your input! Plz input temperature in celsius(e.g. 25c) / Fahrenheit(e.g. 52f): 036f 36.00°F = 2.22°C
Iteration
Lets see a StopIterationexample:
A triplet (x, y, z) is called pythogorian triplet if x*x + y*y == z*z.
defintegers(): """Infinite sequence of integers.""" i = 1 whileTrue: yield i i = i + 1
defsquares(): for i in integers(): yield i * i
deftake(n, seq): """Returns first n values from the given sequence.""" seq = iter(seq) result = [] try: for i in range(n): result.append(next(seq)) except StopIteration: pass return result
print(take(5, squares())) # [1, 4, 9, 16, 25]
1 2 3
pyt = ((x, y, z) for z in integers() for y in range(1, z) for x in range(1, y) if x*x + y*y == z*z) take(10, pyt) # [(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17), (12, 16, 20), (15, 20, 25), (7, 24, 25), (10, 24, 26), (20, 21, 29)]