简体   繁体   中英

Why does this very simply piece of Python script not work? While not loop

Why does this very simply piece of Python script not work?

I'm familar with Java so I thought I would give Python a go...but why does this not work?

def playAgain(roundCounter):
    reply = ""
    replyList='y n'.split()
    if roundCounter == 1:
        print('Would you like to play again? Y/N')
        while not reply in replyList:
            reply = input().lower  
        if reply == 'y':
            roundCounter == 1
        elif reply == 'n':
            print('Thanks for playing! Bye!')
            sys.exit()  

This should print "Would you like to play again?" and then keep requesting the users input until they type 'Y' or 'N'.

For some reason, it keeps looping over and over again though and won't break out of the loop - even if I type 'y' or 'n'.

It's such a simple piece of code I don't understand why it doesn't work - and in fact I used a near identical piece of code earlier on in my script and it worked fine!

you forgot the parantheses:

reply = input().lower  # this returns a function instead of calling it

do this:

reply = input().lower()

Edit: As pointed by arshajii, you're also doing the assignment wrong:

if reply == 'y':
    roundCounter == 1  # change this to: roundCounter = 1

== is the equality operator and returns a boolean, assignment is done by =

import sys

def playAgain(roundCounter):
    reply = ""
    replyList='y n'.split()
    if roundCounter == 1:
        print('Would you like to play again? Y/N')
    while not reply in replyList:
        reply = input().lower()
    if reply == 'y':
        roundCounter = 1
    elif reply == 'n':
        print('Thanks for playing! Bye!')
        sys.exit()

playAgain(1)

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