Python核心编程 第十章练习

笔者刚刚开始Python的系统学习,所以在代码上还无法达到pythonic的水准,很多写法也都是按照C++的习惯来写的,希望能有前辈进行交流指导。

欢迎拍砖

9_6

#!/usr/bin/python
# coding:utf-8

def safe_open(file_name):
    try:
        f = open(file_name)
    except IOError, e:
        f = None
        print e
    return f

if __name__ == '__main__':
    file_name = raw_input('Please input a file name: ')
    f = safe_open(file_name)

10_8

#!/usr/bin/python
# coding: utf-8

def safe_raw_input(str_not):
    try:
        str_ret = raw_input(str_not)
    except (EOFError, KeyboardInterrupt), e:
        str_ret = None
    return str_ret

if __name__ == '__main__':
    str_ret = safe_raw_input("Please input a string: ")

10_9

#!/usr/bin/python
# coding: utf-8

import math

def safe_sqrt(num):
    try:
        ret = math.sqrt(num)
    except ValueError, e:
        ret = complex(0, math.sqrt(abs(num)))
    return ret

if __name__ == '__main__':
    num_sqrt = safe_sqrt(float(raw_input("Input a num: ")))
        print "The result is: %s " %num_sqrt

你可能感兴趣的:(Python,学习笔记)