关于使Python代码更简洁的建议

时间:2018-01-20 14:00:44

标签: python

我刚开始学习python,刚刚编写了一个程序,允许用户找到Fibonacci序列的第n个术语。我测试了它,似乎按预期工作。我的问题是如何使我的代码更简洁或更pythonic。任何建议或提示将不胜感激。

values = [0,1]
n1 = 2

while True:                      # input and loop to limit the input range.
    try:
        n = int(input('Please enter position of fibonacci sequence you wish to know.'))
        break
    except:
        print('That\'s not a valid input')

if n < 3:                                #calculation block
    print (n)

else:
    while n1 != n:
        n2 = values[0] + values[1]
        values[0] = values[1]
        values[1] = n2
        n1 +=1

    print (n2)

1 个答案:

答案 0 :(得分:0)

使用函数可以使你的代码更多&#34; pythonic&#34; - 简洁可能不是您的首要任务:

def get_user_input():
    while True:                      # input and loop to limit the input range.
        try:
            n = int(input('Please enter position of fibonacci sequence you wish to know.'))
            return n
        except:
            print('That\'s not a valid input')


def get_nth_fib_number(nth):
    values = [0, 1]

    current_fib = 2

    while current_fib <= nth:
        values.append(values[-2] + values[-1])
        current_fib += 1

    return values[nth]

get_nth_fib_number(get_user_input())