简体   繁体   中英

Basic Python syntax error for greater/less than symbols

I am teaching myself how to code python. In this problem I kept on receiving syntax errors for my 0 greater than b less or equal to x line. Saying it was an invalid syntax. Why is this the case?

I could use the range(x) function to get a list of numbers but this way seems like it should be quicker and easier. Thanks for the help

def factorial(x):
    if x==0:
        return 1
    elif x>0:
        b=int
        total = 1
        for 0<b<=x:
            total*=b
        return total

Either you mean if , not for (in which case the solution is to replace for with if ) or else you are hoping that your code will iterate over, maybe, all integers b in the given range (in which case the answer is that for doesn't work like that; you need to construct an explicit object to iterate over, eg using range ).

I suspect the latter, since you haven't really given b a value. (Well, actually, you have, but probably not the way you intended. You have made b equal to an object that represents the integer type . If that doesn't make sense to you, ignore it for now.)

I'm afraid Python isn't clever enough for you to say " b is an integer; please do something for each possible value between 0 and x " -- which I think is what you were hoping for. But, eg, range(1,x+1) is an object representing all the integers from 1 (inclusive) to x+1 (exclusive), and you can use a for loop to do something for each of those.

for must be followed by an iterable. The correct syntax is:

for variable in iterable:

In your case you should generate some iterable that goes from 1 to x . To do this you should use range(1,x+1) (Or xrange if you are in python 2)

Your code should look like this:

for b in range(1, x+1):
    total *= b

Also, b = int is not what you think. This is not a declaration, it makes b not a variable of type int but actually the type itself. In python you can't restrict a variable to keep being of certain type (At least not in a simple way, AFAIK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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