In: Computer Science
"PYTHON"
Write some code " USING PYTHON" to keep reading numbers from the user until the users enters a negative number. The program then prints out:
a) the sum of all the numbers
b) the average of all the numbers
c) the max of the numbers
d) the min of the numbers
Note we did not cover lists (array) so you will not use them in this problem.
Finally, ask the user for their name, then print their name as many times as the max value (determined earlier) . Note, I want you to use a for loop for this part.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
EDIT: updated the code to include counters for printing name
#code
def main():
#initializing sum, count, average to 0
sum=0
count=0
avg=0
#initializing two variables to store max and
min values to None
maxVal=None
minVal=None
#looping indefinitely
while True:
#reading a
number
num=int(input("Enter a number (negative to end):
"))
#exiting the loop if
the number is negative
if
num<0:
break
#adding num
to sum
sum+=num
#updating
count
count+=1
#if maxVal is not
initialized or if it is greater than current maxVal, updating
#maxVal to current
value
if
maxVal is None or num>maxVal:
maxVal=num
#doing the same for
minVal, checking if num is less than minVal
if
minVal is None or num<minVal:
minVal=num
#after exiting loop, if count is above 0,
finding average
if count>0:
avg=sum/count
#printing stats
print("Sum of
numbers:",sum)
print("Average of
numbers:",avg)
print("Maximum of numbers:",
maxVal)
print("Minimum of numbers:",
minVal)
#reading name
name=input("Enter your name:
")
#using a for loop, printing name maxVal
times
for i in
range(maxVal):
print(str(i+1)+". "+name)
#invoking main()
main()