python - 在 python 中使用 if/elif/else 作为 "switch"

标签 python

使用以下代码时:

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”案例,为什么会这样??

最佳答案

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

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

演示:

>>> '1' == 1
False
>>> int('1') == 1
True

关于python - 在 python 中使用 if/elif/else 作为 "switch",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16504184/

相关文章:

python 应用程序在 thread.join() 上卡住

python - 如何确定参数是对象还是内置?

python : defaultdict every value is updated

python - 什么时候在 Python 中使用模板引擎?

python - 选择列中只有零的行

python - SQL 数据库查询 - 返回包含列表中所有值的记录 (Python)

python - 如何将 python 字典放入 protobuf 消息中?

python - Ckan 安装失败,出现 : Unknown distribution option: 'message_extractors'

python - 将年转换为年月日 python pandas csv

python - 如何使用 Peewee 从 DateTime 中选择不同的年份