为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2021-03-02 13:14:28
使用以下代码时:url = Noneprint("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”案例,为什么会这样呢?
查看完整描述

4 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

input()返回py3x中的字符串。因此,您需要将其转换为intfirst。


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

演示:


>>> '1' == 1

False

>>> int('1') == 1

True


查看完整回答
反对 回复 2021-03-23
?
12345678_0001

TA贡献1802条经验 获得超5个赞

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


查看完整回答
反对 回复 2021-03-23
?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

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


查看完整回答
反对 回复 2021-03-23
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

您应该使用int()将输入转换 n = input("Which do you choose?")为。n = int(input("Which do you choose?")) 这是由于输入几乎返回始终可以正常工作的事实,所以输入返回所有输入的字符串。


查看完整回答
反对 回复 2021-03-23
  • 4 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号