0

このコードを機能させるために、さまざまな方法を試しました。

これを機能させる方法を知っている人はいますか?

import sys

y = 1

def test():
    print("Hello?")
    x = (sys.stdin.readline())
    if x == ("hello"):
        print("Ah your back")
    else:
        print("Huh?")

while y == 1:
        test()
4

5 に答える 5

1

最後に a がある行を読み取る\nため、比較は失敗します。次のようなものを試してください:

import sys

y = 1

def test():
    print("Hello?")
    x = (sys.stdin.readline())
    if x[:-1] == ("hello"):
        print("Ah your back")
    else:
        print("Huh?")

while y == 1:
        test()
于 2013-10-10T11:02:01.827 に答える
1

改行を取り除きます。

import sys

def test():
    print("Hello?")
    x = sys.stdin.readline().rstrip('\n')
    if x == "hello":
        print("Ah your back")
    else:
        print("Huh?")

while True:
        test()
于 2013-10-10T11:02:02.023 に答える
1
import sys

y = 1
def test():
    print("Hello?")
    x = sys.stdin.readline()
    if x == "hello\n":  #either strip newline from x or compare it with "hello\n".
        print("Ah your back")
    else:
        print("Huh?") 
test()  #your while will cause stack overflow error because of infinite loop.

http://ideone.com/Csbpn9

于 2013-10-10T11:03:43.647 に答える
1

これはうまくいくはずです:

import sys

y = 1

def test():
    print("Hello?")
    x = (sys.stdin.readline())
    if x == ("hello\n"):
        print("Ah your back")
    else:
        print("Huh?")

while y == 1:
    test()

\n文字列の行末を示す または 改行文字がありません。

于 2013-10-10T11:05:02.933 に答える