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

2

为什么不使用input()?当它可能是最简单的方法时......

import sys

y = 1

def test():
    print("Hello?")
    x = input()
    if x == ("hello"):
        print("Ah your back")
    else:
        print("Huh?")

while y == 1:
        test()
于 2013-10-10T11:17:50.217 回答
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 回答