首页 > 解决方案 > elif a=="no": ^ SyntaxError: 无效语法

问题描述

这是我为我的代码得到的错误我似乎无法找到如何解决它

File "C:\Users\mayar\Desktop\final edge project\execute_html.py", line 19
    elif a=="no":
    ^
SyntaxError: invalid syntax

代码 -

import codecs
import subprocess
import os

while (True):
    corona = input("Do you want to know more about Coronavirus-COVID-19?                                                             answer in yes/no format \n")
    if corona== "yes":
        url = "CORONAVIRUS.htm"
#Python executes code following the try statement as a “normal” part of the program
    try:
        os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
    except AttributeError:
        try:
                subprocess.call(['open', url])
        except:
                print('Could not open URL')
        break
    elif a=="no":
       print("Have a nice day!")
    else:
        print("Enter either yes/no")

标签: python

解决方案


您需要elif直接在if. elif在 if 和以下s之间不能有任何其他代码行。您可能弄乱了代码中的缩进。您可以编辑您的代码,try except使其必须包含在第一if条语句中,然后它将起作用。

正确的代码 -

import codecs
import subprocess
import os

while (True):
    corona = input("Do you want to know more about Coronavirus-COVID-19?                                                             answer in yes/no format \n")
    if corona== "yes":
        url = "CORONAVIRUS.htm"

        try:
            os.startfile(url)
    #The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
        except AttributeError:
            try:
                    subprocess.call(['open', url])
            except:
                    print('Could not open URL')
            break
    elif corona=="no":
       print("Have a nice day!")
    else:
        print("Enter either yes/no")

推荐阅读