Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop typical code
#1
Enter a number and then enter an other number add these numbers together and then ask if they want to add another number if they enter y ask them to enter number and keep add the number unitl the answer is N.

once the loop has been stopped , Display the total.

Thank you in advance.
Well below is my code/

num=int(input("enter a number: "))
total=num
again="y"
while again=="y":
    n=int(input("enter a another number: "))
    total=total+n
    nu=input("do you want to add a another number? (y/n) :  ")
    print("total is....",total)
else:
    print("total is",total)
break
Yoriz write Apr-30-2021, 01:23 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button
Reply
#2
break not being in a loop is a syntax error
The value of again is never changed, it needs changing when asking do you want to add a another number? (y/n) :, otherwise it will just continue to loop forever.

If you remove the break and fix the updating of again your code will function as required.
Reply
#3
You are close but you need to understand how break is used to break out of a loop. You want it inside the while loop and to be run only if the user does NOT want to add another number. You are also on the right track with the else: keyword but where is the if: to go with it???

If the logic is confusing you, write the process out in simple pseudo-code, then convert that to proper python...

Give it another try and post back if you're still stuck. Wall
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Typical beginner needing some help foxter00 1 2,616 May-08-2019, 11:46 PM
Last Post: michalmonday

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020