python中outside loop_python“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插入到最后的字符串中,以避免必须进行字符串连接。在

另外,简单地说一下,我假设您使用的是python3。但是,如果您使用python2,input()应该替换为raw_input()。在python2中,input()将尝试将用户输入作为表达式进行计算,而raw_input()将返回一个字符串。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值