-1

When i run this code it doesn't have an output, and please can you explain the purpose of this code and give a line-by-line explanation of how it achieves its purpose.

def mystery(n):
    a, b = 0, 1
    while a < n
       print (a)
       a, b = b, a + b

I have also figured out how to make it output You add a line which is mystery(n) e.g. mystery(200)

I think it is like this:

• The first line defines a function with one parameter. The word “def” presents a function
definition. The function “def” must be followed by the function name e.g. mystery.

• The second line contains a multiple assignment. It is saying that the variable “a” is equal to 0 and “b” is equal to 1

• The function defines the value of “n”. On the third line “n” is undefined.

• The fourth line is to print (a)

• The fifth line makes

bud-e
  • 1,511
  • 1
  • 20
  • 31
  • 2
    Run the code. Notice the first few numbers it outputs. Put that in google. Enjoy ;) – georg Nov 07 '14 at 09:56
  • it is a Fibonacci algo http://stackoverflow.com/questions/15047116/a-iterative-algorithm-for-fibonacci-numbers – Padraic Cunningham Nov 07 '14 at 09:56
  • We had the same question here with the same mistake (a should be 1 initially not 0) some days ago. I just can't find it at the moment. – Klaus D. Nov 07 '14 at 10:25

3 Answers3

0

This code is a Fibonacci series generator upto n. The only error is the missing colon (:) after while statement. It starts with a=0 abd b=1: compares a < n; prints a if comparison generates True; assigns b to a and increments b by a; continues while loop until comparison generates False:

>>> def mystery(n):
...     a, b = 0, 1
...     while a < n:
...        print (a)
...        a,b = b,a+b
... 
>>> mystery (10)
0
1
1
2
3
5
8
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
0
# This is a method. 
# You can call this method to its logic. (sea last line)
# N would be the maximum value
def mystery(n):
    # This is the same as:
    # a = 0 Asign a to 0
    # b = 1 Asign b to 1
    a, b = 0, 1
    # Do the following until a is the same or bigger than n.
    while a < n:
       # Print the value of a
       print a
        # This is the same as:
        # temp = a
        # a = b
        # b = a + b
        # Example: a =1 and b =2
        # temp = a
        # a = 2
        # b = temp + 2
       a, b = b, a + b
# Calling the method with value 10
# you first have to call this before it executes
mystery(10)

Output:

0
1
1
2
3
5
8

This is called fibonacci

Vincent Beltman
  • 2,064
  • 13
  • 27
0

Instead of defining the value you want the Fibonacci sequence for inside of the code, why not change the code to:

def mystery(n):
   a, b = 0, 1
   while a < n:
      print (a)
      a, b = b, a + b
mystery(int(input("Insert A Number: ")))

This will allow the user to input a value of which, the Fibonacci sequence will be shown.

livibetter
  • 19,832
  • 3
  • 42
  • 42