-3

I want to print a fibonacci sequence up to a random number. First I defined a variable (nterm) and assigned an integer number to it. It is actually the range to which the program will print a fibonacci sequence.
I want to do it by generating a random number, so I included the random library with import random. Here a random number is generated but I want to assign that number to nterms (a variable).
How can I assign a random number to nterms.

import random
print(random.randint(0,5))
 # Here a random number should be generated and should be used as nterms           

    n1 = 0
    n2 = 1
    count = 0
    if nterms <= 0:
       print("Please enter a positive integer")
    elif nterms == 1:
       print("Fibonacci sequence upto",nterms,":")
       print(n1)
    else:
       print("Fibonacci sequence upto",nterms,":")
       while count < nterms:
           print(n1,end=' , ')
           nth = n1 + n2
           n1 = n2
           n2 = nth
           count += 1


For example: the random number generated is 5 so it should be equal to nterms.
If nterms = 5 the expected output should be 0 , 1 , 1 , 2 , 3 ,

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Ijlal Hussain
  • 390
  • 1
  • 5
  • 16

2 Answers2

1

In your code you are not assigning any value to nterms. You should assign it like the following:

nterms = random.randint(0,5)
Josef Ginerman
  • 1,460
  • 13
  • 24
0
nterms = random.randint(0,5)

This is simply how you can assign a random number in variable and pass it later. Any more questions, let me know. edit:

Like patrick said, the format of this is nterms =random.randint(lowestvalue,biggestvalue)

So you can add the range of the numbers you want to test with, in that case you do not have to check if it is less than zero in your code,

  if nterms <= 0:
       print("Please enter a positive integer")

because it will never be less than zero, if you enter two positive numbers as the lowest and biggest values. :)

Arka Mallick
  • 1,206
  • 3
  • 15
  • 28