3

I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. I also would like to use a break statement to exit the while loop.

My Incorrect Work:

y = "\n"
total = 0
k = 0

while True:
    x = input("Enter your number here: ")
    x = float(x)
    total = total + float(x)
    k = k + 1
    if type(x) != int:
        print(total/k)
        break
blackraven
  • 5,284
  • 7
  • 19
  • 45
Krys
  • 31
  • 2
  • 1
    You need to check if the input is blank _before_ you call `float()` on it. – John Gordon Jul 30 '22 at 01:57
  • Welcome to Stack Overflow. Please read the [tour] and [ask]. It would help if you could describe what is incorrect in your current code (error, with which message? incorrect output?) – Pac0 Jul 30 '22 at 01:59

4 Answers4

1

Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.

Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:

total = 0
k = 0

while True:
    x = input("Enter your number here: ")
    try:
        total += float(x)
        k += 1
    except ValueError:
        if k > 0:    #to avoid division by zero
            print("Average: ", total/k)
        break

Output:

Enter your number here:  3
Enter your number here:  4
Enter your number here:  5
Enter your number here:  
Average:  4.0
blackraven
  • 5,284
  • 7
  • 19
  • 45
  • Thankyou Perpetual Student. I used your code and tried with the same values 3,4,5 but it resulted in 3. Also, I tried with 1.5,2 and 2.5, then enter and it gave 1.5 as a value. Not exactly sure how this is happening – Krys Jul 30 '22 at 10:09
  • yes, because the error happened after the step k+=1, so there was an additional number (wrongly) added to k.. I've updated my answer pls take a look – blackraven Aug 01 '22 at 02:34
  • so is this working for you now? – blackraven Aug 02 '22 at 20:08
0

Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.

total = 0.0
k = 0.0

while True:

    x = input("Enter your number here: ")
    
    if (x == " "):  # Check for a blank line entry here before attempting to convert to float
        print("Average is:", (total/k))
        break

    x = float(x)

    total = total + float(x)

    k = k + 1

As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
  • Hello NoDakker! Thank you so much for the help. I've tried you're program but it says "ValueError: could not convert string to float: '' I tried the values 1.5, 2 and 2.5 to get the average of 2 to no avail. – Krys Jul 30 '22 at 10:05
  • You are not checking for empty line, you are checking for a line with only one space. – Uncle Dino Jul 30 '22 at 11:41
0

You are immediately casting the value of x that is inputted to a float. So,

if type(x) != int

always is true, meaning the loop breaks after one iteration every time.

Ribs30
  • 13
  • 3
0

Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.

Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number). When a new line is entered, your program should do one of the two possible scenarios:

  • when an empty line is entered: print result & exit (break)
  • else (assume a number is entered): add number to total

No third option is specified, so for now, let's assume that every line will either be an empty line or a number. Will expand it later.

After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:

initialize_variables_total_and_count

while True:
   read_line
   decide_what_to_do:
      # in case line was a number
      convert_line_to_float
      add_float_to_total
      increment_count
   other_case:
      # empty line was entered
      calculate_and_print
      break

With only two options, you only need to decide once what to do. You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).

It's simpler to check for the line being empty with if line_entered == "":. In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.

Checking if a string (the entered line) can be converted to a float is a bit harder. There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. There are other ways too, but this is the simplest - see this question on the topic.
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.

You can avoid putting both cases into an if-else block by using break or continue. (technicly, you never need to use break or continue, all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break, do run = False). You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).

So an example implementation: (testing for == "", not using unstructured control flow)

total = 0
count = 0
run = True
while run:
    line = input("Enter your number here: ")
    if line == "":
        print(total / count)
        run = False
    else:
        total += float(line)
        count += 1

I also renamed k to count, x to line and used in-place addition operators.

Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):

total = 0
count = 0
while True:
    line = input("Enter your number here: ")

    try:
        # order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
        total += float(line)
        count += 1
    except:
        print(f"Average is: {total / count}")
        break

Here I removed the run variable, and used a format string to print a bit fancier.

And an example using both continue and break:

total = 0
count = 0
while True:
    line = input("Enter your number here: ")
    if line != "":
        total += float(line)
        count += 1
        continue

    print(f"Average is: {total / count}")
    break

You can fancy it a bit with adding more error handling - use three cases:

  • user entered empty line: print & exit
  • user entered a number: add to total
  • user entered something else: ignore line, but tell user what to do

I only provide one example implementation for this, but as you can see, it can be implemented in many ways.

total = 0
count = 0

# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")

while True:
    line = input("Enter your number here: ")
    if line == "":
        print(f"Average is: {total / count}")
        break
    else:
        try:
            total += float(line)
            count += 1
        except ValueError:
            print("You should enter a number or an empty line to calculate & exit!")
Uncle Dino
  • 812
  • 1
  • 7
  • 23