1

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?

clinomaniac
  • 2,200
  • 2
  • 17
  • 22
Duane
  • 19
  • 5
  • 6
    You don't go back in the loop, instead you put a while-loop around the user input and keep asking the user until the input satisfies the requirements (you may want to give the user a chance to exit the process, though). – Mike Scotty Feb 28 '18 at 23:02
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Mar 01 '18 at 00:34

1 Answers1

2
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!")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179