Here are some codes I did that tried to "repeatedly reads numbers until the user enters "done", but I don't understand why I need "While true" statement to make the loop infinite in order to run "if" statement. If I don't put "While true" statement and run the code, the computer will say "'break' is out of loop" which confuses me. I also want to know under what circumstances should we use "while true" in a loop? Please help. Thanks!
count=0
total=0
while True:
value=input("Enter a value:")
if value =="done":
break
try:
num=float(value)
except:
print("Bad input")
continue
count=count+1
total=total+num
print(total,count,total/count)
while condition
repeats the code inside, while the condition
is True
.
In while True
, the given condition is True
itself, so it repeats forever on and on until in breaks(break
).
break
means 'Get out of the very outside loop', so if you use break
outside a loop, it gives you an error.
+) This is just a tip but you can use count += 1
as for count = count + 1
! the same goes for total = total + num
too, like total += num