2016-11-11 102 views
-8

我是Python新手。我试图运行下面的代码。但是每次我尝试运行它时,IDE都会说这个中断处于循环之外在循环外打破

catname = [] 

print("Enter the name of the cats") 

name = input() 

if name == '': 

    break 

catname = catname+[name] 

print("The cat Names are :") 

for catname in name: 

    print(name) 

你能帮我吗?

感谢

+3

'break'不在循环内:) –

+1

在'if'语句之后你有一个中断,并且直到最后都没有看到循环。 – Lexi

+1

但是错误信息是误导性的,必须承认。由于没有循环,break语句不能在一个之外。 – Ukimiku

回答

3

您可以使用break当您想让break免于循环时退出循环以跳转到循环后最近的代码。

您的代码不包含循环,所以没有任何东西可以摆脱,因此错误。

0

如果这是你的代码的全部,那么它告诉你到底是什么问题:

catname = [] 

print("Enter the name of the cats") 

name = input() 

if name == '': 

    break 

你必须在并非包含一个循环内的代码break语句。你期望上面的代码做什么?

2

您可以使用“中断”只是循环(“代表”或“而”)里面,你想里面使用刹车“如果”

如何:

if name != '': 
    catname = catname+[name] 
    print("The cat Names are :") 
    for catname in name: 
     print(name) 
3

我想你的意思是exit()而不是break

1

你的break语句不在循环中,它只是在if语句中。 但也许你想要做类似下面的事情。 如果你想要让用户输入名称的随机数,并打印出来的名字,当用户输入任何内容,你可以做到以下几点:

# Here we declare the list in which we want to save the names 
catnames = [] 

# start endless loop 
while True: 
    # get the input (choose the line which fits your Python version) 
    # comment out the other or delete it 
    name = input("Enter the name of a cat\n") # input is for Python 3 
    # name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2 

    # break loop if name is a empty string 
    if name == '': 
     break 

    # append name to the list catnames 
    catnames.append(name) 

print("The cat names are :") 

# print the names 
for name in catnames: 
    print(name) 
1

你在找什么是exit()

然而,你的代码也具有其它问题,这里是一段代码,做你可能想要的东西(提示时,输入用空格隔开,就像名字:CAT1 CAT2):那是因为

name = raw_input("Enter the name of the cats: ") 

if len(name) == 0: 
    exit() 

print("\nThe cat Names are:") 
for c_name in name.split(): 
    print(c_name)