簡體   English   中英

盡管滿足條件,Python If 語句在 function 中沒有運行

[英]Python If Statement in function not running despite condition being met

我目前正在嘗試為我的文本冒險編寫基本的位置移動,無論我做什么 0.1 position 如果語句代碼永遠不會運行。 我曾嘗試編輯 position 變量,然后再將其傳遞到 0.1,但運行 function 時沒有任何反應。 position 0.0 代碼運行良好,但不返回值 0.1,而是返回“NONE”。 (我通過 function 中的打印語句發現了這一點,它給出的只是“無”)我是否遺漏了一些我覺得非常明顯的東西。 重現錯誤的最少代碼是這樣的:

def main():  
    print('Time to test out movement.')
    Position = 0.0
    while Position != 9.9:
        Position = Movement(Position)
        
    
    print('Test concluded.')

def Movement(Position):
    if Position == 0.0:
        print('You have entered this old and decrepid dungeon in hopes of finding some kind of riches.')
        print('What would you like to do?')
        print('1-Move north to room 0.1')
        PChoice = int(input())
        if PChoice == 1:
            return 0.1
        
    if Position == 0.1:
        print('Movement successful.')
        

if __name__ == '__main__': main()

我認為您想在 position 變為 0.1 時停止程序,而且您的代碼正在運行無限循環,因為它無法處理 Position 值不是 0.0 或 0.1 的情況:試試這個代碼:

def main():
        print('Time to test out movement.')
        Position = 0.0
        while Position != 9.9:
            Position = Movement(Position)

        print('Test concluded.')

def Movement(Position):
    if Position == 0.0:
        print('You have entered this old and decrepid dungeon in hopes of finding some kind of riches.')
        print('What would you like to do?')
        print('1-Move north to room 0.1')
        PChoice = float(input())
        #print(PChoice)
        if PChoice == 1:
            return 0.1
        else:
            return PChoice

    elif Position == 0.1:
        print('Movement successful.')
        return 9.9
    else:
        PChoice = float(input())
        return PChoice

if __name__ == '__main__':
    main()

  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM