1

I am having trouble writing a program to repeat this program. I want to ask them if they want to repeat (yes or no). If they say yes it repeats the whole program. This is what I have so far:

sentence=input("Please enter sentence(s)")
words = sentence.split()
number_of_words = len(words)
counter=0
for x in sentence:
    if x in "!?.":
        counter=counter+1
print("There is "+str(counter)+" sentences and " + str(number_of_words) + "  words")
jmd_dk
  • 12,125
  • 9
  • 63
  • 94
Jasmine Lin
  • 13
  • 1
  • 1
  • 3
  • I don't see anything here about asking the user to repeat the program. Where are you having trouble? – user812786 Dec 28 '16 at 16:31
  • 1
    Have you tried wrapping your program with a [while loop](http://stackoverflow.com/documentation/python/237/loops/5520/while-loop#t=201612281630269780609)? – Cache Staheli Dec 28 '16 at 16:32

2 Answers2

3

A good way of organizing your code is to put your main program into a function called main() or similar:

def main():
    sentence = input("Please enter sentence(s): ")
    num_words = len(sentence.split(' '))

    counter = 0
    for x in sentence:
        if x in "!?.":
            counter += 1

    print("There are", counter, "sentences and", num_words, "words.")

Then, underneath this, you write your code for repeating the function:

while True:
    main()
    if input("Repeat the program? (Y/N)").strip().upper() != 'Y':
        break
FlipTack
  • 413
  • 3
  • 15
2

Put the whole code in a while True loop and at the end ask the user if they want to repeat. If not, break the loop.

Something like this:

while True:
    sentence=input("Please enter sentence(s)")
    words = sentence.split()
    number_of_words = len(words)
    counter=0
    for x in sentence:
        if x in "!?.":
            counter=counter+1
    print("There is "+str(counter)+" sentences and " + str(number_of_words) + "words")
    if input('Do you want to repeat(y/n)') == 'n':
        break
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Nir Kogman
  • 131
  • 2
  • 8