简体   繁体   中英

Going back one iteration in a for loop?

I was wondering if, while in a for loop and using a dictionary, you could go back an iteration if someone does not put in an appropriate value. If what I'm saying doesn't make much sense, maybe my code can give you a better idea of what I'm trying to do.

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

If the user doesn't put in an appropriate answer, it willl skip that attribute, and 0 will remain as the value. How to I prevent that from happening?

def get_integer(prompt):
    while True:
       try:
          return int(input(prompt))
       except (ValueError,TypeError):
          print("Expecting an integer")

then you just call

my_int = get_integer("Enter score:")

it will guarantee that you get an integer back

you can also make other input helper functions, for example

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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM