I have the following two very similar functions:
# Get value as int
def get_int(message):
while True:
try:
number = int(input(message))
return number
except ValueError:
print("Invalid input. Try again.")
# Get value as fraction
def get_fraction(message):
while True:
try:
number = Fraction(input(message))
return number
except ValueError:
print("Invalid input. Try again.")
Now I am wondering if that can be done in a simpler way, by combining these two functions into one. This is my first attemt:
# Get value as specific data type
def get_value(message, data_type):
while True:
try:
number = None
match data_type:
case "int":
number = int(input(message))
case "fraction":
number = Fraction(input(message))
return number
except ValueError:
print("Invalid input. Try again.")
So now I'm passing the data type as an argument. But I am sure there is a simpler way without using a case distinction. Can I pass somehow the real data datype to the function and use this directly in the code?
Fraction?