简体   繁体   English

为什么会出现语法错误(python数字检查功能)?

[英]Why am I getting a syntax error (python number checking function)?

I've written this function in Python, which is designed to check if any list element is a number, and return that list element if it is. 我已经用Python编写了此函数,该函数旨在检查是否有任何列表元素是数字,如果有则返回该列表元素。 This is the code: 这是代码:

def check_for_number(list):
x = 0
print(isinstance(list[x], (int, float))
true_or_false = False
for x in range(len(list)-1):
    if isinstance(list[x], (int, float) == True):
        true_or_false = True
        num = list[x]
    x += 1
print(true_or_false)
return true_or_false 
return num

Whenever I try to run it I get a syntax error saying that the colon at the end of the if statement is an 'unexpected token', and every item in the last two lines of the if statement gives the same unexpected token error. 每当我尝试运行它时,我都会收到一个语法错误,指出if语句末尾的冒号是“意外令牌”,并且if语句最后两行中的每个项目都给出相同的意外令牌错误。 I've checked the indentation and I can't see anything wrong with it, what am I missing? 我已经检查了缩进,但看不到任何错,我缺少什么? Thanks. 谢谢。

You just have to indend the code of your function and fix the if isinstance(list[x], (int, float) == True): part and close the paranthesis of your first print statement. 您只需要添加函数代码并修复if isinstance(list[x], (int, float) == True):部分并关闭第一个print语句的括号。

def check_for_number(list):
    x = 0
    print(isinstance(list[x], (int, float)))
    true_or_false = False
    for x in range(len(list)-1):
        if isinstance(list[x], (int, float)) == True:
            true_or_false = True
            num = list[x]
        x += 1
    print(true_or_false)

    # Decide what you want to return here
    return true_or_false 
    return num

If you are interested in improving your code, remove the == True part, as has been stated in the comments as well. 如果您有兴趣改进代码,请删除== True部分,如注释中所述。 And from your question I assume you want to return fals, if true_or_false is False or num otherwise. 从您的问题中,我假设您要返回fals,如果true_or_falseFalsenum则为。

If you add a break statement in the loop, the loop will be exited when you have found the first number. 如果在循环中添加break语句,则在找到第一个数字时将退出循环。 So your computer does not need to loop through the complete list and this can save you some execution time. 因此,您的计算机不需要遍历完整列表,因此可以节省一些执行时间。

I also expect, your x += 1 statement is not what you want to do. 我也希望您的x += 1语句不是您想要执行的操作。 The for ... in range ... loop will increase your x in each cycle. for ... in range ...循环将在每个循环中增加x。 That is why x += 1 will make your code skip every second list element. 这就是为什么x += 1将使您的代码每隔第二个列表元素跳过一次。 You also will not need to declare x first. 您也不需要先声明x。

def check_for_number(list):
    print(isinstance(list[x], (int, float)))
    true_or_false = False
    for x in range(len(list)-1):
        if isinstance(list[x], (int, float)):
            true_or_false = True
            num = list[x]
            break
    print(true_or_false)

    if (true_or_false):
        return num
    else:
        return False

Concering your question about the unnecessary == True part: 关于您不必要的== True部分的问题:

The if statement is working like the following pseudo code. if语句的工作方式类似于以下伪代码。

if (CONDITION) == True then do something special

So, if you add a == True , python would check it like so: 因此,如果添加== True ,python将像这样检查它:

if (valeu == True) == True then do something special

which is the same as: 与以下内容相同:

if (value) == True then do something special

Here is a solution using a list comprehension. 这是一个使用列表推导的解决方案。 It checks each element against the Number abstract base class. 它根据Number抽象基类检查每个元素。 It will return a list of numbers, since there might be more than 1 numeric elelement. 它将返回一个数字列表,因为可能有不止1个数字元素。

import numbers

def get_numbers(l):
    return [x for x in l if isinstance(x, numbers.Number)]

example: 例:

>>> l = ['1', 4.0, 'abc', 'XYZ', 'test', 5]
>>> nums = get_numbers(l)
>>> print(nums)
[4.0, 5]

Python is tab-sensitive and intolerant of errors in this regard. Python在这方面对制表符敏感,并且不容出错。 I'm also seeing an instance of an unmatched parenthesis on line 6. Try the following and you might get a more informative error on what to fix next: 我还在第6行上看到一个括号不匹配的实例,请尝试以下操作,您可能会在接下来要解决的问题上得到更多的提示信息:

def check_for_number(list): 
    x = 0 
    print(isinstance(list[x], (int, float))
    true_or_false = False 
    for x in range(len(list)-1):
        if isinstance(list[x], (int, float) == True): # missing a parenthesis to close isinstance. 
        # "== True" is unnecessary because isinstance() will resolve to True or False
            true_or_false = True 
            num = list[x]
            x += 1 
            print(true_or_false) 
            return true_or_false 
    return num # this will result in unexpected behavior...
        # ...because num will not be defined if this line is reached.
        # Either the return inside the if will finish the method or num will never be defined.

It's a bit ambiguous how some of that should be indented because I can't tell what you're trying to do. 缩进其中的某些位有点模棱两可,因为我不知道您要做什么。

If you're trying to return to values, consider returning a list or a dictionary containing the values. 如果尝试返回值,请考虑返回包含值的列表或字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM