3 回答

TA贡献1801条经验 获得超8个赞
您应该将代码分解为执行您想要执行的操作的单个函数。在这种情况下,您可以提示用户是要从文件中读取还是手动输入。根据该决定,您可以调用适当的函数。
def jumlah(A,B,C):
result = A+B+C
return result
def start():
option = input(' Would you like to: \n'
' - (r) read from a file \n'
' - (i) input(i) by hand \n'
' - (q) quit \n ')
if option.lower() not in 'riq':
print('Invalid choice, please select r, i, or q.')
option = start()
return option.lower()
def by_hand():
count = 0
i = eval(input('input total test case: '))
while count < i :
A = eval(input('input A: '))
B = eval(input('input B: '))
C = eval(input('input C: '))
result = jumlah(A,B,C)
count = count + 1
print('case no'+str(count)+' : '+str(result))
def from_file():
path = input('Please input the path to the file: ')
with open(path, 'r') as fp:
cases = int(fp.readline().strip())
for i in range(1, cases+1):
a,b,c = fp.readline(), fp.readline(), fp.readline()
result = jumlah(A,B,C)
print('case no'+str(i)+' : '+str(result))
def main():
while True:
opt = start()
if opt == 'r':
from_file()
if opt == 'i':
by_hand()
if opt == 'q':
print('Goodbye.')
return
if __name__ == '__main__':
main()
添加回答
举报