【发布时间】:2019-10-07 20:24:35
【问题描述】:
我遇到了一个我无法弄清楚的小问题。我陷入了一个while循环。我有 3 个 while 循环,第一个按计划执行,然后进入第二个。但它只是卡在第二个,我不知道为什么。
关于我要做什么的一点解释:
我想得到 3 个输入:多年的经验 (yearsexp)、性能 (performance) 和在 1-10(level) 之间生成的随机 int。该程序会询问用户他们的体验,如果它在 3-11 之间他们是合格的。如果没有,它会告诉他们他们不合格并要求重新输入一个值。性能也一样。如果他们输入一个小于或等于 11 的数字,它将继续生成随机 int(级别),在该点级别将用于评估他们的奖金。系统会提示用户体验,并将正常运行并继续执行。但是,即使输入了有效的输入,它也会不断要求他们重新输入性能#。我无法弄清楚为什么它会这样卡住。
import random
error = True
expError = True
performanceError = True
# Get users name
name = input("Enter your name: ")
# Get users experience *MINIMUM of 3 yrs py
while (expError):
try:
yearsexp = int (input(name+", Enter the years of your experience: "))
if (yearsexp >= 3 and yearsexp <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
#Get users performance
while (performanceError):
try:
performance = int (input(name+", Enter the performance: "))
if (performance <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
performanceError = False
# Get random level number
level = random.randint(1,11)
print ("Random Level: ", end =' ')
print (level)
bonus = 5000.00
while (error):
try:
if (level >=5 and level <=8):
error = False
print ("Expected Bonus: $5,000.00")
print (name + ", your bonus is $", end =' ')
print (bonus)
elif (level <= 4 ):
error = False
bonus = bonus * yearsexp * performance * level
print ("Expected bonus: ", end =' ')
print (bonus)
print (name + ", your bonus is $", end =' ')
print (bonus)
else:
raise ValueError
except:
print ("You do not get a bonus")
【问题讨论】:
-
不要使用
while (errorVar):,而是使用while(True):,然后在您想跳出循环时使用break。 -
错字:第二个循环有
expError = False而不是performanceError = False -
如果您使用
while True:成语,就不会遇到这样的问题。 -
这只是运行 while 循环的一种更简洁的方法吗?如果我将其设置为 while True: If 语句失败会自动触发 false 吗?还是我必须说 this = false?
-
没有什么会自动触发假。您使用
break语句结束循环而不是设置变量。
标签: python exception while-loop