简体   繁体   English

为什么这个非常简单的Python脚本不起作用? 虽然不循环

[英]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? 为什么这个非常简单的Python脚本不起作用?

I'm familar with Java so I thought I would give Python a go...but why does this not work? 我对Java很熟悉,所以我认为我可以试一试……但是为什么这不起作用?

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'. 然后继续要求用户输入,直到他们键入“ Y”或“ 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'. 出于某种原因,即使我键入“ y”或“ 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: 编辑:正如arshajii指出的那样,您也做错了分配:

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)

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

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