如何使用户按特定顺序输入关注列表

我有一个代码块,使用户输入斐波那契数列。代码块:


    numb_list = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55]

    numb = int(input('Enter the next Fibonacci number >'))

    while numb in numb_list and numb <= 50:

      numb = int(input('Enter the next Fibonacci number >'))

        if numb in numb_list:

          print('Well done')

        else:

          print('Try again')

我要求用户输入这些数字。当用户输入超过50或输入所有正确的数字时,程序会给出输出“做得好”。如果用户输入错误,程序将输出“重试”。这是完美的工作,但我将如何使用户输入按照这个特定的顺序跟随这个列表,如果不是按照这个顺序,程序输出“重试”。


这是电流输出:


    Enter the next Fibonacci number >1

    Enter the next Fibonacci number >1

    Enter the next Fibonacci number >2

    Enter the next Fibonacci number >3

    Enter the next Fibonacci number >8

    Enter the next Fibonacci number >3

    Enter the next Fibonacci number >

这是我想要实现的输出:


    Enter the next Fibonacci number >1

    Enter the next Fibonacci number >1

    Enter the next Fibonacci number >2

    Enter the next Fibonacci number >3

    Enter the next Fibonacci number >8

    Enter the next Fibonacci number >3

    Try again

不幸的是,我在实现此输出时遇到问题。有人能帮助我吗?


万千封印
浏览 149回答 2
2回答

慕尼黑8549860

您可以改为循环访问目标号码,并使用循环不断要求用户输入,直到输入号码与目标号码匹配:numb_listwhilenumb_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]for target in numb_list:&nbsp; &nbsp; while int(input('Enter the next Fibonacci number >')) != target:&nbsp; &nbsp; &nbsp; &nbsp; print('Try again')print('Well done')

有只小跳蛙

假设您希望在每次输入正确值时都进行打印,并且修改了您的值以在其中增加一个1(根据斐波那契数列),则每次获得序列中的下一个值时,都可以在带有索引的列表中移动:Well donenumb_listnumb_list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]numb = 0current_index = 1while numb <= 50:&nbsp; &nbsp; numb = int(input('Enter the next Fibonacci number >'))&nbsp; &nbsp; if numb_list[current_index] == numb:&nbsp; &nbsp; &nbsp; &nbsp; print('Well done')&nbsp; &nbsp; &nbsp; &nbsp; current_index += 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print('Try again')如果您不想打印每个迭代,只需删除该语句即可Well doneprint()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python