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

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

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

手掌心 2021-12-21 15:07:43
我正在使用 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())我希望循环继续进行,并将每个结果添加到列表中。直到用户退出循环。
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

据我了解,您要解决两个问题:

  1. 循环继续,util 用户想退出循环

  2. 将每个结果添加到列表中

示例代码在这里:

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

希望它会帮助你。


查看完整回答
反对 回复 2021-12-21
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信