-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacciSequence.py
More file actions
70 lines (57 loc) · 2.29 KB
/
fibonacciSequence.py
File metadata and controls
70 lines (57 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import sys
print('''Fibonaccci sequence begins with 0 and 1, and the next number is the sum of the previous two numbers.
The seuence continues forever:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987...''' )
while True: # Main program loop.
while True: # Keep asking until the nters valid input.
print('Enter he Nth fibonacci number you wish to')
print('calculate (such as 5, 50, 1000, 9999), or QUIT to quit:')
response = input('>').upper()
if response == 'QUIT':
print('Thanks for playing!')
sys.exit()
if response.isdecimal() and int(response) != 0:
nth = int(response)
break # Exit the loop when the user enters a valid number.
print('Please enter a number greater than 0, or QUIT.')
print()
# Handle the special cases if the user entered 1 or 2:
if nth == 1:
print('0')
print()
print('The #1 Fibonacci number is 0.')
continue
elif nth == 2:
print('0, 1')
print()
print('The #2 Fibonacci number is 1.')
continue
# Display warning if the user entered a large number:
if nth >= 10000:
print('WARNING: this will take a while to display on the')
print('screen. if you want to quit this program before it is')
print('done, press Ctrl-C')
input('Press Enter to begin...')
# calculate the nth Fibonacci number:
secondToLastNumber = 0
lastNumber = 1
fibNumbersCalculated = 2
print('0, 1, ', end='') # Display the first two fibonacci numbers.
# Display all the later numbers of the fibonacci sequence:
while True:
nextNumber = secondToLastNumber + lastNumber
fibNumbersCalculated += 1
# Display the next nnumber in the sequence:
print(nextNumber, end='')
# Check if we've found the Nth number the user wants:
if fibNumbersCalculated == nth:
print()
print()
print('The #', fibNumbersCalculated, 'fibonacci',
'number is ', nextNumber, sep='')
break
# Prit a comma in between the sequence numbers:
print(', ', end='')
# Shift the last two numbers:
secondToLastNumber = lastNumber
lastNumber = nextNumber