A few minor tips on making the code more compact:
Remove unneeded variables/initializations. In particular your t
variable doesn't need to be initialized outside the loop since its value is always set within the loop before it's used.
The run
variable can also be eliminated; make the loop while True
and use a break
to escape it when you're done.
Instead of doing text.isdigit()
just do the int
conversion inside a try
block.
Combine your two "Try again" cases into a single block of code rather than repeating yourself.
With those changes the code looks like:
# Init previous two values of Fibonacci sequence
prev_2 = 1
prev_1 = 0
# Run while loop to prompt user enter Fibonacci number
while True:
try:
t = int(input('Enter the next Fibonacci number >'))
if t != prev_2 + prev_1:
raise ValueError('not the next Fibonacci number!')
if t > 50:
print('Well done')
break
# move to next value in the sequence
prev_2, prev_1 = prev_1, t
except ValueError:
print('Try again')
break
A larger tip on improving the code would be to separate the two distinct tasks the code is doing: computing the Fibonacci sequence up to 50, and quizzing the user on it. Here's how I might write that:
# Init Fibonacci sequence up to first value past 50 (shfifty-five)
fib = [0, 1]
while fib[-1] <= 50:
fib.append(fib[-2] + fib[-1])
# Prompt the user for all those values (after the initial 0, 1)
for n in fib[2:]:
try:
if int(input('Enter the next Fibonacci number >')) != n:
raise ValueError('not the next Fibonacci number!')
except ValueError:
print('Try again')
break
else:
print('Well done')
Now the code is in two smaller parts that are each a lot simpler than the previous version -- the first few lines compute the Fibonacci sequence in a very straightforward way, and the rest of the code simply iterates over the sequence and checks the input against it.
In a larger project you'd probably take these two "chunks" of code and define them as functions (you'd have one function that generates the sequence and another that handles the quizzing), but even within a function it's valuable to think about how you can break a problem does into distinct simple parts (and once you've done that, the next step of refactoring it into smaller functions becomes easy).