2017-08-16 45 views
0

當我開發我的第一個代碼時,遇到了一個問題,我用break命令試圖在程序出現錯誤時重新啓動程序。python「break」error:break outside loop

看看代碼,也許你會更好理解。

Name = str(input("Please enter Your Name:")) 
    Age = input("Please enter your age: ") 
     if Age != int(): 
      print ("Error! Check the age") 
      break 
    elif Age == int(): 
      continue 
    Height = input("Please enter your height: ") 
    if Height != int(): 
     print ("Error! Check the Height") 
      break 
    elif Height == int(): 
     continue 

if Age == int() and Age >= 18 and Height == int() and Height >= 148: 
    print("You're able to drive a car " + (Name)) 

elif Age == int() and Age < 18 and Height == int() and Height > 148: 
    print("You're not able to drive a car " + (Name)) 

elif Age and Height != int() : 
    print ("Error! , Age or Height are not numbers") 

錯誤:

"C:\Users\Ghanim\Desktop\Coding\Documents\Projects\Python\Project1\Project1.py", line 6 break ^ SyntaxError: 'break'

outside loop

+2

您的代碼縮進似乎被破壞。 – Moberg

+1

在這裏看看如何檢查一個變量是否包含一個數字:https://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not – Moberg

回答

1

break語句用於退出循環,而不是程序。使用sys.exit()退出程序,您還需要導入sys

編輯:

在回答您的意見,這是我大概會做到這一點:

while True: 

    inputted_name = input("Please enter your name:") 

    try: 
     name = str(inputted_name) 
    except ValueError: 
     print("Please enter a valid name") 
    else: 
     break 


while True: 

    inputted_age = input("Please enter your age:") 

    try: 
     age = int(inputted_age) 
    except ValueError: 
     print("Please enter a valid age") 
    else: 
     break 


while True: 

    inputted_height = input("Please enter your height:") 

    try: 
     height = float(inputted_height) 
    except ValueError: 
     print("Please enter a valid height") 
    else: 
     break 


if age >= 18 and height >= 148: 
    print("You're able to drive a car {}".format(inputted_name)) 

if age < 18 and height > 148: 
    print("You're not able to drive a car {}".format(inputted_name)) 

所以有一些變化:

用戶輸入的每個階段在它自己的循環中。我使用了try/except/else語句,它試圖將輸入轉換爲正確的類型,除了ValueErrors(如果它不能被投射,如果用戶對文檔input age進行了回答,則會發生這種情況)如果投射到正確的類型成功,循環被打破,腳本移動到下一個,每個單獨的循環意味着如果用戶爲其中一個輸入了不正確的值,他們不必重做整個事情。

我也用format()插入name進入決賽的字符串,以避免做字符串連接。

而且,只是一個快速的注意,我假設你使用Python 3本。但,如果你使用Python 2 input()應替換爲raw_input()。在Python 2中,input()將嘗試將用戶輸入評估爲表達式,而raw_input()將返回一個字符串。

+0

但是我怎樣才能使程序在出現錯誤時從頭重新啓動? –

+0

在這種情況下,您將需要一個用於輸入呼叫的while循環,我會更新我的答案給你一個例子 – RHSmith159

+0

非常感謝,我很感激:) –

0

break語句,跳出一個循環(for循環或while循環)。除此之外,這是沒有意義的。

0

break不能重新啓動你的程序,break只能用於循環,比如for或while。

在你的情況下,只需要使用出口(-1)

0

程序中沒有循環。 break不能在循環外使用。您可以使用sys.exit()而不是breakpass而不是繼續。