我如何返回到我的代码的开头/有一个嵌套循环?

时间:2016-02-05 16:20:32

标签: python string loops nested

我希望我的代码能够运行,这样如果条件不满足(在if循环中),它将返回代码的开头,要求用户输入另一个句子。我如何添加这个嵌套循环(如果这是它的名称)?

sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word, {0}, is in positions:".format (word))
for position,w in enumerate(wordlist):
    if w == word:
        print("{0}".format(position+1))

2 个答案:

答案 0 :(得分:2)

您可以在代码和whilebreak周围添加continue循环,具体取决于输入:

while True:
     sentence = input("Please input a sentence: ")
     if bad(sentence): # replace with actual condition
         continue
     ...
     for position, w in enumerate(wordlist):
         ...
     break

答案 1 :(得分:0)

只是做:

sig_id  ip_src       ip_dst         sig_name                                        timestamp                                                             num
    501 192.168.0.1 192.168.0.103   DNS SPOOF query response with TTL of 1 min. and no authority    2010-08-23 21:43:37                                   5236
    502 192.168.0.1 192.168.0.103   COMMUNITY WEB-PHP DeluxeBB newpost.php access   2010-08-23 21:45:39                                                   238
    503 192.168.0.1 192.168.0.103   ICMP Destination Unreachable Communication with Destination Host is Administratively Prohibited 2010-08-23 21:47:12 1428
    504 192.168.0.1 192.168.0.103   COMMUNITY WEB-PHP DeluxeBB forums.php access    2010-08-23 21:47:56                                                   119
    505 192.168.0.1 192.168.0.103   MS-SQL version overflow attempt 2003-09-05 06:14:33                                                                   2261
    506 192.168.0.1 192.168.0.103   NETBIOS SMB repeated logon failure  2003-09-06 14:11:57                                                               4879