Checking to see if a string is an integer or float - python

So I'm creating a program to show number systems, however I've run into issues at the first hurdle. The program will take a number from the user and then use that number throughout the program in order to explain several computer science concepts.
When explaining my first section, number systems, the program will say what type of number it is. I'm doing this by converting the string into a float number. If the float number only has '.0' after it then it converts it into a integer.
Currently I'm using this code
while CorrectNumber == False:
try:
Number = float(NumberString) - 0
print (Number)
except:
print ("Error! Not a number!")
This is useful as it shows if the user has entered a number or not. However I am unsure how to now check the value after the decimal place to check if I should convert it into a integer or not. Any tips?

If the string is convertable to integer, it should be digits only. It should be noted that this approach, as #cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:
if NumberString.isdigit():
Number = int(NumberString)
else:
Number = float(NumberString)
If you already have Number confirmed as a float, you can always use is_integer (works with negatives):
if Number.is_integer():
Number = int(Number)

Not sure I follow the question but here is an idea:
test = ['1.1', '2.1', '3.0', '4', '5', '6.12']
for number in test:
try:
print(int(number))
except ValueError:
print(float(number))
Returns:
1.1
2.1
3.0
4
5
6.12

Here is the method to check,
a = '10'
if a.isdigit():
print "Yes it is Integer"
elif a.replace('.','',1).isdigit() and a.count('.') < 2:
print "Its Float"
else:
print "Its is Neither Integer Nor Float! Something else"

This checks if the fractional-part has any non-zero digits.
def is_int(n):
try:
float_n = float(n)
int_n = int(float_n)
except ValueError:
return False
else:
return float_n == int_n
def is_float(n):
try:
float_n = float(n)
except ValueError:
return False
else:
return True
Testing the functions:
nums = ['12', '12.3', '12.0', '123.002']
for num in nums:
if is_int(num):
print(num, 'can be safely converted to an integer.')
elif is_float(num):
print(num, 'is a float with non-zero digit(s) in the fractional-part.')
It prints:
12 can be safely converted to an integer.
12.3 is a float with non-zero digit(s) in the fractional-part.
12.0 can be safely converted to an integer.
123.002 is a float with non-zero digit(s) in the fractional-part.

Regular expressions are nice for this as they can be custom tailored in case you have some edge-cases. For example:
How do you want to handle padded numbers (numbers with leading zeros). My example here includes this consideration.
Do you need to handle exponents, e.g. 2.3E12 or 2.3e12. This is not handled here.
...in other words, if your implementation doesn't agree with an assumption mine makes, you can change it.
Regular expressions work in all versions of Python (and other languages). They can be compiled for reuse, so should be pretty quick.
# Int is:
# - Only numbers that do NOT start with 0 (protect padded number strings)
# - Exactly 0
re_int = re.compile(r"(^[1-9]+\d*$|^0$)")
# Float is:
# - Only numbers but with exactly 1 dot.
# - The dot must always be followed number numbers
re_float = re.compile(r"(^\d+\.\d+$|^\.\d+$)")
These tests all pass:
def test_re_int(self):
self.assertTrue(re_int.match("1"))
self.assertTrue(re_int.match("1543"))
self.assertTrue(re_int.match("0")) # Exactly 0 is good
self.assertFalse(re_int.match("1.54"))
self.assertFalse(re_int.match("1a4"))
self.assertFalse(re_int.match("14a"))
self.assertFalse(re_int.match("a14"))
self.assertFalse(re_int.match("00")) # Ambiguous
self.assertFalse(re_int.match("0012")) # Protect padding
def test_re_float(self):
self.assertTrue(re_float.match("1.0"))
self.assertTrue(re_float.match("1.456"))
self.assertTrue(re_float.match("567.456"))
self.assertTrue(re_float.match("0.10"))
self.assertTrue(re_float.match(".10"))
self.assertFalse(re_float.match("1.0.0")) # Too many dots
self.assertFalse(re_float.match(".10.0"))
self.assertFalse(re_float.match("..034"))
self.assertFalse(re_float.match("1"))
self.assertFalse(re_float.match("0"))
self.assertFalse(re_float.match("1a4"))
self.assertFalse(re_float.match("14a"))
self.assertFalse(re_float.match("a14"))
self.assertFalse(re_float.match("1.a4"))
self.assertFalse(re_float.match("1.4a"))
self.assertFalse(re_float.match(".a14"))
Please comment if there are any caveats, missing details or regular expression improvements I can make.

