簡體   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