在Python中使用if / elif / else进行“切换”

使用以下代码时:


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

我只返回“ else”案例,为什么会这样呢?


德玛西亚99
浏览 204回答 4
4回答

临摹微笑

input()返回py3x中的字符串。因此,您需要将其转换为intfirst。n = int(input("Which do you choose?"))演示:>>> '1' == 1False>>> int('1') == 1True

12345678_0001

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

翻翻过去那场雪

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

婷婷同学_

您应该使用int()将输入转换 n = input("Which do you choose?")为。n = int(input("Which do you choose?")) 这是由于输入几乎返回始终可以正常工作的事实,所以输入返回所有输入的字符串。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python