Home > front end >  How to put 1) 2) 3) behind string automatically
How to put 1) 2) 3) behind string automatically

Time:07-13

Im trying to make a notetaking program. When i input run, I want:

1)Do homework
2)Do Dishes
3)Study

Attempt:

noteList = ['Do homework', 'do dishes', 'Study']
for i in noteList:
     print(i)

I have tried this but it doesnt give the desired output

noteList = ['Do homework', 'do dishes', 'Study']
    for i in noteList:
          for no in range(1,len(noteList) 1):
            print(str(no) ') '  i) 

CodePudding user response:

Consider utilizing enumerate:

>>> notes = ['Do homework', 'Do dishes', 'Study']
>>> for i, note in enumerate(notes, start=1):
...     print(f'{i}) {note}')
...
1) Do homework
2) Do dishes
3) Study

CodePudding user response:

You are iterating over the number of all elements in two nested loops. (for i in noteList: and for no in range(1,len(noteList) 1):) You only need one of these loops.

One option (which is kind of deprecated but closely related to your code) is to only iterate over your range() and then indexing your list inside the loop:

noteList = ['Do homework', 'do dishes', 'Study']
for no in range(1,len(noteList 1)):
    print(str(no) ') '  noteList[no-1]) 

The other, better option is to use the enumerate() over the list which returns the index and the element for each iteration. This results in the code which was already provided by the other answers:

noteList = ['Do homework', 'do dishes', 'Study']
for i, item in enumerate(noteList):
    print(str(i 1) ') '  item) 

CodePudding user response:

noteList = ['Do homework', 'do dishes', 'Study']
for i, item in enumerate(noteList):
    print("{}) {}".format(i 1, item))

CodePudding user response:

Think simple!

noteList = ['Do homework', 'do dishes', 'Study']

for i in range(len(noteList)):
    print(f'{i   1}){noteList[i]}')

CodePudding user response:

Use enumerate function while indexing to get the position of the element and the setting end=" ", makes sure that for each line space is added instead of a new line.

CODE

noteList = ['Do homework', 'do dishes', 'Study']
for index, element in enumerate(noteList, start=1):
    print(str(index)   ")"   element)

OUTPUT

1)Do homework 
2)do dishes 
3)Study

CodePudding user response:

noteList = ['Do homework', 'do dishes', 'Study']

for i in range(len(noteList)):
     print(f"{i   1}) {noteList[i]}")

Here, I loop the code i times where i is the number of Items in noteList. I use f which stands for Format to print i 1 as the starting number in a loop is 0. and print the Item at i position in noteList

  • Related