First-time poster and very new to Python and programming in general. I have been working on a character creator project and I'm trying to figure out how to deal with a non-integer being typed in for one of the attributes prompts, like "int(input('Strength: ')),"
I want to prevent a crash from the user typing in something other than an integer, and then to prompt the user to input the specific attribute again.
Here's a chunk of the code that I'm talking about.
class Char_presets:
def __init__(self, name, type, strength, dexterity, wisdom, intelligence, faith):
self.name = name
self.type = type
self.strength = strength
self.dexterity = dexterity
self.wisdom = wisdom
self.intelligence = intelligence
self.faith = faith
def create_clss():
c1 = input('Save name?: ')
c1 = Char_presets(
input("What is your name?: "),
input('Class type?: '),
int(input('Strength: ')),
int(input('Dexterity: ')),
int(input('Wisdom: ')),
int(input('Intelligence: ')),
int(input('Faith: '))
)
Thanks for any help.
CodePudding user response:
Determine if the input string is an integer or not, and continue asking if not.
strength = input("Strength: ")
while not strength.isnumeric():
strength = input("That's not an integer! Strength: ")
# at this point, strength will contain an integer
CodePudding user response:
You can utilize the walrus operator introduced in python 3.9:
def create_clss():
c1 = input('Save name?: ')
while (strength := input('Strength: ')): # strength is defined here!
if strength.isdigit(): # check if the input is all digits
break
c1 = Char_presets(
input("What is your name?: "),
input('Class type?: '),
int(strength),
int(input('Dexterity: ')),
int(input('Wisdom: ')),
int(input('Intelligence: ')),
int(input('Faith: '))
)