在Python 3中使用异常和写入文件数据

0 投票
3 回答
940 浏览
提问于 2025-04-18 00:28

这是我需要做的事情:

如果用户选择了菜单上没有的任何项目,你的程序必须抛出一个异常。除了抛出异常,还要写代码来处理这个异常。

询问用户要转换的值。如果输入出现错误,你的程序必须抛出异常,并处理这个异常。

进行转换,并将原始值、原始单位、转换后的值和转换后的单位写入一个名为conversions.txt的输出文件。

重复步骤a和b 10次(用循环)。

这是我的代码:

#imports

import os

# global variables
mile_choice = 1
gallon_choice = 2
pound_choice = 3
inch_choice = 4
fah_choice = 5
quit_choice = 6

mainfile = open('conversions.txt', 'w')

# intro and global name variable

name = input ('what is your name? ')
print()
print('hello',name,', today we will be doing\
some standard to metric conversions.')

#define main function
def main():

    choice = 0

    while choice != quit_choice:

             display_menu()

             print()
             choice = int(input('Please enter a number 1 - 6 : '))\

             if choice == mile_choice:
                    print()
                    miletokm()

             elif choice == gallon_choice:
                    print()
                    galtolit()

             elif choice == pound_choice:
                    print()
                    poundstokg()

             elif choice == inch_choice:
                    print()
                    inchtocm()

             elif choice == fah_choice:
                    print()
                    fahtocel()

             elif choice == quit_choice:
                    print()
                    print('Exiting the program.')




#define functions
def display_menu():
    print()
    print('          Menu          ')
    print()
    print('Press 1 for Miles to Kilometers')
    print()
    print('Press 2 for Gallons to Liters')
    print()
    print('Press 3 for Pounds to Kilograms')
    print()
    print('Press 4 for Inches to Centimeters')
    print()
    print('Press 5 for Fahrenhiet to Celisus')
    print()
    print('To exit please enter 6 ')



def miletokm():
     invalid_attempts = 0

 #while loop for invalid input limited to 3

    while invalid_attempts < 3 and invalid_attempts >= 0:
        print()
        mile = float(input('how many miles would you\
 like to convert to kilometers? '))
        mainfile.write(str(mile) + '\n')

 # if statement to determine weather to proceed with conversation
 # valid input = conversion
 # invalid input =  return with + 1 to invalid_attempt count

    if mile >= 0 :

        print()
        mile_conv = mile * 1.6
        print('that would be:', format(mile_conv, '.2f'), 'kilometers.')
        print()
        mainfile.write(str(mile_conv) + '\n')
        return mile


    else:

        print()
        print ('invalid input')
        print()
        invalid_attempts += 1

我省略了其他转换的定义,以便让内容更简洁。

我在异常处理部分遇到了问题。我尝试了各种方法,但就是搞不清楚怎么正确写出代码。我知道如何定义一个值错误,用于处理输入超出菜单范围的数字,但我不明白如何将单位和输入的数据一起写入文件。现在的写法是没有把任何信息写入主文件。

我觉得我的代码写得很乱。我不知道该怎么办,因为我的教授拒绝帮助我。

我知道这些内容很多,但我真的没有其他地方可以求助。我不明白该如何构建代码,以及如何有效地完成我需要做的事情。我读过的资料涵盖了基础知识,但除了非常简单的例子外,我没有其他可以参考的例子,这些简单的例子只涉及单一的内容。

3 个回答

0

你可以试试这样的做法……(来自 http://docs.python.org/2/tutorial/errors.html#exceptions

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...
0

你走在正确的道路上。首先,你需要更好地处理用户给你的 choice 值。试着想想,如果用户输入 9 或者 'foo' 会发生什么。

接下来,你应该对你在转换单位的函数中接收到的每一个值都做同样的处理。为此,你可以使用 try/except,就像 @bitfish 给你展示的那样(不过你要用 input 而不是 raw_input)。

0
  1. 记得关闭你打开的文件(用 mainfile.close()
  2. 在这个 while choice != quit_choice 里写 elif choice == quit_choice: 是没有意义的
  3. '\n' 可以跳过一行(print('\n')print() 两次效果是一样的)

解决这样的问题有很多种方法,随着经验的积累,你会发现更优雅的解决方案,但这个方法已经可以用了。

撰写回答