Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am new to python and i dont know why this code isnt working

class Car:
    def __init__(self, pos=0):
        self.pos = pos

    def move(self, direction):
        self.pos = self.pos + direction

    def get_position(self):
        return self.pos


def main():
    n = int(input())
    car = Car()
    for _ in range(n):
        instruction = input()
        if instruction == "MOVE":
            distance = int(input())
            car.move(distance)
        elif instruction == "POSITION":
            position = car.get_position()
            print(position)

if __name__ == '__main__':
    main()

I really dont know why its not working

I tried to launch it and for some reason when you type MOVE 100 or any number it still stays in same position

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because "MOVE 100" is considered as one input, so with instruction = input() and this MOVE 100 as input, instruction will be "MOVE 100", not "MOVE", in order to separate them, you can either do the following:

instruction = input()
if instruction.startswith("MOVE"):
    distance = int(instruction.split(' ')[1])
    car.move(distance)

Or you can keep your code the same, but you can change the input so that you input MOVE and 100 separately.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading