
To stop the execution of our program we can use the exit() function that belongs to the Python sys module. We want to exit the program with a clear message for our user if something different that a number is passed as input to the program. ValueError: invalid literal for int() with base 10: 'not_a_number'Ī user of our program wouldn’t know what to do with this error… Number_of_terms = int(input("How many terms do you want for the sequence? ")) So, let’s move the function before the line in which we call it and see what happens: number_of_terms = int(input("How many terms do you want for the sequence? ")) We need to make sure the function is defined before being used. We have defined the function we are calling so why the error?īecause we are calling the function calculate_nth_term before defining that same function. NameError: name 'calculate_nth_term' is not defined number_of_terms = int(input("How many terms do you want for the sequence? ")) We assign the values to the (n-2)th and (n-1)th terms so we can use them in the next iteration of the while loop to calculate the value of the nth term. Assign the value of the nth terms to the (n-1)th terms.Assign the value of the (n-1)th terms to the (n-2)th terms.Calculate the nth term as the sum of the (n-2)th and (n-1)th terms.Here is the meaning of the variables n1, n2 and n: Variable Meaning n nth term of the sequence n1 (n-1)th term of the sequence n2 (n-2)th term of the sequence To simplify things our Python program will print the sequence starting from the number 1. That’s pretty much everything we need to know to create a Python program that generates this sequence. The sequence starts with 0 and 1.īelow you can see the first 10 numbers in the sequence: In the Fibonacci sequence every number is the sum of the two preceding numbers in the sequence. We will go through the creation of a program that prints the Fibonacci sequence and while doing that we will see 4 different ways in which the Python NameError can appear.įirst of all, to understand the program we are creating let’s quickly introduce the Fibonacci sequence. Conclusion A Simple Program to Print the Fibonacci Sequence.Order Really Counts in a Python Program.

A Simple Program to Print the Fibonacci Sequence.
