除了声明之外,这有什么问题? Python 3.4.3

时间:2016-02-19 01:56:11

标签: python except

代码一直有效,直到我尝试使用except语句处理ValueError。返回无效的语法回溯。

def write():
    filename = input('Please Enter the File name:') + '.txt';
    with open (filename, "a") as f:
        while True:
            a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
            a = str (a)
            b1 = float (b)
            f.write (a+','+ b+ '\n');
            except ValueError:
                continue
            loop = input ('Do you want to add anything else y/n:')
            if loop == 'n':
                break

2 个答案:

答案 0 :(得分:2)

我的代码中没有看到try语句。你可能想要这样的东西。有关更多示例,请参阅docs

while True:
    try:
        a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
        a = str (a)
        b1 = float (b)
        f.write (a+','+ b+ '\n');
    except ValueError:
        continue

答案 1 :(得分:0)

你需要一个try语句才能有一个except语句。

def write():

    filename = input('Please Enter the File name:') + '.txt';
    with open (filename, "a") as f:
        while True:
            try:     #added try statement
                a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
                a = str (a)
                b1 = float (b)
                f.write (a+','+ b+ '\n');
            except ValueError:
                continue
            loop = input ('Do you want to add anything else y/n:')
            if loop == 'n':
                break