在Python中运算符重载的概念中,使用while循环来限制用户只输入整数



当用户为变量a&b、 并循环直到用户输入一个整数?这是在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)
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)

相关内容

  • 没有找到相关文章

最新更新