Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

How to do 3 part if statement in python?

Why the if statements doesn't work at the below? I just want if the values are number do the math, if the values are string except "Done" give me just "enter a number" warning and continue, if the value is "Done" finish the job and give me the answers.

quantity = 0
sum = 0
avg = 0
n = None


while n != "Done":
    try:
        n = int(input("Enter a value:
"))
        sum = sum + n
        quantity = quantity + 1
        avg = sum / quantity
    except:
        print("Enter a number!")

        if n =="Done":
            print("Process is Done!")
            break
            print("Sum : {}, Quantity : {}, Avg : {}".format(sum, quantity,avg))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

n = int(input("Enter a value: "))

Once you hit an Exception for invalid input for your int() cast, the "Done" value is never assigned to n. So, n == "Done" is effectively using the old value of n from the previous iteration or None if it's the first iteration.

Try the following:

quantity = 0
sum = 0
avg = 0
n = None
input_val = None

while input_val != "Done":
    try:
        input_val = input("Enter a value:
")
        n = int(input_val)
        sum = sum + n
        quantity = quantity + 1
        avg = sum / quantity
    except:
        print("Enter a number!")

print("Process is Done!")
print("Sum : {}, Quantity : {}, Avg : {}".format(sum, quantity,avg))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...