I want to add several numbers together and get the average in the end when I write 'done'; but this code automatically gets the average every time and when I finish the loop it just exits the program and doesn't show the result. What can I do to print the average of numbers at the last?
moadel=0
while True :
nomre =input('nomreye khod ra vared kon :')
if nomre == 'done' :
break
else:
nomre=float(nomre)
moadel=(moadel nomre)/5
print(moadel)
CodePudding user response:
you can take your print out of the while loop
moadel=0
while True :
nomre =input('nomreye khod ra vared kon :')
if nomre == 'done' :
break
else:
nomre=float(nomre)
moadel=(moadel nomre)/5
print(moadel)
print('final:', moadel)
or you can put it also inside de if nomre == 'done' :
before the break
moadel=0
while True :
nomre =input('nomreye khod ra vared kon :')
if nomre == 'done' :
print('final:', moadel)
break
else:
nomre=float(nomre)
moadel=(moadel nomre)/5
print(moadel)
CodePudding user response:
Try this. It makes a list and then gets the sum and length:
nums = []
while True:
num = input('Enter a number: ')
if num == 'done':
break
else:
nums.append(float(num))
print('Sum:', sum(nums)) # Comment out if you want
print('Length:', len(nums)) # Comment out if you want
print('Average:', sum(nums) / len(nums))
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: done
Sum: 10.0
Length: 4
Average: 2.5
CodePudding user response:
moadel = 0
quantity = 0
while True:
nomre = input("nomreye khod ra vared kon: ")
if nomre == "done":
print(moadel/quantity)
break
else:
moadel = float(nomre)
quanity = 1
You can register how many numbers you had enter in the input with quanity, so no matter how many numbers you enter, you always get the average at the end. The moadel will be the sum of all the numbers you established on the input. You only want to print the average when you write "done", so the print must be inside that condition before breaking the while loop.