如何让Python斐波那契数列代码更简洁、更具Pythonic风格?
Nice job getting your Fibonacci code up and running—testing early to confirm functionality is such a solid habit! Let’s break down how to make this code more concise, readable, and aligned with Python’s best practices (aka "Pythonic" style):
1. Narrow Down Exception Handling
Your current except: catches all exceptions, which can hide unexpected errors (like accidental keyboard interrupts). Instead, catch only the specific error you expect: ValueError when the input can’t be converted to an integer. We can also make the input loop more straightforward by adding a check for positive positions:
while True: try: n = int(input('Please enter position of fibonacci sequence you wish to know: ')) if n >= 1: # Ensure we're working with a valid positive position break print('Please enter a positive integer.') except ValueError: print('That\'s not a valid integer—try again!')
2. Replace List Tracking with Variable Unpacking
Your values list works, but Python’s variable unpacking lets us update the two previous values in one clean line—no index juggling required. This is way more readable and idiomatic:
Instead of this:
n2 = values[0] + values[1] values[0] = values[1] values[1] = n2
Do this:
a, b = b, a + b
3. Simplify Boundary Conditions
Your current if n < 3 logic works, but making the base cases explicit makes the code easier to follow (and matches the variable names we’ll use later):
if n == 1: print(1) elif n == 2: print(2) else: # Calculation logic here
4. Wrap It All in a Function
Putting the core logic into a function makes it reusable, testable, and cleaner. Returning the value instead of printing it directly also gives you more flexibility (like using the result elsewhere later).
Full Optimized Code
Here’s how all these improvements come together:
def get_fibonacci(n): # Handle base cases matching your original logic if n == 1: return 1 elif n == 2: return 2 # Initialize starting values a, b = 1, 2 # Loop from 3 to n (since we've already handled positions 1 and 2) for _ in range(3, n + 1): a, b = b, a + b return b # Get valid input from the user while True: try: n = int(input('Please enter position of fibonacci sequence you wish to know: ')) if n >= 1: break print('Please enter a positive integer.') except ValueError: print('That\'s not a valid integer—try again!') # Calculate and print the result print(get_fibonacci(n))
Bonus Tips
- Generator for Sequences: If you ever need to generate multiple Fibonacci numbers, a generator function is super memory-efficient:
def fibonacci_generator(): a, b = 1, 2 while True: yield a a, b = b, a + b - Memoization for Repeated Calls: If you’re going to call the function multiple times with the same
n, memoization (caching results) can speed things up. Python’sfunctools.lru_cachemakes this trivial:
Note: This recursive approach is elegant but less efficient for very largefrom functools import lru_cache @lru_cache(maxsize=None) def get_fibonacci(n): if n == 1: return 1 elif n == 2: return 2 return get_fibonacci(n-1) + get_fibonacci(n-2)ncompared to the iterative method we used earlier.
内容的提问来源于stack exchange,提问作者savedashaggy

