Reputation: 19
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?
Upvotes: 1
Views: 126
Reputation: 113940
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!")
Upvotes: 2