我想知道,如果在for循环和使用字典中,如果有人没有输入适当的值,你可以返回迭代。如果我说的话没有多大意义,也许我的代码可以让你更好地了解我正在尝试做什么。
attributesD = {"Charisma": 0, "Intelligence" : 0 ,"strength" : 0 , "agility" : 0 , "constitution" : 0}
totalPoints = 15
def listing():
print(" Attributes ".center(108,"*"))
abilitiesSteady_Print("\n\nPoints left: " + str(totalPoints) + "\n\n")
for index in attributesD:
abilitiesSteady_Print(index + ": " + str(attributesD[index]) + "\n\n")
for key in attributesD:
if totalPoints > 0:
listing()
try:
attributesD[key] = int(input("\n\nHow many points would you like to put in " + key + "?\n>"))
totalPoints -= attributesD[key]
replit.clear()
except:
steady_print("Not possible, try again")
else:
continue
如果用户没有输入正确的答案,它将跳过该属性,0将保留为该值。如何防止这种情况发生?
答案 0 :(得分:2)
def get_integer(prompt):
while True:
try:
return int(input(prompt))
except (ValueError,TypeError):
print("Expecting an integer")
然后你只需要打电话
my_int = get_integer("Enter score:")
它将保证你得到一个整数
您还可以创建其他输入辅助函数,例如
def get_choice(prompt,i_expect_one_of_these_things):
while 1:
result = raw_input(prompt)
if result in i_expect_one_of_these_things:
return result
print("Invalid input!")