Small experiment:
implement a program, the minutes into hours and minutes. Implement a function MinutesToHours.py file Hours()
, input by the user 分钟数
into 小时数和分钟数
, and the number of hours required as large as possible. The results in XX H, XX M
the form of print.
Claim:
- Users can enter a command line parameter number of minutes, do not use
input
, you can use the command-line parameterssys.argv
to extract. For example, a program is executedpython3 MinutesToHours.py 80
, the argument passed80
is the number of minutes, the program need to print out the corresponding number of hours and minutes, is output1 H, 20 M
. - If the user enters a negative value, the program needs
raise
to throw anValueError
exception. Hours()
When a function call is requiredtry...except
to handle exceptions. After obtaining an exception, you print out the on-screenParameter Error
prompts the user to enter an incorrect value.sys.argv
Gets command line arguments, pay attention to the parameter acquisition of a string, you can useint()
the string to an integer, here may also occur unusual circumstances, such as the input is "abcd" can not be converted to an integer- raise statement
- try ... except statement
import sys
# 转换函数
def Hours(minute):
# 如果为负数则 raise 异常
if minute < 0:
raise ValueError("Input number cannot be negative")
else:
print("{} H, {} M".format(int(minute / 60), minute % 60))
# 函数调用及异常处理逻辑
try:
Hours(int(sys.argv[1]))
except:
print("Parameter Error")