Here's my gist that not only checks for positive & negative ints, but also checks for positive & negative floats. It also checks if the string is just a normal non-number.
def int_float_or_string(string):
try:
int(string) # strict and nice
except ValueError:
if is_strictly_float(string): # float() is too permissive, this is better
return "float"
else:
return "string"
else:
return "int"
def is_strictly_float(string):
if string.startswith("-"):
string = string[1:]
return "." in string and string.replace(".", "", 1).isdecimal()
int() is great for checking an integer, but float() has a problem of being too laid back in what it calls a float.

x=input("Enter a value to check it's type: ")
def checknumber(a):
try:
a=float(a)
if int(a)/a==1:
print("This is Integer")
return a
elif a/int(a)>1:
print("This is Float")
return a
except ValueError:
print("This value is String")
return str(a)
x=checknumber(x)```

I rewrite bin Mohammed's answer as follows (number also may be negative):
from numpy import nan, isnan
def is_valid_number(s):
if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
if (s.count('-') == 0):
s_type = 'Positive Integer'
else:
s_type = 'Negative Integer'
elif (s.find('-') <= 0) and (s.count('.') < 2) and \
(s.replace('-', '', 1).replace('.', '', 1).isdigit()):
if (s.count('-') == 0):
s_type = 'Positive Float'
else:
s_type = 'Negative Float'
else:
s_type = "Not alphanumeric!"
return('{}\t is {}'.format(s, s_type))
example:
nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
print(is_valid_number(num))
result:
12 is Positive Integer
-34 is Negative Integer
12.3 is Positive Float
-12.0 is Negative Float
123.0-02 is Not alphanumeric!
12! is Not alphanumeric!
5-6 is Not alphanumeric!
3.45.67 is Not alphanumeric!
minimal code:
from numpy import nan, isnan
def str2num(s):
if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
return(int(s))
elif (s.find('-') <= 0) and (s.count('.') < 2) and \
(s.replace('-', '', 1).replace('.', '', 1).isdigit()):
return(float(s))
else:
return(nan)
example:
nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
x = str2num(num)
if not isnan(x):
print('x =', x) # .... or do something else
result:
x = 12
x = -34
x = 12.3
x = -12.0

Related

Check if Input is Binary

I have this code. I just can't figure out how to make it that only "1" and "0" are accepted.
a = input('Enter a binary number : ')
ar = [int(i) for i in a]
ar = ar[::-1]
res = []
for i in range(len(ar)):
res.append(ar[i]*(2**i))
sum_res = sum(res)
print('Decimal Number is : ',sum_res)
You can use isdigit() or isnumeric()method to allow integers only and use any() to check whether number is binary or not. So, it needs to be like this
if a.isnumeric():
if any([int(i) > 1 for i in a]):
print("Please enter binary numbers only!")
else:
#some code
else:
print("Please enter integers only!")
Use the int constructor with base argument:
try:
user_bin = int(input('Binary number: '), 2)
except ValueError:
print('Binary digits 0-1 only allowed.')
else:
break
There are a few approaches you can follow:
as described in other posts, you could catch the exception of int. Having said that, given that you are rewriting a method which essentially mimics what int(...,2) does, maybe it is a little bit illogical!
you could see if all the elements of the string you entered are 0 or 1, adding in your code a check like this after the input:
if not all(map(lambda x: x in ["0", "1"], list(a))):
print("Only values '0' or '1' should be entered")
return
you could use good old regular expressions:
import re
pattern = re.compile("^[0-1]+$")
...
if not pattern.match(a):
print("Only values '0' or '1' should be entered")
return

Python 3 program about finding the average of integers in a list [duplicate]

How do I check if a user's string input is a number (e.g., -1, 0, 1, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
The above won't work since input always returns a string.
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
See Handling Exceptions in the official tutorial.
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
The method isnumeric() will do the job:
>>>a = '123'
>>>a.isnumeric()
True
But remember:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
EDITED:
You could also use this below code to find out if its a number or also a negative
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
you could also change your format to your specific requirement.
I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.
If you specifically need an int or float, you could try "is not int" or "is not float":
user_input = ''
while user_input is not int:
try:
user_input = int(input('Enter a number: '))
break
except ValueError:
print('Please enter a valid number: ')
print('You entered {}'.format(user_input))
If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:
a = ''
while a.isdigit() == False:
a = input('Enter a number: ')
print('You entered {}'.format(a))
Works fine for check if an input is
a positive Integer AND in a specific range
def checkIntValue():
'''Works fine for check if an **input** is
a positive Integer AND in a specific range'''
maxValue = 20
while True:
try:
intTarget = int(input('Your number ?'))
except ValueError:
continue
else:
if intTarget < 1 or intTarget > maxValue:
continue
else:
return (intTarget)
I would recommend this, #karthik27, for negative numbers
import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
Then do whatever you want with that regular expression, match(), findall() etc
natural: [0, 1, 2 ... ∞]
Python 2
it_is = unicode(user_input).isnumeric()
Python 3
it_is = str(user_input).isnumeric()
integer: [-∞, .., -2, -1, 0, 1, 2, ∞]
try:
int(user_input)
it_is = True
except ValueError:
it_is = False
float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1,
..., ∞]
try:
float(user_input)
it_is = True
except ValueError:
it_is = False
The most elegant solutions would be the already proposed,
a = 123
bool_a = a.isnumeric()
Unfortunately, it doesn't work neither for negative integers nor for general float values of a. If your point is to check if 'a' is a generic number beyond integers, I'd suggest the following one, which works for every kind of float and integer :). Here is the test:
def isanumber(a):
try:
float(repr(a))
bool_a = True
except:
bool_a = False
return bool_a
a = 1 # Integer
isanumber(a)
>>> True
a = -2.5982347892 # General float
isanumber(a)
>>> True
a = '1' # Actually a string
isanumber(a)
>>> False
This solution will accept only integers and nothing but integers.
def is_number(s):
while s.isdigit() == False:
s = raw_input("Enter only numbers: ")
return int(s)
# Your program starts here
user_input = is_number(raw_input("Enter a number: "))
This works with any number, including a fraction:
import fractions
def isnumber(s):
try:
float(s)
return True
except ValueError:
try:
Fraction(s)
return True
except ValueError:
return False
You can use the isdigit() method for strings.
In this case, as you said the input is always a string:
user_input = input("Enter something:")
if user_input.isdigit():
print("Is a number")
else:
print("Not a number")
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.
numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]
for item in numList:
try:
print (item / 2) #You can divide by any number really, except zero
except:
print "Not A Number: " + item
Result:
249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:
I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise
def validate(userInput):
try:
val = int(userInput)
if val > 0 and val < 101:
valid = True
else:
valid = False
except Exception:
valid = False
return valid
If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:
def isnumber(x):
import numpy
try:
return type(numpy.float(x)) == float
except ValueError:
return False
I've been using a different approach I thought I'd share. Start with creating a valid range:
valid = [str(i) for i in range(-10,11)] # ["-10","-9...."10"]
Now ask for a number and if not in list continue asking:
p = input("Enter a number: ")
while p not in valid:
p = input("Not valid. Try to enter a number again: ")
Lastly convert to int (which will work because list only contains integers as strings:
p = int(p)
while True:
b1=input('Type a number:')
try:
a1=int(b1)
except ValueError:
print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})
else:
print ('You typed "{}".'.format(a1))
break
This makes a loop to check whether input is an integer or not, result would look like below:
>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>>
I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.
This was the solution that ended up working well for me to force an answer I wanted:
player_number = 0
while player_number != 1 and player_number !=2:
player_number = raw_input("Are you Player 1 or 2? ")
try:
player_number = int(player_number)
except ValueError:
print "Please enter '1' or '2'..."
I would get exceptions before even reaching the try: statement when I used
player_number = int(raw_input("Are you Player 1 or 2? ")
and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.
This will work:
print(user_input.isnumeric())
This checks if the string has only numbers in it and has at least a length of 1.
However, if you try isnumeric with a string with a negative number in it, isnumeric will return False.
Now this is a solution that works for both negative and positive numbers
try:
user_input = int(user_input)
except ValueError:
process_non_numeric_user_input() # user_input is not a numeric string!
else:
process_user_input()
Looks like there's so far only two answers that handle negatives and decimals (the try... except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.
Looks like it is still quite a lot slower than the try/exceptions method, but if you don't want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:
>>> from timeit import timeit
On Python 3.10 on Windows shows representative results for me:
Explicitly check each character:
>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
0.5673831000458449
>>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.0832774000009522
>>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.9836419000057504
A lot slower than the try/except:
>>> def exception_try(string):
... try:
... return type(float(string)) == int
... except:
... return false
>>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try"))
0.22721579996868968
>>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try"))
0.2409859000472352
>>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try"))
0.45190039998851717
But a fair bit quicker than regex, unless you have an extremely long string?
>>> print(timeit('import re'))
0.08660140004940331
(In case you're using it already)... and then:
>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.3882658999646083
>>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4007637000177056
>>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4191589000402018
None are close to the simplest isdecimal, but that of course won't catch the negatives...
>>> print(timeit('text="1234"; text.isdecimal()'))
0.04747540003154427
Always good to have options depending on needs?
I have found that some Python libraries use assertions to make sure that the value supplied by the programmer-user is a number.
Sometimes it's good to see an example 'from the wild'. Using assert/isinstance:
def check_port(port):
assert isinstance(port, int), 'PORT is not a number'
assert port >= 0, 'PORT < 0 ({0})'.format(port)
I think not doing a simple thing in one line is not Pythonic.
A version without try..except, using a regex match:
Code:
import re
if re.match('[-+]?\d+$', the_str):
# Is integer
Test:
>>> import re
>>> def test(s): return bool(re.match('[-+]?\d+$', s))
>>> test('0')
True
>>> test('1')
True
>>> test('-1')
True
>>> test('-0')
True
>>> test('+0')
True
>>> test('+1')
True
>>> test('-1-1')
False
>>> test('+1+1')
False
Try this! It worked for me even if I input negative numbers.
def length(s):
return len(s)
s = input("Enter the string: ")
try:
if (type(int(s))) == int:
print("You input an integer")
except ValueError:
print("it is a string with length " + str(length(s)))
Here is the simplest solution:
a= input("Choose the option\n")
if(int(a)):
print (a);
else:
print("Try Again")
Checking for Decimal type:
import decimal
isinstance(x, decimal.Decimal)
You can type:
user_input = input("Enter something: ")
if type(user_input) == int:
print(user_input, "Is a number")
else:
print("Not a number")
try:
val = int(user_input)
except ValueError:
print("That's not an int!")
This is based on inspiration from an answer. I defined a function as below. It looks like it’s working fine.
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
a=10
isinstance(a,int) #True
b='abc'
isinstance(b,int) #False

Python 3.4.4 How to verify if a string is only made of 0 and 1

I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.
here's the program:
binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
hopefully someone can help me <3
Follow the EAFP approach, try to convert it to decimal via int() and handle the ValueError:
try:
int(binary, 2)
is_binary = True
except ValueError:
is_binary = False
If you must avoid using int(binary, 2) and handle the exception, you could use the all() function with a generator expression:
all(c in '01' for c in binary)
all() with a generator expression will bail out early and return False when a non-binary digit is found.
If you are already looping over all characters anyway you could just raise an exception in your loop:
binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
try:
while bit>0:
if binary[bit-1] not in '01':
raise ValueError('Not a binary string: %s' % binary)
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
Rather than use an index, your code could just loop over the reverse of the string, using numbers generated by enumerate() as the power:
binary = input("Enter a binary number")
result = 0
try:
for power, bit in enumerate(reversed(binary)):
if bit not in '01':
raise ValueError('Not a binary string: %s' % binary)
result += int(bit) * 2 ** power
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
Use all()
all(x in '10' for x in binary_string)
Maybe all(x in "01" for x in binary).
Following is for 2.7.9, just look for a 3.4.4 parallel:
import re
binary = raw_input("enter binary number")
if re.match("^[01]*$", binary):
print "ok"
You could check if the sum of occurrences of '0' and '1' is equal to the length of the string.
binary.count('0') + binary.count('1') == len(binary)
I suppose checking the input string for correctness is best done with regular expressions. The code that would help you is the following:
import re
binary = input("Enter a binary number")
len_bin = len(binary)
result = 0
if re.search("^[0-1]+$", binary) is not None:
for position in range(len_bin):
result += int(binary[position]) * 2 ** (len_bin - position - 1)
print(binary + " in decimal is equal to " + str(result))
else:
print("The input is not a binary number")
The regular expression determines whether the binary number only contains zeros and ones. Also, I took the opportunity to shorten the code a bit, using result += ..., which is equal to result = result + ....

How to get only numbers as a response in python?

I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any number, but when you type a string value it crashes. here is the code
num1=0;
num2=0;
num3=0;
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
if (num1<num2) and (num1<num3):
print "%i is the smallest number of all three"% num1;
elif (num2<num1) and (num2<num3):
print "%i is the smallest number of all three"% num2;
elif (num3<num2) and (num3<num1):
print "%i is the smallest number of all three"% num3;
elif (num1==num2) or (num1==num3) or (num2==num3):
print "Two equal numbers have been written.";
A simple while loop. You may put this in a function.
while True:
try:
num1=int((raw_input("Type below the first number \n")))
break
except ValueError: # catch the *specific* exception
print("Enter numbers only")
Read more on exceptions:
Handling Exceptions in Python
The most important point is probably to separate concerns, ie. keeping user input separate from validation. You've gotten a couple of good solutions using exceptions. Here is a solution that manually validates the input:
def is_int(strval):
"""A string represents an int if all characters are digits.
Returns True if strval represents a valid int, otherwise False.
"""
for ch in strval:
if not ch.isdigit(): # if '0' <= ch <= '9':
return False
return True
def read_int(prompt='Type number: '):
"""Read one integer from user.
"""
while True:
val = raw_input(prompt)
if is_int(val):
return int(val, 10) # the 10 is the radix (base)
else:
print 'That is not a number.., try again'
numbers = []
for pos in 'first', 'second', 'third':
numbers.append(read_int('Type %s number: ' % pos))
to use the exception handling code, all you have to do is change is_int:
def is_int(strval):
try:
int(strval, 10)
except ValueError:
# int() raised an exception, so strval is not an int
return False
else:
# int() didn't raise an exception, so it is an int
return True
it is also possible to be a bit more concise when finding the smallest:
def smallest(a, b, c):
if b > a < c: # if a is less than both b and c..
return a
if a > b < c:
return b
if a > c < b:
return c
return "Error: two of the numbers must be equal!"
you can call it like so:
smallest(numbers[0], numbers[1], numbers[2])
but Python has a shorthand that does exactly that which looks like:
smallest(*numbers)
def getNumber(i):
try:
num = int(raw_input("type in number %s : " %i))
return num
except Exception as e:
print('This is not a valid number')
return getNumber(i)
numbers = []
for i in range(1,4):
numbers.append(getNumber(i))
print(numbers)
You can simply add the input getting code in try except block and handle the ValueError exception with some meaningful code.
try:
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
except ValueError:
print "Please enter integer only."
exit(-1)

How can I make the program recognize a string input as a wrong answer in an arithmetic quiz? [duplicate]

How do I check if a user's string input is a number (e.g., -1, 0, 1, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
The above won't work since input always returns a string.
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
See Handling Exceptions in the official tutorial.
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
The method isnumeric() will do the job:
>>>a = '123'
>>>a.isnumeric()
True
But remember:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
EDITED:
You could also use this below code to find out if its a number or also a negative
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
you could also change your format to your specific requirement.
I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.
If you specifically need an int or float, you could try "is not int" or "is not float":
user_input = ''
while user_input is not int:
try:
user_input = int(input('Enter a number: '))
break
except ValueError:
print('Please enter a valid number: ')
print('You entered {}'.format(user_input))
If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:
a = ''
while a.isdigit() == False:
a = input('Enter a number: ')
print('You entered {}'.format(a))
Works fine for check if an input is
a positive Integer AND in a specific range
def checkIntValue():
'''Works fine for check if an **input** is
a positive Integer AND in a specific range'''
maxValue = 20
while True:
try:
intTarget = int(input('Your number ?'))
except ValueError:
continue
else:
if intTarget < 1 or intTarget > maxValue:
continue
else:
return (intTarget)
I would recommend this, #karthik27, for negative numbers
import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
Then do whatever you want with that regular expression, match(), findall() etc
natural: [0, 1, 2 ... ∞]
Python 2
it_is = unicode(user_input).isnumeric()
Python 3
it_is = str(user_input).isnumeric()
integer: [-∞, .., -2, -1, 0, 1, 2, ∞]
try:
int(user_input)
it_is = True
except ValueError:
it_is = False
float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1,
..., ∞]
try:
float(user_input)
it_is = True
except ValueError:
it_is = False
The most elegant solutions would be the already proposed,
a = 123
bool_a = a.isnumeric()
Unfortunately, it doesn't work neither for negative integers nor for general float values of a. If your point is to check if 'a' is a generic number beyond integers, I'd suggest the following one, which works for every kind of float and integer :). Here is the test:
def isanumber(a):
try:
float(repr(a))
bool_a = True
except:
bool_a = False
return bool_a
a = 1 # Integer
isanumber(a)
>>> True
a = -2.5982347892 # General float
isanumber(a)
>>> True
a = '1' # Actually a string
isanumber(a)
>>> False
This solution will accept only integers and nothing but integers.
def is_number(s):
while s.isdigit() == False:
s = raw_input("Enter only numbers: ")
return int(s)
# Your program starts here
user_input = is_number(raw_input("Enter a number: "))
This works with any number, including a fraction:
import fractions
def isnumber(s):
try:
float(s)
return True
except ValueError:
try:
Fraction(s)
return True
except ValueError:
return False
You can use the isdigit() method for strings.
In this case, as you said the input is always a string:
user_input = input("Enter something:")
if user_input.isdigit():
print("Is a number")
else:
print("Not a number")
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.
numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]
for item in numList:
try:
print (item / 2) #You can divide by any number really, except zero
except:
print "Not A Number: " + item
Result:
249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:
I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise
def validate(userInput):
try:
val = int(userInput)
if val > 0 and val < 101:
valid = True
else:
valid = False
except Exception:
valid = False
return valid
If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:
def isnumber(x):
import numpy
try:
return type(numpy.float(x)) == float
except ValueError:
return False
I've been using a different approach I thought I'd share. Start with creating a valid range:
valid = [str(i) for i in range(-10,11)] # ["-10","-9...."10"]
Now ask for a number and if not in list continue asking:
p = input("Enter a number: ")
while p not in valid:
p = input("Not valid. Try to enter a number again: ")
Lastly convert to int (which will work because list only contains integers as strings:
p = int(p)
while True:
b1=input('Type a number:')
try:
a1=int(b1)
except ValueError:
print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})
else:
print ('You typed "{}".'.format(a1))
break
This makes a loop to check whether input is an integer or not, result would look like below:
>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>>
I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.
This was the solution that ended up working well for me to force an answer I wanted:
player_number = 0
while player_number != 1 and player_number !=2:
player_number = raw_input("Are you Player 1 or 2? ")
try:
player_number = int(player_number)
except ValueError:
print "Please enter '1' or '2'..."
I would get exceptions before even reaching the try: statement when I used
player_number = int(raw_input("Are you Player 1 or 2? ")
and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.
This will work:
print(user_input.isnumeric())
This checks if the string has only numbers in it and has at least a length of 1.
However, if you try isnumeric with a string with a negative number in it, isnumeric will return False.
Now this is a solution that works for both negative and positive numbers
try:
user_input = int(user_input)
except ValueError:
process_non_numeric_user_input() # user_input is not a numeric string!
else:
process_user_input()
Looks like there's so far only two answers that handle negatives and decimals (the try... except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.
Looks like it is still quite a lot slower than the try/exceptions method, but if you don't want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:
>>> from timeit import timeit
On Python 3.10 on Windows shows representative results for me:
Explicitly check each character:
>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
0.5673831000458449
>>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.0832774000009522
>>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.9836419000057504
A lot slower than the try/except:
>>> def exception_try(string):
... try:
... return type(float(string)) == int
... except:
... return false
>>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try"))
0.22721579996868968
>>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try"))
0.2409859000472352
>>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try"))
0.45190039998851717
But a fair bit quicker than regex, unless you have an extremely long string?
>>> print(timeit('import re'))
0.08660140004940331
(In case you're using it already)... and then:
>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.3882658999646083
>>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4007637000177056
>>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4191589000402018
None are close to the simplest isdecimal, but that of course won't catch the negatives...
>>> print(timeit('text="1234"; text.isdecimal()'))
0.04747540003154427
Always good to have options depending on needs?
I have found that some Python libraries use assertions to make sure that the value supplied by the programmer-user is a number.
Sometimes it's good to see an example 'from the wild'. Using assert/isinstance:
def check_port(port):
assert isinstance(port, int), 'PORT is not a number'
assert port >= 0, 'PORT < 0 ({0})'.format(port)
I think not doing a simple thing in one line is not Pythonic.
A version without try..except, using a regex match:
Code:
import re
if re.match('[-+]?\d+$', the_str):
# Is integer
Test:
>>> import re
>>> def test(s): return bool(re.match('[-+]?\d+$', s))
>>> test('0')
True
>>> test('1')
True
>>> test('-1')
True
>>> test('-0')
True
>>> test('+0')
True
>>> test('+1')
True
>>> test('-1-1')
False
>>> test('+1+1')
False
Try this! It worked for me even if I input negative numbers.
def length(s):
return len(s)
s = input("Enter the string: ")
try:
if (type(int(s))) == int:
print("You input an integer")
except ValueError:
print("it is a string with length " + str(length(s)))
Here is the simplest solution:
a= input("Choose the option\n")
if(int(a)):
print (a);
else:
print("Try Again")
Checking for Decimal type:
import decimal
isinstance(x, decimal.Decimal)
You can type:
user_input = input("Enter something: ")
if type(user_input) == int:
print(user_input, "Is a number")
else:
print("Not a number")
try:
val = int(user_input)
except ValueError:
print("That's not an int!")
This is based on inspiration from an answer. I defined a function as below. It looks like it’s working fine.
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
a=10
isinstance(a,int) #True
b='abc'
isinstance(b,int) #False

Categories

Resources