Find if a part of the integer from another integer is divisible by 7?
I'm not sure why you think the second one is "optimized"; the former at least looks faster to me.

Don't name variables temp - it tells you nothing about the actual job of the variable. q is also a bad name'; num_iters is clearer, and i is not used so just use an underscore instead.

Don't pre-initialize values, in this case temp. Assign to it only when you need to.

Don't use input - always use raw_input and explicit conversions.

Then you have

inp = raw_input()
num_iters = int(raw_input())

for _ in range(num_iters):
    l, r = map(int, raw_input().split())
    temp = int(inp[l - 1:r])

    if temp % 7 == 0:
        print "YES"
    else:
        print "NO"


which is simple enough to basically be ideal. A more advanced programmer might want to handle errors or put code into functions, but the advantages of those only really apply to larger programs.