My character doesn't retain left animation while in the air

I am using godot 4

Question

So I have written a script to move my 2d character.

while everything works fine but there is a problem.
when the character jumps and when I click the left arrow , for a moment the animation/frame for left animation plays but when I release the left arrow key the animation/frame for right jump plays. How to fix this ?
Here is the script I wrote.

extends CharacterBody2D

const SPEED = 200.0
const JUMP_VELOCITY = -500.0
@onready var sprite_2d = $Sprite2D

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

func _physics_process(delta):
#Animations:
if(velocity.x>1):
sprite_2d.animation=“running_right”
elif(velocity.x<-1) :
sprite_2d.animation=“running_left”
else:
sprite_2d.animation=“default”

# Add the gravity.

	
if not is_on_floor():
	if velocity.x<0:
		sprite_2d.animation="jumping_left"
	else:
		sprite_2d.animation="jumping"
	velocity.y+=gravity*delta

	

# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
	velocity.y = JUMP_VELOCITY

# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)

move_and_slide()

Seems like a similar solution to your running animation would apply here, try an elif instead of else; so your variable is left alone at zero.

if velocity.x < 0:
	sprite_2d.animation="jumping_left"
elif velocity.x > 0:
	sprite_2d.animation="jumping"

It kind of worked but now there is a new problem.
The character does turn left and right upon pressing respective arrow keys but when I release the arrow keys the characters goes back to idle animation which is not a desired output.
How do I make the character maintain the left or right animation state/frame?

Combine your floor animation logic with your not-floor animation logic, use and if/else

if is_on_floor():
	if(velocity.x>1):
		sprite_2d.animation="running_right"
	elif(velocity.x<-1) :
		sprite_2d.animation="running_left"
	else:
		sprite_2d.animation="default"
else: # not on floor
	if velocity.x < 0:
		sprite_2d.animation="jumping_left"
	elif velocity.x > 0:
		sprite_2d.animation="jumping"