Python -> (7) study notes

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 Mthe form of print.

Claim:

  • Users can enter a command line parameter number of minutes, do not use input, you can use the command-line parameters sys.argvto extract. For example, a program is executed python3 MinutesToHours.py 80, the argument passed 80is the number of minutes, the program need to print out the corresponding number of hours and minutes, is output 1 H, 20 M.
  • If the user enters a negative value, the program needs raiseto throw an ValueErrorexception.
  • Hours()When a function call is required try...exceptto handle exceptions. After obtaining an exception, you print out the on-screen Parameter Errorprompts the user to enter an incorrect value.
  • sys.argvGets command line arguments, pay attention to the parameter acquisition of a string, you can use int()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")
Published 33 original articles · won praise 1 · views 1250

Guess you like

Origin blog.csdn.net/weixin_44783002/article/details/104582804