用字符串回答Stdin

时间:2013-10-10 10:56:07

标签: python-3.x

我已尝试了许多不同的方法来使这段代码正常工作。

任何人都知道如何让它发挥作用?

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

5 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

它最后读取\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()

答案 2 :(得分: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()

答案 3 :(得分: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

答案 4 :(得分: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或换行符,表示字符串中行的结尾。