简体   繁体   中英

Python If Statement in function not running despite condition being met

I am currently attempting to program basic positional movement for a text adventure of mine and no matter what I do the 0.1 position if statement code never runs. I have tried editing the position variable before it is passed in as well to 0.1 but nothing occurs when the function is ran. The position 0.0 code runs fine but doesn't return the value of 0.1, instead returning 'NONE'. (I found this out via a print statement within the function and all it gave was 'NONE') Is there something I'm missing that's super obvious as I feel like there is. The bare minimum code to reproduce the error is this:

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

I think you want to stop the program when position becomes 0.1, also your code is running an infinte loop as it does not handle the cases when Position value is not 0.0 or 0.1: Try this code:

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

  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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