繁体   English   中英

我在Python中的if-elif-else语句不能正常工作

[英]My if-elif-else statement in Python is not working properly

这是我的代码:

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语句。 我无法弄清楚我上面发布的代码有什么问题。 我已经尝试在输入后打印变量“direction”和“distance”的值,并且它们都打印为正确的值。 在此之后,尽管运行了if和elif语句,但仍然执行了else语句。 任何帮助,将不胜感激。

这里有两个问题。 第一个,正如其他答案所指出的那样,你将int与字符串进行比较。 所以,用int包装你的input 第二个是你在最后一次分配中有== ,所以即使达到了这种情况,它也不会更新entity.x的值。 这段代码应该有效:

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')

这是因为该input返回一个字符串,因此您需要将输入转换为整数以与该数字进行比较,或者只是与字符串数字进行比较。另请注意,在将其放入计算之前需要将distance转换为整数:

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')

请注意,将输入转换为int ,可能会引发值错误,因此,为了解决此问题,可以使用try-except表达式。

那是因为输入是一个字符串,但if循环中的值是整数。

坏:

a = input()
if a == 1:
    print("hello world")

好:

a = input()
if a == "1":
    print("hello world")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM