mark= eval(raw_input(\"What is your mark?\"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print \"This is not a
Actually if you going to use eval() you have to define more things.
acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
try:
mark= eval(int(raw_input("What is your mark?")))
except ValueError:
print ("It's not a number!")
if mark not in acceptables:
print ("You cant do anything but arithmetical operations!")
It's a basically control mechanism for eval().
You can simply cae to float
or int
and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.
try:
mark= float(raw_input("What is your mark?"))
except ValueError:
print "This is not a number"
"Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]
import re
pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")
status = re.search(pattern, raw_input("Enter the Mark : "))
if not status:
print "Invalid Input"
remove eval and your code is correct:
mark = raw_input("What is your mark?")
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
Just checking for a float will work fine:
try:
float(mark)
except ValueError:
print "This is not a number"
you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.
def getInput(prompt):
value = input(prompt)
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)