1

I have an assignment that states...

Create a condition looop that will ask the user for input of two numbers. The numbers should be added and the sum displayed. The loop should also ask the user if he or she wishes to perform the operation again. If so, the loop should repeat, otherwise the loop should terminate.

This is what I have come up with...

n1=input('Please enter your first number: ')
print "You have entered the number ",n1,""
n2=input('Pleae enter your second number: ')
print "You have entered the number ",n2,""
total=n1+n2
print "I will now add your numbers together."
print "The result is:",total

y = raw_input('Would you like to run the program again? y=yes n=no')
print'The program will now terminate.'

y='y'
while y=='y':
print 'The program will start over.'

When you run this the first part of the program will work but when it ask you to run again it will continuously state "The program will start over."

How do I allow for the user to input wether or not they would like to start the program over and how do I word this so that it will loop?

2
  • could you give us the whole loop code ? Commented Feb 14, 2012 at 11:37
  • 1
    look at this example: wiki.python.org/moin/WhileLoop Commented Feb 14, 2012 at 11:38

2 Answers 2

4

You have placed the loop in wrong place. Need to do something like this:

y = 'y'

while y == 'y':
    # take input, print sum
    # prompt here, take input for y

At first the value of y is 'y', so it will enter the loop. After first input set prompt user to input y again. If they enter 'y' then the loop will execute again, otherwise it will terminate.

An alternate way is to make an infinite loop and break that if anything other than 'y' is entered. Something like this

while True:
    # take input, print sum
    # prompt here, take input for y
    # if y != 'y' then break
Sign up to request clarification or add additional context in comments.

Comments

1

You need to put that while y=='y' at the beginning of your script.

Even though I wouldn't call y a variable that could be either 'n' or 'y',
Example:

def program():
    n1 = input('Please enter your first number: ')
    print "You have entered the number ",n1,""
    n2 = input('Pleae enter your second number: ')
    print "You have entered the number ",n2,""
    total = n1+n2
    print "I will now add your numbers together."
    print "The result is:",total


flag = True
while flag:
    program()
    flag = raw_input('Would you like to run the program again? [y/n]') == 'y'

print "The program will now terminate."

Even though it should be said that in this way you will terminate the program if the user insert anything that is not 'y'.

Comments

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.