我需要做的是:
如果用户选择菜单上没有的任何项目,程序必须引发异常
提出了。在引发异常的同时,编写处理此异常的代码。在
要求用户为转换。你的程序必须引发异常,并处理异常,如果输入
发生错误
执行转换并写入原始值、原始单位、
转换后的值,并将转换后的单位转换为名为
转换.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
我遗漏了另一个转换定义。让它更短。在
我有问题的例外部分首先和大部分。
我试过各种方法,但我不知道如何正确地写出代码
我知道如何为菜单范围外输入的数字定义值错误
我不明白如何将单位和输入的数据一起写入文件。
以我现在的方式,它没有向主文件写入任何信息。在
我也觉得我的代码写得很草率。我不知道,因为我的教授拒绝帮助我。在
我知道有很多事情要做,但我真的没有别的路可走。我不明白我应该如何构建代码,以及如何有效地完成我需要完成的任务。
我所读到的内容涵盖了这一点的基础,但我没有其他例子可以看,除了非常简单的例子,严格地处理一件事。在