when I trying to await my “async def” I get the error: “The “await” keyword is only allowed in an asynchronous function”. My code:
import time
import asyncio
energy = 0
async def regen_energy(energy):
while energy != 1000:
energy += 1
await time.sleep(0.5)
await print(energy)
await regen_energy(energy)
What’s or Where’s my mistake?
1
Here is fixed version:
- Use
asyncio.sleep()
instead synchronoustime.sleep()
- Why use
await
with theprint()
function? That doesn’t make sense - Use
asyncio.run()
import asyncio
async def regen_energy(energy):
while energy != 10:
energy += 1
await asyncio.sleep(0.5) # <-- use asyncio.sleep() instead
print(energy) # <-- remove await here
energy = 0
if __name__ == "__main__":
asyncio.run(regen_energy(energy))