-2

I am practicing while loops and i am trying to come up with different formula that i used in for loops to do the same and i want to know if its possible to do it.

Database=["Akaki","Salome","Giorgi","Lasha","Beqa"]    
x=0    
for i in Database:  
  while x<len(Database):    
    x+=1  
    print(f"{x} {i}")  

This is what I tried and answer I got is

1 Akaki  
2 Akaki  
3 Akaki  
4 Akaki  
5 Akaki

And I want to numerate it correctly with correct names in for loops. I have this formula to do it:

Database= ["Akaki","Salome","Giorgi","Lasha","Beqa"]  
for i in range(len(Database)):  
  print(i,Database[i])

That does the job but can I do it with while loops as well?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Does this answer your question? [Accessing the index in 'for' loops](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Jorge Luis Mar 21 '23 at 09:48

2 Answers2

0

It is possible:

x=0    
while x<len(Database):      
    print(f"{x} {Database[x]}")
    x+=1

You don't need two nested loops in your first example.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

The Pythonic way is to use enumerate. It returns a default 0-based index and a value for each item in the iterable:

Database = ['Akaki', 'Salome', 'Giorgi', 'Lasha', 'Beqa']    
for i, value in enumerate(Database, start=1):
    print(f'{i} {value}')  

Output:

1 Akaki
2 Salome
3 Giorgi
4 Lasha
5 Beqa
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251