1

how can I use a for loop in OOP to display an error message when a user inputs something other than an integer for variables a & b, and loop it until the user inputs an integer? This is in the context of operator overloading in Python

class Number:
    
    def __init__(self, x):
        self.x = x
        
        
    def __mul__(self, other):
        x = self.x + other.x
        return x
    
a = Number(int(input("Enter a number: ")))
 
b = Number(int(input("Enter another number: ")))
 
print("\nThose two numbers added together are",a*b)
tytds
  • 61
  • 1
  • 2

1 Answers1

0
class Number:
    
    def __init__(self): # taking in put in init! This will run whenever an object of the class is created
        while True:
            try:
                self.x = int(input("Enter a number: ")) # trying to convert the input to int
                break
            except Exception as exp:
                print(f"Here is your ERROR: {exp}. RETRY!")  # if conversion failed, retry!
        
        
    def __mul__(self, other):
        x = self.x + other.x
        return x
    
a = Number()
 
b = Number()
 
print("\nThose two numbers added together are",a*b)
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22