在for循环中返回一次迭代?

问题描述 投票:1回答:1

我想知道,如果在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将保留为该值。如何防止这种情况发生?

python python-3.x
1个回答
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!")
© www.soinside.com 2019 - 2024. All rights reserved.