简体   繁体   中英

Else statement is executing along with if statement

I am a beginner programmer learning Python 3.4.3. I am writing a program which tokenizes a string representing a mathematical formula, or turning the string into a list.

I am using a series of if / elif / else statements to accomplish this. My code for this function is as follows:

def positive_or_add(usr_string, place):
    """ Determines if a + or - is intended to be a add /subtract or positive
    or negative.  Takes a string (usr_string) and an integer (place) to
    determine the place in the string.  Returns true for an operator, or
    negative for pos/neg
    (string) -> bool
    >>> '3 + 5 +(-4)
    Fales
    """
    #munover the place setting prior to the +/- operator
    place -= 1
    #munover left through the white space to determine what preceeded
    while usr_string[place] == ' ':
        place -= 1
    if usr_string[place].isdigit() or usr_string[place] == ')':
        return True
    else:
        return False

def tokenize(usr_string):
    """
    (str) -> list
    Takes a string, and tokenizes it.  Basically turning the string
    representing a mathimatical formual and making it into a list, eliminating
    the white spaces
    >>> '3 + 5 + (-4)
    [3, +, 5, +, (, -4, )]
    """
    token_list = []
    i = 0
    while i < len(usr_string):
#Add values to the list that arent white space, + or -
        if usr_string[i] != ' ' and usr_string[i] != '+' and usr_string[i] != '-':
            token_list.append(usr_string[i])
            i += 1
        elif usr_string[i] == '+' or usr_string[i] == '-':
#Determine if that + or - is an operator or pos / neg
            sign = positive_or_add(usr_string, i)
            if sign == True: #Operator
                token_list.append(usr_string[i])
                i += 1
            elif sign == False: #pos / neg
                token_list.append(usr_string[i] + usr_string[i + 1])
                i += 2
        elif usr_string == ' ':
            continue
        else:
            print('something messed up')
            i += 1
    return token_list

#Test
print(tokenize('3 + 5 + (-4)'))

My problem is that my else statement is always executing, along with the if / elif statements. I basically get the 'something messed up' line multiple times, followed by my generated list tonek_list.

When I try to erase the else statement the program basically gives me a blank line, and nothing happens.

I am guessing I am just not seeing something here. Any help would be greatly appreciated.

Your immediate problem almost certainly has to do with this line here:

elif usr_string == ' ':

Every other check is being performed on usr_string[i] so I'm not sure exactly what prompted you to check the entire string for that particular case. What it means is that, whenever you find a space in the input string (and the whole string isn't just a single space), it will drop through to your "something amiss" case.

In addition, that's the only case where you're not incrementing the index variable i so the first space you find (once you've fixed that first issue) will put you into an infinite loop.

I think you'll find things will go a lot smoother if you change it to:

elif usr_string[i] == ' ':
    i += 1

Even once both those issues are fixed, it appears that you have no code to correctly handle the parentheses ( and ) . For now, I'd suggest taking them out of the input string so as to test a more basic expression but you'll probably need to handle them at some point.

Here you have the fixed code:

def tokenize(usr_string):
    """
    (str) -> list
    Takes a string, and tokenizes it.  Basically turning the string
    representing a mathimatical formual and making it into a list, eliminating
    the white spaces
    >>> '3 + 5 + (-4)
    [3, +, 5, +, (, -4, )]
    """
    token_list = []
    i = 0
    while i < len(usr_string):
#Add values to the list that arent white space, + or -
        if usr_string[i] != ' ' and usr_string[i] != '+' and usr_string[i] != '-':
            token_list.append(usr_string[i])
            i += 1
        elif usr_string[i] == '+' or usr_string[i] == '-':
#Determine if that + or - is an operator or pos / neg
            sign = positive_or_add(usr_string, i)
            if sign == True: #Operator
                token_list.append(usr_string[i])
                i += 1
            elif sign == False: #pos / neg
                token_list.append(usr_string[i] + usr_string[i + 1])
                i += 2
        elif usr_string[i] == ' ':
            i += 1
            continue
        else:
            print('something messed up')
            i += 1
    return token_list

Fixed:
- sr_string[i] instead of sr_string (line 26)
- Needed an indent of i += 1 before continue , otherwise infinite loop

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