需要有关循环的代码的帮助

时间:2018-11-07 20:09:05

标签: python-3.x

print("Descriptive Analytics:\n\t*1. Summary\n\t*2. Time Series\n\t*3. 
Trend Lines\n\t*4. Moving Averages\nPredictive Analytics:\n\t*5.Linear 
Regression Model\n\t*6.Non Linear Regression Model")

while True:
try:
    choice = (input("Step 2: Please choose an option:"))
except ValueError:
    print("Sorry, you've entered an invalid input. Please try again!")
if choice in ("1","2","3","4","5","6"):
        break
if choice == "1":
   print("Descriptive Analytics: Summary")
elif choice == "2":
   print("Descriptive Analytics: Time Series")
elif choice == "3":
   print("Descriptive Analytics: Trend Lines")
elif choice == "4":
   print("Descriptive Analytics: Moving Averages")
elif choice == "5":
   print("Predictive Analytics: Linear Regression Model")
elif choice == "6":
   print("Predictive Analytics: Non Linear Regression Model")

有人可以发现此代码中的错误吗?到目前为止,循环有效,但无法打印“抱歉,您输入的行无效。请重试!

1 个答案:

答案 0 :(得分:0)

您需要使用适当的缩进级别,并确保您的代码在else块而不是except块中执行

while True:
    try:
        choice = (input("Step 2: Please choose an option:"))
    except ValueError:
        print("Sorry, you've entered an invalid input. Please try again!")
    else:
        if choice == "1":
           print("Descriptive Analytics: Summary")
        elif choice == "2":
           print("Descriptive Analytics: Time Series")
        elif choice == "3":
           print("Descriptive Analytics: Trend Lines")
        elif choice == "4":
           print("Descriptive Analytics: Moving Averages")
        elif choice == "5":
           print("Predictive Analytics: Linear Regression Model")
        elif choice == "6":
           print("Predictive Analytics: Non Linear Regression Model")
        if choice in ("1", "2", "3", "4", "5", "6"):
            break