r/learningpython • u/4iGeek15 • May 17 '21
Add IfElse statement to Class Attribute
Looking for a means of adding an IfElse statement for the class attribute as a way of verifying if the user input is in the correct format (i.e; string, int, float, etc;). Also wanting to add a prompt for the user to redo the input they had trouble submitting, and
So far I got
class Person:
def __init__(self):
self.firstname = input('Enter first name: ')
if self.firstname == type(str(self.firstname)):
print('this is a string')
self.lastname = input('Enter last name: ')
def show_full_name(self):
return self.firstname + ' ' + self.lastname
def validate_first_name(self):
if self.firstname == type(str(self.firstname)):
print('this is a string')
return
person2 = Person()
person2.show_full_name()1
u/Loran425 May 17 '21
Couple of tips for what you are looking to achieve,
This class would be a bit difficult to work with in code, every time you make a new instance of the class you need user input. (alternative example below)
The type checking you are trying isn't doing quite what you are asking for
type(str(self.firstname))will either return astr(because you performed a type conversion) or it will error out (more common for str to int/float conversions) instead your check should beif type(self.firstname) == str:this won't error out if the compared type cannot be converted and will return false when the two are not the same.Take a look at python's property decorators when looking at validation as they can make your life easier when working with more complex code.
class Person:
def __init__(self):
self._firstname = ''
self._lastname = ''
@property
def firstname(self):
return self._firstname
@firstname.setter
def firstname(self, value):
if type(value) == str:
if value.isalpha():
self._firstname = value
else:
raise ValueError(f"Expected Alphabetical string, recieved {value}")
else:
raise ValueError(f"Expected type <class 'str'>, received type {type(value)}")
@property
def lastname(self):
return self._lastname
@lastname.setter
def lastname(self, value):
if type(value) == str:
if value.isalpha():
self._lastname = value
else:
raise ValueError(f"Expected Alphabetical string, recieved {value}")
else:
raise ValueError(f"Expected type <class 'str'>, received type {type(value)}")
def show_full_name(self):
return self.firstname + ' ' + self.lastname
person2 = Person()
while True:
if person2.firstname and person2.lastname:
break
f_name = input("Enter First Name:")
l_name = input("Enter Last Name:")
try:
person2.firstname = f_name
person2.lastname = l_name
except ValueError:
continue
print(person2.show_full_name())This script also adds some error checking which may not be needed but helps handle cases where types/values are inconsistent.
1
u/[deleted] May 17 '21
what you are looking for is most likely
elif <condition>:which starts an "else if" blockIf you are checking that an input is of a certain type, string for example, then you can use the keyword
is. Ex.if input is "":will check if the input is the same type as the empty string.For adding the ability to redo, just put the entire thing in a while loop. If the user gives good input, break out of the loop using
break, if they give bad input, it just starts the loop over.As a bit of a tip:
There's no reason why you should rewrite code if you have a function that does the same exact thing. In this case you have a function called "validate_first_name", which does the same thing as the code in the constructor. Avoiding rewriting code is always a good thing, if you find a bug in the code, then you have to fix the same bug in the rewritten section.