Home > database >  Enumerating a for loop, Python
Enumerating a for loop, Python

Time:07-17

I'm taking a python course for beginners and I'm already struggling with unclear instructions. What I need the program to print out is this:

How many Fibonacci numbers do you want? 7
1. 1
2. 1
3. 2
4. 3
5. 5
6. 8
7. 13

...but the course hasn't gone through enumerating yet and I can't get it to work. What I have is this:

pre_previous_fib = 0
previous_fib = 1
num = int(input("How many Fibonacci numbers do you want? ", ))

for n in range(1, num   1):
    if (n == 1):
        new_fib = n
    else:
        new_fib = pre_previous_fib   previous_fib
        pre_previous_fib = previous_fib
        previous_fib = new_fib
        print(new_fib)

I tried using another for loop to enumerate, but I end up with on error code as new_fib is not iterable.

CodePudding user response:

Just use your n, it already enumerate the iterations

for n in range(1, num   1):
    if n == 1:
        new_fib = n
    else:
        new_fib = pre_previous_fib   previous_fib
        pre_previous_fib = previous_fib
        previous_fib = new_fib

    print(f"{n}. {new_fib}")

If you enumerate on a list, use enumerate

values = 'jfujd'
for i, x in enumerate(values):
    print(i, x)

0 j
1 f
2 u
3 j
4 d

CodePudding user response:

Like the other answer already tells you, your loop variable already effectively enumerates your iterations. But if you really wanted to, you could:

num = int(input("How many Fibonacci numbers do you want? "))

prev = 0
for n, _ in enumerate(range(num), 1):
    if n == 1:
        this = 1
    else:
        this, prev = this prev, this
    print(f"{n}. {this}")

Demo: https://ideone.com/UUZ7ix

You're not really enumerating "the for loop", you are enumerating an iterable and passing its output to the two-argument for.

  • Related