+ 1

Hey I usually test my codes on phone on Dcoder .I got 4/2=2 in only python and 4/2= 2.0 in python3. why?

5th Oct 2018, 1:54 PM
partha
partha - avatar
13 Answers
+ 3
Using int built in function. x=4 print(int(x/2)) #output=2
5th Oct 2018, 5:09 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
Python 2.x assumes the integer result of division as float only if either of operands is float: 4/2 = 2, but 4/2.0 = 2.0 and 4.0/2 = 2.0 Python 3 assumes the result of the division as float no matter if it is integer or not: 4/2 = 2.0
5th Oct 2018, 2:09 PM
strawdog
strawdog - avatar
+ 2
I think Dcoder is using python 2.x. in python3 it will give you output in float.
5th Oct 2018, 4:00 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
partha the reason behind it because a/2 create a float number in python3.x and float values can't multiple with string. but in python2.x a/2 is create a int and int can multiple with string.
5th Oct 2018, 5:02 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
I'm right Dcoder is on python2.x
5th Oct 2018, 5:03 PM
Maninder $ingh
Maninder $ingh - avatar
6th Oct 2018, 3:46 PM
Maninder $ingh
Maninder $ingh - avatar
+ 1
partha , Maninder Singh is right, you need to convert division result to int. This will work in both python branches. // is a floor division, it returns the closest lower integer to the result.
5th Oct 2018, 5:42 PM
strawdog
strawdog - avatar
0
thanks strawdog I did something similar to this on computer , in python 2.7 it gave right answer but have error for the same in 3.7.9 . I'm short on details right now but can you think of anything like that?
5th Oct 2018, 2:14 PM
partha
partha - avatar
0
partha I can not imagine why would python 3.7.9 give you an error in this example, but if you provide more details, we could be able to try to work it out.
5th Oct 2018, 4:46 PM
strawdog
strawdog - avatar
0
hey strawdog and Maninder Singh it's this code a=4 print("hi"*(a/2)) I even tried in Dcoder it's working fine in 'python' but showing error in 'python3'. it's also showing error in sololearn playground
5th Oct 2018, 4:56 PM
partha
partha - avatar
0
Maninder Singh how to get the same result in python 3? Dcoder has both
5th Oct 2018, 5:06 PM
partha
partha - avatar
0
hey Maninder Singh I just got that it can be done this way too a=4 print("hi"*(a//2)) and it worked but can't figure out how(what's "//" for?) though using it in "python" changes nothing
5th Oct 2018, 5:12 PM
partha
partha - avatar
0
thanks Maninder Singh andstrawdog ✌️✌️
6th Oct 2018, 12:28 AM
partha
partha - avatar