强制raw_input

时间:2012-04-23 23:03:10

标签: python

我如何实施以下内容:

title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if not title:
    # repeat raw_input

2 个答案:

答案 0 :(得分:12)

title_selection = ''
while not title_selection:
  title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))

有必要先将title_selection定义为'',这意味着空(也是假)。 not会使False变为真(否定)。

答案 1 :(得分:11)

这通常使用“loop-and-a-half”结构,中间有break

while True:
    title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
    if title_selection:
        break
    print "Sorry, you have to enter something."

此方法使您可以轻松打印消息,告诉用户程序期望的内容。