簡體   English   中英

python“中斷”錯誤:中斷外循環

[英]python “break” error: break outside loop

當我開發我的第一個代碼,我遇到它與一個問題break命令,我試圖用重新啟動程序,如果有一個錯誤。

看一下代碼也許你會更好地理解。

  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”,第 6 行中斷 ^ SyntaxError: 'break'

外環

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()將返回一個字符串。

break語句跳出循環(for 循環或 while 循環)。 在這個上下文之外,它沒有意義。

break 不能重新啟動你的程序,break 只能在循環中使用,例如 for 或 while。

在你的情況下,只需使用 exit(-1)

你的程序中沒有循環。 break不能在循環外使用。 您可以使用sys.exit()代替breakpass代替 continue。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM