Math day problem doubt

Can someone please tell me where my code is going wrong

def func(a,n,mod):
res = 1
while n>0:
if n%2==1:
res = (res * a)%mod
a = (a * a)%mod
n >>= 1
return res%mod

for _ in range(int(input())):
a,n,p = map(int,input().split())
ans = a%p
for i in range(2,n+1):
ans = func(ans,i,p)
print(ans)

Your logic is correct but python is giving TLE. I have coded it in C++ and got AC.
You can see my implementation here -:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.