0

I am trying to ask for user input once, but every time I run the code it asks you to enter a number twice in a row and only prints the sum of one of the first number you enter. Any solutions so I can get it to only ask once?

thesum=0.0
count=0
print('Welcome to Sum and Average Finder')
userinput=(float(input('Enter a Number or Hit Enter to Quit: ')))
while userinput !='':
    number=float(userinput)
    thesum+=number
    count+=1
    userinput=input('Enter a Number or Hit Enter to Quit: ')
    print('The Sum is',thesum)
    print('Avergae is',thesum/count)
martineau
  • 119,623
  • 25
  • 170
  • 301
John
  • 35
  • 1
  • 5
  • 4
    `userinput=(float(input('Enter a Number or Hit Enter to Quit: ')))` is in your code twice – JacobIRR Sep 23 '19 at 18:05
  • when i take out the 2nd line of userinput=input('Enter a Number or Hit Enter to Quit: ') it runs infinitely and when i use the break command it doesnt run at all? – John Sep 23 '19 at 18:10

2 Answers2

0

If I understand your question correctly, just change the while statement to an if statement and remove the second userinput line from your code to only ask the user once:

thesum=0.0
count=0
print('Welcome to Sum and Average Finder')
userinput=(float(input('Enter a Number or Hit Enter to Quit: ')))
if userinput !='':
    number=float(userinput)
    thesum+=number
    count+=1
    print('The Sum is',thesum)
    print('Avergae is',thesum/count)
vendrediSurMer
  • 398
  • 5
  • 15
0

A common way to do something like this is using while True: "infinite" loop and then breaking out of it when the user enter something indicating they want to stop:

thesum = 0.0
count = 0

print('Welcome to Sum and Average Finder')

while True:
    userinput = input('Enter a Number or Hit Enter to Quit: ')
    if userinput == '':
        break
    number = float(userinput)
    thesum += number
    count += 1
    print('The Sum is', thesum)
    print('Average is', thesum / count)

Your question kind of like Asking the user for input until they give a valid response in reverse. Note especially the part in the accepted answer about The Redundant Use of Redundant input Statements.

martineau
  • 119,623
  • 25
  • 170
  • 301