how to get result based on float or int in python - python

I'm trying to determine result based on the weather the output is int or float.
it just prints same number twice. Whether my input odd or even number.
number = int(input())
mod = number/2
if type(mod) == int():
print(mod)
else:
print(number)

Your type comparison is wrong. Calling a type results in creating an instance of the type with a default value. int() resolves to zero(0) and comparing a type to zero is always false. Remove the parentheses to test for the type correctly.
>>> type(0) == int
True
>>> type(0.0) == float
True
However, the type of the result is fixed in this instance, and the type depends on the version of Python you are running. The result of the division operator(/) changes.
In Python 3, division always returns float, so type(mod) in your example would always be <type 'float'>.
In Python 2, 3/2 (integer divided by integer) gives an int result (rounded toward negative infinity, e.g. 3/2==1 and -3/2==-2), so type(mod) in your example would always be <type 'int'>. Python 2 can be made to work like Python 3 with from __future__ import division.
In both versions, you can force integer division with //.
Examples
Python 2.7
>>> type(2/2)
<type 'int'>
>>> type(3/2)
<type 'int'>
>>> from __future__ import division
>>> type(2/2)
<type 'float'>
>>> type(3/2)
<type 'float'>
>>> type(2//2)
<type 'int'>
>>> type(3//2)
<type 'int'>
Python 3.8
>>> type(2/2)
<class 'float'>
>>> type(3/2)
<class 'float'>
>>> type(2//2)
<class 'int'>
>>> type(3//2)
<class 'int'>
The Fix
If you want to test for whole numbers, use the modulus operator (%) to compute a remainder. Both int and float zero values are considered false:
>>> if 3 % 2:
... print('odd')
...
odd

There's a difference between int and int():
int is the type
int() is calling the type to construct an int; it will always return 0
So your trying to compare a type with 0, which doesn't make sense.
For type checking, use isinstance. Example: isinstance(3, int)

isinstance()
Try isinstance() to compare data types in python. Your Modified Code :
number = int(input())
mod = number/2
print(type(mod))
if isinstance(mod, int):
print(mod)
else:
print(number)
Do Have a Look.

In programming language generally we use typecast concept.First you need to understand the difference between the datatype and functions i.e int and int()
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

Related

With scientific notation, two different floats evaluate as equal

How come the following expression evaluates to true?
In [0]: 1e18 == (1e18 + 50)
Out[0]: True
When replacing the scientific notation by exponentiation, this evaluates, as one would expected, to False:
In [1]: 10**18 == (10**18 + 50)
Out[1]: False
You do not have two pairs of floats. The top example, being scientific notation, is a pair of floats. Since the added difference is less than float precision, they compare as equal.
The bottom example is a pair of integers. You can easily check this with the type function. Python's long integers have no problem keeping the needed 18 digits of accuracy.
>>> type(1e18)
<class 'float'>
>>> type(10**18)
<class 'int'>

String conversion to Number

I'm writing a programming language in python, and I need to convert a String into an Integer or a Floating Point Number depending on what the type of the converted value is. I used ternary operators and even created a function that returned the type of a value as a string:
def rtrn_as_str(value):
return str(type(value))[8:-2]
and this is the output:
>>>rtrn_as_str(123)
'int'
>>>rtrn_as_str('A')
'str'
But I couldn't find a way to convert a string into a float or int like in Javascript. Can anyone help me with this?
If you mean convert 'str' to int or float either, You can try this ;
import ast
number = input("Number : ")
print(type(ast.literal_eval(number)))
Output;
Number : 3
<class 'int'>
Number : 3.14
<class 'float'>
I'm not sure if that's what you are trying to do, but casting a string into float can be easily done:
In [32]: some_string = "1.2"
In [33]: some_string_as_float = float(some_string)
...:
In [34]: print(some_string_as_float)
1.2
In [35]: type(some_string_as_float)
Out[35]: float
If you want to try cast it into integer first:
In [36]: some_other_string = "1"
In [37]: def cast(string):
...: try:
...: return int(string)
...: except:
...: return float(string)
...:
In [38]: cast(some_string)
Out[38]: 1.2
In [39]: cast(some_other_string)
Out[39]: 1

How to prrint the Data Type in Python?

I am new to Python. I have written a simple code to know the Data type of input.
Here is my code.
I gave 2 inputs that are getting convert as a "String". Using the "If" condition to match inputs data type. But my output is weird. I don't know why it is printing the only integer here. Can anyone help me to solve this?
I have added my output also here
Code:
a=str(input("Enter A Value \n"))
b=str(input("Enter B value \n"))
print('\n')
print('A is = ',a)
print('B is = ',b)
if (type(a)==int, type(b)==int):
print('A and B is Integer')
elif (a==str, b==str):
print('A and B is String')
elif (a==float, b==float):
print('\nA and B is Float')
print('\n*Program End*')'
Output:
Enter A Value
abc
Enter B value
def
A is = abc
B is = def
A and B is Integer
*Program End*
(I'm not sure if this is what you're looking for) You can print the data type of something in python using the type() function like so:
var = 25
print(type(var))
Output:
<class 'int'>
The problem is on this line:
if (type(a)==int, type(b)==int)
^ this goes for all the if conditions you have.
That is not the way to use multiple condition on an if statement. In fact, that is just a tuple. So you are saying if (0,0). So. According to documentation
By default, an object is considered true unless its class defines
either a bool() method that returns False or a len() method
that returns zero, when called with the object. 1 Here are most of the
built-in objects considered false:
- constants defined to be false: None and False.
- zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
- empty sequences and collections: '', (), [], {}, set(), range(0)
In this case you are using a tuple with len() != 0 so it will always return True when checked its truth value. So the correct way to check multiple truth conditions is using boolean operators:
a=str(input("Enter A Value \n"))
b=str(input("Enter B value \n"))
print('\n')
print('A is = ',a)
print('B is = ',b)
if type(a)==int and type(b)==int:
print('A and B is Integer')
elif type(a)==str and type(b)==str:
print('A and B is String')
elif type(a)==float and type(b)==float:
print('\nA and B is Float')
print('\n*Program End*')
^ Note I added type() to the other conditions because they weren't present.
Now. There is another issue here:
a=str(input("Enter A Value \n"))
b=str(input("Enter B value \n"))
You are converting to str the input, which is already an str because input give you str, so you will always get:
A and B is String
Because they are both str. So you could use str built-in functions for this:
if a.isnumeric() and b.isnumeric():
print('A and B is Integer')
elif a.isalpha() and b.isalpha():
print('A and B is String')
elif a.replace('.','',1).isdigit() and b.replace('.','',1).isdigit():
print('\nA and B is Float')
The first one is a.isnumeric(), then a.alpha() and for last a workaround to check if it is float: replace the . for a 1 and check if it remains as isdigit().
type() method will return class type
a=5
print(a,"is type of",type(a))
b=2.9
print(b,"is type of",type(b))
c='Hello'
print(c,"is type of",type(c))
Output:
5 is type of <class 'int'>
2.9 is type of <class 'float'>
Hello is type of <class 'str'>
integer=100
print(integer,"is a",type(integer))
string="Python"
print(string,"is a",type(string))
decimal=5.973 #decimal is also called as float.
print(decimal,"is a",type(decimal))
OUTPUT:
100 is a <class 'int'>
Python is a <class 'str'>
5.973 is a <class 'float'>

Python calculated 1.0 of type float converts to zero using int() [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I am new to python, so I expect that I am missing some basic knowledge of types here. I am trying to create a string where I take a floating point number and replace decimal point with a string. In doing so I tried calling a line of code that is equivalent to:
int(pow(10, 1)*(5.1%1)))
But if you run this code:
x = pow(10, 1)*(5.1%1)
print(x)
print(type(x))
print(int(x))
print(int(1.0))
print(type(1.0))
It returns:
1.0
<type 'float'>
0
1
<type 'float'>
I assumed there is a type problem here but they are both type float. So why does int(x) return zero but not int(1.0)?
Due to rounding error, you didn't get exactly 1, but a bit less
>>> x = pow(10, 1)*(5.1%1)
>>> print '{:.20f}'.format(x)
0.99999999999999644729
You are just getting a bunch of other things rounding up for you when you display it
>>> x = pow(10, 1)*(5.1%1)
>>> print x
1.0
>>> print '{:.10f}'.format(x)
1.0000000000
To get something displayed that will definitely give the same number (slightly better for debugging), use repr out of habit
>>> x = pow(10, 1)*(5.1%1)
>>> print repr(x)
0.9999999999999964
>>> print 'hello {!r} world'.format(x)
hello 0.9999999999999964 world

Type-Checking in Functions between Python 2.7 and Python 3.3

In my functions, I check for the types of the input so that it is valid (example - for a function that checks the primality of 'n', I don't want 'n' to be inputted as a string).
The problem occurs with checking for longs and ints.
In Python 3.3, they removed the long-type number, so the problem occurs with this:
def isPrime(n):
"""Checks if 'n' is prime"""
if not isinstance(n, int): raise TypeError('n must be int')
# rest of code
This works universally for both v2.7 and v3.3.
However, if I import this function in a Python 2.7 program, and enter a long-type number for 'n', like this: isPrime(123456789000), it would obviously raise a TypeError because 'n' is of the type long, not int.
So, how can I check if it is valid input for both v2.7 and v3.3 for longs and ints?
Thanks!
A way I can think of is:
from numbers import Integral
>>> blah = [1, 1.2, 1L]
>>> [i for i in blah if isinstance(i, Integral)]
[1, 1L]
edit (after an insightful comment from #martineau)
Python 2.7:
>>> map(type, [1, 1.2, 2**128])
[<type 'int'>, <type 'float'>, <type 'long'>]
Python 3.3:
>>> list(map(type, [1, 1.2, 2**128]))
[<class 'int'>, <class 'float'>, <class 'int'>]
The example still stands that using isinstance(n, numbers.Integral) but stands more coherent.
def isPrime(n):
"""Checks if 'n' is prime"""
try:
n = int(n)
except:
raise TypeError('n must be int')
# rest of code
From: http://docs.python.org/3.1/whatsnew/3.0.html#integers
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
if not isinstance(n, int) or n > sys.maxsize: raise TypeError('n must be int')
may work for differentiating int and long.

Categories

Resources