Need help for python, I cant get it to calculate

Question:

I really don’t know what I am doing wrong here but whenever I run the code the output doesn’t calculate the variable and only sets it to 0.0

total = 0.0
num1 = 0.0
average = 0.0

while True:
    input_num = input("Enter a number ")

    if input_num == 'done':
        break

    try:
        num = float(input_num)
    except ValueError:
        print("Invalid Input")
        continue

        total = total + num
        num1 = num1 + 1
        average = total / num1

print("total: ", total)
print("count: ", num1)
print("average: ", average)

I got the following after running the code
[Image of code run]: (https://imgur.com/a/lEz6ibh)

Asked By: LateNightGame's

||

Answers:

Your code isn’t indented properly, so the code after continue never gets executed. To get it to work, unindent the lines after continue:

total = 0.0
num1 = 0.0
average = 0.0

while True:
    input_num = input("Enter a number ")

    if input_num == 'done':
        break

    try:
        num = float(input_num)
    except ValueError:
        print("Invalid Input")
        continue

    total = total + num
    num1 = num1 + 1
    average = total / num1

print("total: ", total)
print("count: ", num1)
print("average: ", average)
Answered By: PythonDudeLmao

This should work.

num_list = []

while True:
    input_num = input("Enter a number ")
    if input_num == 'done':
        total = sum(num_list)
        average = total / len(num_list)
        break
    num_list.append(float(input_num))


print(f"Average: {average}")
print(f"Total: {total}")
print(f"num_list: {num_list}")
Answered By: Flow
total = 0.0
num1 = 0.0
average = 0.0

while True:
    input_num = input("Enter a number ")

    if input_num == 'done':
        break

    try:
        num = float(input_num)
        total = total + num
        num1 = num1 + 1
        average = total / num1
    except ValueError:
        print("Invalid Input")
        continue

print("total: ", total)
print("count: ", num1)
print("average: ", average)

Your code to calculate values should be inside the try block rather than the except block otherwise they are never executed.

Answered By: asultan904
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.