当我开发我的第一个代码时,我遇到了 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’
外循环
原文由 Sam Ghanim 发布,翻译遵循 CC BY-SA 4.0 许可协议
break
语句用于退出循环,而不是程序。使用sys.exit()
退出程序,你还需要导入sys
。编辑:
在回答您的评论时,我可能会这样做:
所以有一些变化:
用户输入的每个阶段都在自己的循环中。我使用了 try/except/else 语句来尝试将输入转换为正确的类型,除了
ValueErrors
(如果无法转换则抛出,如果用户将文本答案放入input age
例如。如果它成功转换为正确的类型,则循环被中断并且脚本移动到下一个。每个循环都有单独的循环意味着如果用户为其中一个输入了错误的值,他们不必重做整个事情。我还使用
format()
将name
插入到最终字符串中,以避免必须进行字符串连接。另外,请快速注意一下,我假设您为此使用 Python 3。但是,如果您使用的是 Python 2
input()
应该替换为raw_input()
。在 Python 2input()
将尝试将用户输入计算为表达式,而raw_input()
将返回一个字符串。