Exploring Data Types TechGig
The question asked to check out the data type of the user input. It was quite tricky as python by default converts the type of the input into type str. So, I was halfway blank like what approach to use.
Further, I googled & ended up with this article: How You Make Sure input() Is the Type You Want It to Be in Python Unluckily, it introduced me with nothing new concept but, gave me a path to go & explore libraries. And while looking out for them I discovered regex that is regular expressions in python and to this, I thought of adding exception handling.
Finally, trial & test lead me to a code that actually passed out all the test cases. Seriously, Exception handling is a wingman.
Also, keeping below mentioned five custom inputs in mind, I had been able to see the clear picture:
Custom Input 1: Hello Engineer Bae
Expected Output: This input is of type string.
Custom Input 2: 22.33
Expected Output: This input is of type Float.
Custom Input 3: 33
Expected Output: This input is of type Integer.
Custom Input 4: @@
Expected Output: This is something else.
Custom Input 5: #space as input since, space is a character
Expected Output: This input is of type string.
Here we go. The code that is the answer to the exploring data types - day 02 question of techgig.
# Exploring Data Types _ TechGig
import re
def checking():
user_input = input("Enter input: ")
try:
check = int(user_input)
print("This input is of type Integer.")
except ValueError:
try:
check = float(user_input)
print("This input is of type Float.")
except ValueError:
try:
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if regex.search(user_input):
print("This is something else.")
else:
check = str(user_input)
print("This input is of type string.")
except ValueError:
print("This input is of type string.")
checking()
# Exploring Data Types _ TechGig
import re
def checking():
user_input = input("Enter input: ")
try:
check = int(user_input)
print("This input is of type Integer.")
except ValueError:
try:
check = float(user_input)
print("This input is of type Float.")
except ValueError:
try:
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if regex.search(user_input):
print("This is something else.")
else:
check = str(user_input)
print("This input is of type string.")
except ValueError:
print("This input is of type string.")
checking()
No comments:
Post a Comment