2

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: '))
2
  • input ('Enter value {}'.format(_) Commented Jan 10, 2019 at 14:09
  • @SuryaTej, that's a reasonable solution if the OP is satisfied with just printing the digits of _. But if they want to literally print the words "first", "second", etc, then that's not something that format can do on its own. Commented Jan 10, 2019 at 14:10

1 Answer 1

6

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".

Sign up to request clarification or add additional context in comments.

1 Comment

The num2words package is more specifically designed for this (e.g. num2words(42, to='ordinal') -> forty-second).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.