Home > other >  Addition of python while averaging
Addition of python while averaging

Time:09-26

. Write a program to prompt the user for first to enter the Numbers, and then use the while loop repeatedly prompt the user for the Numbers, and add the Numbers to the running total, when the input the correct number, the program should print the average, this program should be how to write

CodePudding user response:

The code below
 
Def num_average () :
_sum=0 # calculation combined
Count=0 # statistical total input
While True:
Numerical (value=https://bbs.csdn.net/topics/input (" please enter exit input "q" to end the operation and print the average) : ")
If the value. The lower ()! '=' q:
N=float # (value) converts a string to a floating-point
_sum +=n
Count +=1
Elif value. The lower ()=='q' :
Print (f "is the sum of input for {_sum}, average for {_sum/count}")
Break

CodePudding user response:

reference 1st floor Hajo_ response:
code below
 
Def num_average () :
_sum=0 # calculation combined
Count=0 # statistical total input
While True:
Numerical (value=https://bbs.csdn.net/topics/input (" please enter exit input "q" to end the operation and print the average) : ")
If the value. The lower ()! '=' q:
N=float # (value) converts a string to a floating-point
_sum +=n
Count +=1
Elif value. The lower ()=='q' :
Print (f "is the sum of input for {_sum}, average for {_sum/count}")
Break



Code logic basic not too big problem, but robustness can improve it!

 
Def num_average () :
_sum=0 # calculation combined
Count=0 # statistical total input
While True:
Numerical (value=https://bbs.csdn.net/topics/input (" please enter exit input "q") : ")
If the value. The lower ()=='q' :
If count> 0:
Print (f "{_sum}, input the sum of the average of {_sum/count}")
Break

If the value. The lower ()! '=' q:
Try:
N=float # (value) converts a string to a floating-point (pay attention to the exception handling)
_sum +=n
Count +=1
Print (f "has the sum of the input current for {_sum}, the current average of {_sum/count}")
Except:
Print (" input is not a valid number, please input again!" )

Num_average ()
  • Related