Is x in int(x) numeric/non-numeric string? - python

In the code below, int(x) throws an exception. I understand that x should be a string but -numeric or non-numeric string?
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz")

The string you supply as the function argument has to be representable as an integer. What would you consider the numerical representation of "xyz" to be?
If you pass the function string representations of numbers, positive or negative, then you won't trigger the exception.
When numbers are encoded as strings there are no problems,
>>> int("10")
10
>>> int("-10")
-10
When symbols that aren't readily represented by a number is supplied to the function the exception will triggered,
>>> int("-10a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-10a'
int(x) does not accept floating-point numbers either:
>>> int("10.0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.0'

Related

ZeroDivisionError: as 'integer division or modulo by zero' but get as 'division by zero

I want to get the exception of ZeroDivisionError: as 'integer division or modulo by zero', but I get as 'division by zero'. How can I get that?
a=int(input())
b=[]
for i in range(a):
b.append(list(input().split()))
try:
print(int(int(b[i][0])/int(b[i][1])))
except Exception as e:
print( "Error Code: ", e)
The Python exception is ZeroDivisionError:
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
If you are trying to handle the exception, do an:
except ZeroDivisionError as e:
instead of trying to match the exception description.
If this answer doesn't cover you, please expand on what your needs are and why, so that we help you.
PS A naïve way to accomplish what you seem to ask:
>>> try: 1/0
... except ZeroDivisionError:
... raise ZeroDivisionError('integer division or modulo by zero')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
ZeroDivisionError: integer division or modulo by zero
I'm sure you have a reason for wanting the specific error message (maybe to understand float vs int division) so I'll address that.
Even though there is only one divide by zero exception (ZeroDivisionError) it's given with a different error message depending on the types used and the operation involved.
If you're trying to get the integer division exception message ("integer division or modulo by zero"), you need to perform integer division specifically using // instead of /. Converting numbers to integers with int() before or after dividing doesn't make / perform integer division.
As an example of how the error messages vary depending on the types involved:
>>> 5 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 5.0 / 0.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
>>> 5 // 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 5.0 // 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float divmod()
The above pertains to Python 3. / division in Python 2 of two int objects where the denominator is zero would result in the "integer division or modulo by zero" message.

Python: invalid literal for int() with base 10

I'm getting an invalid literal for int() with base 10 where it seems as if the input stream is concatenating values generated in a loop.
def collectData():
lst = makeCases()
cases = int(input())
for i in range(cases):
size = int(input())
case = []
for j in range(size):
value = int(input())
case +=[value]
insert(lst,case)
return lst
That is the function generating the issue. The value and size variables are the problem as they seem to concatenate subsequent values before the conversion.
The makeCases() function generates a tuple on the form ("Case",[]).
EDIT: The code works fine locally but won't work in the hackerrank IDE
As Tom Karzes has said, input() is returning something other than a number. Looking at the error message that is produced by Python, I assume you are using Python 3 but I will cover Python 2 too.
Python 2
input() checks if the given input from stdin is something it can evaluate to. It is equivalent to eval(raw_input()). (Pydoc)
>>> a = input()
123
>>> a
123
>>> abc = 3
>>> a = input()
abc
>>> a
3
It produces a different error when you input() something it cannot eval:
>>> a = input()
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
Since it performs eval on the given input, it will assume that abc may be a variable name. It searches for it but throws an error because it couldn't find it.
Python 3
input() is the new raw_input() in Python 2. input() returns a string even if the given input is a number. (Pydoc)
>>> a = input()
123
>>> a
'123'
This is the most likely reason you would convert it to an int() after you get an input().
I can replicate your error message as so (in Python 3):
>>> a = int(input())
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> a = int(input())
123 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123 123'
In conclusion, the most likely reason why it is returning such an error is because you are giving it something it cannot convert to an int.

"Type Error: range() integer end argument expected, got float" even using int()

Here is the complete code. What's confusing me is that I'm using int to turn the ceiling of l/2 into an integer and it's still not working. The error would have to be elsewhere in the code unless... well I dun goofd. Thanks
def switcheroo(vec):
from math import ceil
from __future__ import division
l = len(vec) - 1
holdingcell = []
for i in range(int(ceil(l/2))):
holdingcell = vec[i]
vec[i] = vec[l-i+1]
vec[l-i+1] = holdingcell
return vec
The error I am getting is:
>>> o = switcheroo(v)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "switcheroo.py", line 8, in switcheroo
for i in range(int(ceil(l/2))):
TypeError: range() integer end argument expected, got float.

Is there any object can make str() function throw error or exception in python?

I have a function that requires the input to be a string.
I know I can assert or do check on the input type, but I would like to handle that as much as possible.
I have following code to handle that. But I'm wondering if there's any case that this line can throw exception that I need to handle.
def foo(any_input):
clean_input = str(any_input) # will this throw any exception or error?
process(clean_input)
Yes, some unicodes:
>>> str(u'í')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 0: ordinal not in range(128)
You might get a RuntimeError while trying to str a deeply-nested list:
>>> x = []
>>> for i in range(100000):
... x = [x]
...
>>> y = str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded while getting the repr of a list
or a MemoryError trying to str a huge list:
>>> x = 'a'*1000000
>>> y = [x] * 1000000 # x and y only require a few MB of memory
>>> str(y) # but str(y) requires about a TB of memory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
I mean, you could trivially make one:
class BadStr:
def __str__(self):
raise Exception("Nope.")

Best Python Input method for Integers

In python 2.7, if we take an integer as input, which one is more faster and efficient or there is no difference at all:
input() or int(raw_input())
From the Python docs
input([prompt])
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
int(raw_input()) will be faster, more secure and produce less confusing results.
Consider:
>>> b = 5
>>> a = input()
[1, 2, 3]
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> a = int(raw_input())
[1, 2, 3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '[1, 2, 3]'
The ValueError raised when reading input is far more desirable than the TypeError raised when using the variable.

Categories

Resources