将 while 循环用户输入计算添加到列表中。

我正在使用 python3 并且我有这个代码,我要求用户提供三个输入。然后我对它们进行计算。我想继续将计算结果添加到列表中。怎么做?


...


if choice == '1': #my fist input x

    while True:

        x = int(input('Please insert the number of things you consider yourself a fan of'))

        if x > 0:

            break

        else:

             print('Please insert a number higher than 0')


elif choice == '2': #my second input y

    while True:

        y = int(input('Please insert the number of hobbies you like to do every month'))

        if y % 4 == 0:

            break

        else:

            print('Please insert a valid number')


elif choice == '3': #my third input z

    while True:

        z = int(input('Please insert the number of sports you like'))

        if z > 0:

            break

        else:

            print('Please insert a number higher than 0')


elif choice == '4': #the calculation part

    import math

    def square_root():

        c=(42 * y ** 2)/(z + 1)

        nerd_score=int(x*math.sqrt(c))

        return nerd_score

    print('your nerd score is', square_root())

我希望循环继续进行,并将每个结果添加到列表中。直到用户退出循环。


手掌心
浏览 151回答 1
1回答

慕容森

据我了解,您要解决两个问题:循环继续,util 用户想退出循环将每个结果添加到列表中示例代码在这里:def loop_calculation(choice):    # record results in list    results = []    # loop keep going, util user input choice 'x' which means exit    while choice != 'x':        if choice == '1':  # my fist input x            while True:                x = int(input('Please insert the number of things you consider yourself a fan of'))                if x > 0:                    break                else:                    print('Please insert a number higher than 0')        elif choice == '2':  # my second input y            while True:                y = int(input('Please insert the number of hobbies you like to do every month'))                if y % 4 == 0:                    break                else:                    print('Please insert a valid number')        elif choice == '3':  # my third input z            while True:                z = int(input('Please insert the number of sports you like'))                if z > 0:                    break                else:                    print('Please insert a number higher than 0')        elif choice == '4':  # the calculation part            import math            def square_root():                c = (42 * y ** 2) / (z + 1)                nerd_score = int(x * math.sqrt(c))                return nerd_score            result = square_root()            print('your nerd score is', result)            # add each result to list            results.append(result)    return results希望它会帮助你。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python