Combining a for loop and an if statement

I have a function that I’m trying to design to check if a string that is passed to it has any spaces or any punctuation and if it has either one of those things it will return an error message for both. If it has neither of those things it will return the original string that was passed to it.

The issue that I’m running into is that I’m trying to check every character in the string to see if there is a punctuation character and then I’m trying to check if there is a split, I’m not sure how to do both of these and while troubleshooting this function it appears that the for loop is only running once. I could likely solve this with regex, but I would rather not.

def punct_space_check(word):
    punct = string.punctuation
    error_msg_space = "Please enter only one word at a time."
    error_msg_punct = "Please enter a word with no punctuation."
    
    for ww in word:
        if ww in punct:
            return error_msg_punct
            break
        elif len(word.split()) > 1:
            return error_msg_space 
        else:
            return word

The code that I have so far seems to work fine for finding a split, and it seems to be able to identify a punctuation character in the first index, but it can’t identify a punctuation character in any another index.

Is there a way to properly combine a for loop and an if/else statement?

Thanks.

To understand what’s happening in loops, it’s useful to trace through them. I would start by tracing through the loop for a word that starts with a punctuation character. What happens in that case?

You may be aware of this already, but whenever you include a return statement in a function, your function ends right away there, whether it’s in the middle of a loop or not.

Once you’ve done the tracing, you might understand why it’s only looping a short number of times, but you might not know how to approach the problem. One way might be to create a boolean variable for each check that defaults to False and if one of your check condition matches change that to True. At the end of the loop, it will be False if no conditions matched, and True if at least one condition matched. Then, outside the loop, you can create logic to return error messages based on that variable.

One last tip, elif len(word.split()) > 1: doesn’t use ww at all, so you might decide to move that logic outside the loop.

I hope this is helpful, I’ve tried to guide you towards the answer without giving it to you explicitly :wink:

2 Likes

This is the solution that I ended up going with in the end.

def punct_space_check(word):
    punct = string.punctuation
    error_msg_space = "Please enter only one word at a time."
    error_msg_punct = "Please enter a word with no punctuation."
   
    
    for ww in word:
        if ww in punct:
            return True
    if len(word.split()) > 1:
        return True
    else:
        return False

Thanks for your help.

1 Like