为了账号安全,请及时绑定邮箱和手机立即绑定

如何将.in文件作为python的输入

如何将.in文件作为python的输入

万千封印 2021-09-14 20:22:52
这是我的代码def jumlah(A,B,C):    global result    result = A+B+Ccount = 0i = eval(input('input total test case: '))while count < i :    A = eval(input('input A: '))    B = eval(input('input B: '))    C = eval(input('input C: '))    jumlah(A,B,C)    count = count + 1    print('case no'+str(count)+' : '+str(result))如何放置外部文件进行输入,这样我就可以在不输入数字 1 by 1 的情况下进行测试这是我的示例 input.in 文件2123234第一行是案例总数,其余是 A、B 和 C 的输入。我的预期结果将是case no1 : 6case no2 : 9请帮忙。谢谢
查看完整描述

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()



查看完整回答
反对 回复 2021-09-14
  • 3 回答
  • 0 关注
  • 277 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号