0

I'm running a Python script to post a Tweet if the length is short enough with an exception for errors and an else statement for messages that are too long.

When I run this, it posts the Tweet and still gives the Tweet too long message. Any idea why that is happening and how to make it work as intended?

if len(tweet_text) <= (280-6):
    try:    
        twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
        twitter.update_status(status=tweet_text)
    except TwythonError as error:
            print(error)
    else:
        print("Tweet too Long. Please try again.")
3
  • 1
    Shouldn't the else be aligned with your if not the try/except? Commented May 5, 2022 at 4:45
  • 2
    else will execute , if there are no exceptions in your try block. So I think its normal. And as @IainShelvington said, you should consider aligning it with if block, as it seems logical Commented May 5, 2022 at 4:47
  • There is no loop. Commented May 5, 2022 at 5:34

2 Answers 2

2

The first string is checking the length of the tweet. Move the else four spaces back. Because try/except construction can be try/except/else construction

Sign up to request clarification or add additional context in comments.

Comments

1

From the docs:

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. (emphasis added)

Spaces/Tabs matter in Python.

What your snippet says in common English is "Try to post the tweet, unless there's an error, then print the error. If there's not an error, print 'Tweet too long. Please try again.'"

What you want is:

if len(tweet_text) <= (280-6):
    try:    
        twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
        twitter.update_status(status=tweet_text)
    except TwythonError as error:
        print(error)
else:
    print("Tweet too Long. Please try again.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.