程序代码:
def get_input(): print("请输入两个参数,第一个是整数,第二个是 add 或者 fact, 不区分大小写") while True: s = input(">") try: num, operate = s.split() num = int(num) return num, operate except ValueError: print("请按以下格式输入\n9 add\n4 fact") def process(num, operate): if operate.lower() == 'add': output = add(num) print(output) add_record(output) elif operate.lower() == 'fact': output = fact(num) print(output) add_record(output) def add_record(output): with open("jisuan.txt", 'a+') as f: f.write(output + "\n") def add(num): sum = 0 formula = "" n = [] for i in range(2, num): if i % 2 == 0: sum += i n.append(str(i)) formula = "+".join(n) return "输入 {} {}, {}={}".format(num, 'add', formula, sum) def fact(num): sum = 1 formula = "" n = [] for i in range(1, num + 1): sum *= i n.append(str(i)) formula = "*".join(n) return "输入 {} {}, {}={}".format(num, 'fact', formula, sum) if __name__ == '__main__': num, operate = get_input() process(num, operate)