Python中字符串的if语句?
我还是个初学者,一直在看这个链接:http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements,但是我对这里的问题有点搞不懂。其实很简单,如果用户输入'y',程序应该打印出“这将进行计算”,可是我在写IF answer=="y"的时候却出现了语法错误。
answer = str(input("Is the information correct? Enter Y for yes or N for no"))
proceed="y" or "Y"
If answer==proceed:
print("this will do the calculation"):
else:
exit()
6 个回答
Python 是一种区分大小写的编程语言。所有的 Python 关键字都是小写的,所以要用 if
,而不是 If
。
另外,在调用 print()
时,不要在后面加冒号。同时,要把 print()
和 exit()
的调用缩进,因为 Python 是通过缩进来表示代码块的,而不是用大括号。
还有,proceed = "y" or "Y"
这样写是行不通的。应该用 proceed = "y"
,然后用 if answer.lower() == proceed:
来判断,或者用类似的方式。
另外,你的程序只要输入的值不是单个字符 "y" 或 "Y",就会退出,这和提示的 "N" 选项是矛盾的。与其在那儿用 else
,不如用 elif answer.lower() == info_incorrect:
,并且在之前定义 info_incorrect = "n"
。如果输入的值是其他内容,就重新提示用户输入。
如果你在学习过程中遇到这么多问题,我建议你去看看 Python 文档里的教程。可以访问这个链接:http://docs.python.org/tutorial/index.html
这里的If
应该改成if
。你的程序应该像这样:
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
print("this will do the calculation")
else:
exit()
另外,注意缩进也很重要,因为在Python中,缩进用来标记代码块。
即使你修正了代码中大小写错误的if
和不正确的缩进,它也可能不会像你预期的那样工作。要检查一个字符串是否在一组字符串中,可以使用in
。下面是你可以这样做的方式(注意if
是全小写,并且if
块中的代码缩进了一层)。
一种方法:
if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
print("this will do the calculation")
另一种方法:
if answer.lower() in ['y', 'yes']:
print("this will do the calculation")