Advertisement
ozozx235

number input filter

Aug 30th, 2024 (edited)
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | Software | 0 0
  1. num = ""#starts as empty string
  2. neg = False
  3. while type(num) == str:#loops so long as input remains string (cannot parse to int / float)
  4.     num = input("Enter a number: ").strip()#new input
  5.     if num[0] == "-":#check for negative number
  6.         neg = True
  7.         num = num[1:]#remove negative sign
  8.     if num.isnumeric():#if can be parsed into int
  9.         num = int(num)
  10.     elif num.count(".") == 1 and num.replace(".","").isnumeric():#if has only one '.' and once removed can be parsed into int
  11.         num = float(num)
  12.     else:
  13.         print("Invalid input, try again")
  14.         neg = False#if invalid input started with '-', set negative back to false for the next number
  15. if neg:
  16.     num = num*-1# if number was negative, add back negative sign by multiplying (-1)
  17. print("{}({})".format(str(type(num))[8:-2],num))#prints result as number, cast into class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement