1

使用以下代码时:

url = None
print("For 'The Survey of Cornwall,' press 1")
print("For 'The Adventures of Sherlock Holmes,' press 2")
print("For 'Pride and Prejudice,' press 3")
n = input("Which do you choose?")
if n==1:
    url = 'http://www.gutenberg.org/cache/epub/9878/pg9878.txt' #cornwall
    print("cornwall")
elif n==2:
    url = 'http://www.gutenberg.org/cache/epub/1661/pg1661.txt' #holmes
    print("holmes)
elif n==3:
    url = 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt' #pap
    print("PaP")
else:
    print("That was not one of the choices")

我只收到了“其他”案例,为什么会这样?

4

6 回答 6

4

input()在 py3x 中返回一个字符串。因此,您需要int先将其转换为。

n = int(input("Which do you choose?"))

演示:

>>> '1' == 1
False
>>> int('1') == 1
True
于 2013-05-12T04:27:15.827 回答
3

input()返回一个字符串,但您将其与整数进行比较。您可以使用该函数将结果从输入转换为整数int()

于 2013-05-12T04:27:12.017 回答
1

您应该使用 int() 转换输入 n = input("Which do you choose?")应该是n = int(input("Which do you choose?")) 这是因为输入返回所有输入的字符串,因为它应该几乎总是有效。

于 2013-05-12T04:27:05.313 回答
1

我猜你正在使用 Python 3,它的input行为就像raw_input在 Python 2 中所做的那样,也就是说,它将输入值作为字符串返回。在 Python 中,'1' 不等于 1。您必须使用 将输入字符串转换为 int n = int(n),然后执行一系列 elif。

于 2013-05-12T04:28:33.040 回答
1

input() 返回一个字符串类型。因此,您需要使用 int() 将输入转换为整数,否则您可以将输入与字符而不是整数进行比较,例如“1”、“2”。

于 2013-05-12T04:57:50.810 回答
1

虽然其他答案正确地确定了您else在当前代码中获得块的原因,但我想建议一个更“Pythonic”的替代实现。而不是一堆嵌套的if/elif语句,使用字典查找,它可以支持任意键(包括可能比整数更有意义的键):

book_urls = {'cornwall': 'http://www.gutenberg.org/cache/epub/9878/pg9878.txt',
             'holmes': 'http://www.gutenberg.org/cache/epub/1661/pg1661.txt',
             'p and p': 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt'}

print("For 'The Survey of Cornwall,' type 'cornwall'")
print("For 'The Adventures of Sherlock Holmes,' type 'holmes'")
print("For 'Pride and Prejudice,' type 'p and p'")

choice = input("Which do you choose?") # no conversion, we want a string!

try:
    url = book_urls[choice]
except KeyError:
    print("That was not one of the choices")
    url = None

如果你愿意,你可以让整个事情都是数据驱动的,书名和网址作为参数提供给一个要求用户选择一个的函数(不知道他们提前是什么)。

于 2013-05-12T05:24:52.493 回答