while循环::::仅迭代1次,而条件满足时则迭代

时间:2019-07-01 07:58:45

标签: python

在给定的代码中,我有一个while循环,用于打印斐波那契数列,在此,我有一条打印行

print(f'''The Fibonacci series of number "{last_number}" is"{y}.''')

我希望此行仅打印一次,并且仅在其后添加y的值。输出应为数字“ 50”的斐波那契数列是1,1,2,3,5,8,13,21, 34。

while True:
            while True:
                        try:
                            last_number = int(input('\nEnter last number :'))
                        except ValueError:
                            print("\nPlease enter only number")
                        else:
                            break
            x,y=0,1
            while y<last_number:
                print(f'''The Fibonacci series of number "{last_number}" is"{y}.''')
                x,y=y,x+y
            while True:
                        Repeat=input("\nDo you want to repeat?\n\nYes or No:")
                        Repeat=Repeat.lower()
                        if Repeat not in ["yes","y","no","n"]:
                            print("\nPlease select correct option")
                        else:
                            break


            if Repeat in ["yes","y"]:
                continue
            else:
                if Repeat in ["no","n"]:
                    print("\n-----Thank you for using-----")
                    input()
                    break

2 个答案:

答案 0 :(得分:0)

在循环之前进行打印,然后创建一个列表,并通过添加添加该系列。 然后,您可以只打印列表,它看起来会一样 另一种方法是在打印之前创建列表,然后使用您输入的句子打印列表

答案 1 :(得分:0)

您需要将值插入列表中,然后再从列表中获取值,因为列表中有整数值,需要先将其设为字符串,然后再从列表中获取值。

    while True:
                while True:
                            try:
                                last_number = int(input('\nEnter last number :'))
                            except ValueError:
                                print("\nPlease enter only number")
                            else:
                                break
                x,y=0,1
                z=[]
                while y<last_number:
                    z.append(y)
                    x,y=y,x+y
                a=str(z)[1:-1]
                print(f'''The Fibonacci series of number "{last_number}" is {a}.''')
                while True:
                            Repeat=input("\nDo you want to repeat?\n\nYes or No:")
                            Repeat=Repeat.lower()
                            if Repeat not in ["yes","y","no","n"]:
                                print("\nPlease select correct option")
                            else:
                                break


                if Repeat in ["yes","y"]:
                    continue
                else:
                    if Repeat in ["no","n"]:
                        print("\n-----Thank you for using-----")
                        input()
                        break