Python if else语句无效

时间:2017-02-20 11:14:28

标签: python

我的if else语句在下面的代码中没有运行,我正在使用我的终端执行这一段python,一旦我输入4或5,程序就会终止并返回到提示符。我做错了什么?

#!/usr/bin/env python
import webbrowser

print '\033[0;37;40m' + "Title: The interlinked bit (the index)"
print "Heading: Links!"
print "Paragraph Some Interesting stuff can be found here"
print "Paragraph: And some other bits are also available"
print "1: ./page4.html"
print "2: /page5.html"

pageNumber = raw_input("Enter 4 or 5: ")
if pageNumber == 4:
  print "A Page of stuff"; 
  print "Actually this is all rather dull, why don't you look here           instead, or alternatively    go back  to the index";
elif pageNumber == 5:
  print "Another page of stuff"
  print "Nothing very much here, you should probably try here instead, or       perhaps go back to the index"

提前致谢!

5 个答案:

答案 0 :(得分:0)

替换为: -

pageNumber = raw_input("Enter 4 or 5: ")使用pageNumber = input("Enter 4 or 5: ")

注意: - 如果您使用的是python 3 input()将与python2.7中的raw_input()相同,那么您需要像int(input("Enter 4 or 5: "))一样使用它。 python3中没有raw_input()

答案 1 :(得分:0)

尝试定义raw_input的返回类型。现在,这是一个str,它应该是int!尝试将代码更改为:

pageNumber = int(raw_input("Enter 4 or 5: "))

答案 2 :(得分:0)

如果您使用的是python2。*使用pageNumber = input("Enter 4 or 5: ")或者如果您使用的是python3,则可以使用pageNumber = int(input("Enter 4 or 5: "))

答案 3 :(得分:0)

除非您有理由对用户输入的数字进行操作,否则我会将if语句更新为:

if pageNumber == "4":

这会将它们作为字符串进行比较。 elif语句还需要更新:

elif pageNumber == "5":

答案 4 :(得分:0)

事情是raw_input()总是将你输入的任何内容视为一个字符串,所以当你输入输入时,让我们说4,它被视为一个字符串然后它正在进行比较如果pageNumber == 4,则将字符串4添加到int 4(:`)您可以做的是:

#!/usr/bin/env python
import webbrowser

print '\033[0;37;40m' + "Title: The interlinked bit (the index)"
print "Heading: Links!"
print "Paragraph Some Interesting stuff can be found here"
print "Paragraph: And some other bits are also available"
print "1: ./page4.html"
print "2: /page5.html"

pageNumber = raw_input("Enter 4 or 5: ")
if pageNumber == '4': #this
  print "A Page of stuff"; 
  print "Actually this is all rather dull, why don't you look here           instead, or alternatively    go back  to the index";
elif pageNumber == '5': #this
  print "Another page of stuff"
  print "Nothing very much here, you should probably try here instead, or       perhaps go back to the index"

输入:

4

输出:

Title: The interlinked bit (the index)
Heading: Links!
Paragraph Some Interesting stuff can be found here
Paragraph: And some other bits are also available
1: ./page4.html
2: /page5.html
Enter 4 or 5:  4
A Page of stuff
Actually this is all rather dull, why don't you look here           instead, or alternatively    go back  to the index