My if-elif-else statement in Python is not working properly
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def moveEntity(entity): print('forward=1') print('backward=2') print('left=3') print('right=4') direction = input('Where would you like to move?') distance = input('How many units?') if direction == 1: entity.y = entity.y + distance elif direction == 2: entity.y = entity.y - distance elif direction == 3: entity.x = entity.x - distance elif direction == 4: entity.x == entity.x + distance else: print('invalid input') |
当我运行这个函数并输入4个选项中的任何一个(1、2、3、4)时,函数总是跳过4个if/elif语句并执行else语句。我不知道我上面发布的代码有什么问题。在输入变量"方向"和"距离"后,我尝试打印它们的值,它们都以正确的值打印。之后,尽管运行了if和elif语句,但是仍然执行了else语句。任何帮助都将不胜感激。
这里有两个问题。第一个问题,正如其他答案所指出的,是你在比较一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def moveEntity(entity): print('forward=1') print('backward=2') print('left=3') print('right=4') direction = int(input('Where would you like to move?')) distance = int(input('How many units?')) if direction == 1: entity.y = entity.y + distance elif direction == 2: entity.y = entity.y - distance elif direction == 3: entity.x = entity.x - distance elif direction == 4: entity.x = entity.x + distance else: print('invalid input') |
这是因为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | def moveEntity(entity): print('forward=1') print('backward=2') print('left=3') print('right=4') direction = input('Where would you like to move?') while True: try : distance = int(input('How many units?')) if direction == '1': entity.y = entity.y + distance elif direction == '2': entity.y = entity.y - distance elif direction == '3': entity.x = entity.x - distance elif direction == '4': entity.x == entity.x + distance #return value except ValueError:: print('please enter a valid digit') |
请注意,当您将输入转换为
这是因为输入是一个字符串,但是if循环中的值是整数。
坏的:
1 2 3 | a = input() if a == 1: print("hello world") |
好:
1 2 3 | a = input() if a =="1": print("hello world") |