-4

I am trying to do a API test on a URL with Python, I have the following code block

       def simple_get(url):
        try:
            page_response = requests.get(page_link, timeout=5)
            if page_response.status_code == 200:
            # extract
            else:
                print(page_response.status_code)
                # notify, try again
        except requests.Timeout as e:
            print("It is time to timeout")
            print(str(e))
        except # other exception

When I run it give me the following error

File "<ipython-input-16-6291efcb97a0>", line 11
else:
   ^
IndentationError: expected an indented block

I dont understand why is the notebook still asking for indentation when I already have the "else" statement indented

Jin
  • 69
  • 2
  • 3
  • 11

3 Answers3

1

Problem is that you did not tell the program what to do when the first condition is satisfied (if statement). If you are not sure about what to do in if, you can use python build in 'pass'.

if page_response.status_code == 200:
    pass
else:
    print(page_response.status_code)
petezurich
  • 9,280
  • 9
  • 43
  • 57
shahidammer
  • 1,026
  • 2
  • 10
  • 24
1

This is a very basic concept in Python to start coding:
Lines which start with # are ignored within a code block.

The code here

    if page_response.status_code == 200:
    # extract
    else:
        print(page_response.status_code)

literally translated as

    if page_response.status_code == 200:
    else:
        print(page_response.status_code)

and therefore produces IndentationError.

You can solve it by placing at least pass command or any working line into to the if statement.

Similar question is already asked before:
Python: Expected an indented block

Akif
  • 6,018
  • 3
  • 41
  • 44
0
import requests
from bs4 import BeautifulSoup
def simple_get(url):
    try:
        page_response = requests.get(url, timeout=5)
        if page_response.status_code == 200:
            print(page_response.status_code)
            pass
            # extract
        else:
            print(page_response.status_code)
            # notify, try again
    except requests.Timeout as e:

        print("It is time to timeout")
        print(str(e))
simple_get("https://www.nytimes.com/")
Xavier
  • 11
  • 2