Python 计算思维训练——输入和错误处理练习(一)

  • Post author:
  • Post category:python

第1关:交互式输入 – 华氏-摄氏温度换算

编程要求
人们常用以下公式进行华氏-摄氏温度转换:

C=(F−32)÷1.8

C 和 F 分别为摄氏度和华氏度。

请在右侧编辑器中的Read函数中,打印一句提示语华氏温度=?,然后读取用户输入的华氏温度,使用上面的公式转化为摄氏温度后输出。

注意:打印提示语后不要换行,具体要求请见测试说明。

def Read():
    #   请在此添加实现代码   #
    # ********** Begin *********#
    f=float(input('华氏温度=?'))
    c=(f-32)*5/9
    print(c)
    # ********** End **********#

第2关:文件读取- 华氏-摄氏温度换算

编程要求
以上一关为基础,这次是从文件中读取华氏温度值,使用转化公式计算出摄氏温度后将其输出。

def Read():
    #   请在此添加实现代码   #
    # ********** Begin *********#
    path = input()
    infile=open(path,'r')
    f=(float)(infile.readlines()[-1].split()[-1])
    c=(f-32)*5/9
    print(c)
    infile.close()
    # ********** End **********#

第3关:文件读取 – 华氏-摄氏温度换算

任务描述
本关任务:编写一个能将文件中的华氏温度转化成摄氏温度小程序。

def Read():
    outputPath = 'step3/out.txt' #输出文件的路径
    #   请在此添加实现代码   #
    # ********** Begin *********#
    path = input()
    infile=open(path,'r')
    lines=infile.readlines()
    outfile=open(outputPath,'w')
    outfile.write('Fahrenheit\tCelsius\n')
    outfile.write('--------------------\n')
    for i in range(2,len(lines)):
        f=(float)(lines[i].split()[-1])
        c=(f-32)*5/9
        outfile.write('%.5f\t%.5f\n' % (f,c))
    infile.close()
    outfile.close()
    # ********** End **********#

第4关:异常处理 – 华氏-摄氏温度换算

def Read(data):
    #   请在此添加实现代码   #
    # ********** Begin *********#
    try:
        f=float(data[0])
        c=(f-32)*5/9
        print(c)
    except IndexError:
        print('error:请输入华氏温度')
    # ********** End **********#

版权声明:本文为qq_43570528原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。