basic python help (again) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

basic python help (again)

number = input("the number ") try: if number is not int: print(number + " Is not a number!") else: print("Valid!") except: print("a") raise the code considers numbers not a number too, so its going to execute the if statement no matter what i put in

9th Feb 2021, 2:11 PM
Ok6c
Ok6c - avatar
5 Answers
+ 4
Ok6c , as long as you are not forced to use a try... except... block, you can just use string.isdigit() method like this: number = input("the number ") if not number.isdigit(): print(number. "Is not a number!") else: print("Valid!") but this is only working while using integer numbers. if you also want to check floats, you can perform a conversion in a try... except block.
9th Feb 2021, 3:14 PM
Lothar
Lothar - avatar
+ 1
Use "if not number.isdigit():"
9th Feb 2021, 2:25 PM
Abhay
Abhay - avatar
+ 1
open world games channel type for number will be string unless you convert it to int explicitly like type(int(number))
9th Feb 2021, 2:26 PM
Abhay
Abhay - avatar
+ 1
if number is not int: return True if number is not the int class. as number hold the input() return value, number is always a string. however, if number is str return False also, as number is a str instance, not the str class itself... checking for number inputed could be done by multiple ways, among wich try/except blocks: try: number = int(input()) # if number no error raised print('an integer') except: print("not an integer") ... or by one of the already given answer ;)
9th Feb 2021, 4:45 PM
visph
visph - avatar
0
Use type if type(number)!=int: print(f"{number} is not a number") else: print("valid") except some error as err: print(err)
9th Feb 2021, 2:19 PM
Ireneo language