Switching words in a for-loop string

Viewed 97

In the code below, is there are way that I could change the 'nth' in the for loop into the particular term I am considering.

For example: Enter a value for the first term, Enter a value for the second term, Enter a value for the third term, and so on. As opposed to the line 'Enter a value for the nth term' every time the loop runs.

for _ in range (n):
    total += float (input ('Enter a value for the nth term: '))
1 Answers

There's a library called Inflect that does almost exactly this.

inflect.py - Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.

import inflect
p = inflect.engine()

for x in range (n):
    total += float (input('Enter a value for the {} term: '.format(p.ordinal(x+1))))

Puts...

Enter a value for the 1st term: 
Enter a value for the 2nd term: 

And so on. There is also a numbers-to-words function you should take a look a - does the same thing but will actually put the word in english rather than "1st".

Related