Communication between arduino and python with pyserial

 Arduino Code:

int led = 8;

void setup() {
  // put your setup code here, to run once:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
   while (Serial.available() == 0) {}
    String teststr = Serial.readString();
    teststr.trim();
 
    if (teststr == "on") {
      digitalWrite(led, HIGH);
      Serial.print(teststr);


    } else if (teststr == "off") {
      digitalWrite(led, LOW);
      Serial.print(teststr);
    }
 
}


Python Code:
import serial
import time
ser = serial.Serial(port='COM3', baudrate=9600, bytesize=serial.EIGHTBITS)


while True:
    inputVal = input("Enter on or off :")
    ser.write(bytes(inputVal, 'utf-8'))
    time.sleep(0.05)


Circuit:


Comments