I am trying to write a python script that divides two numbers and then stores the value of the first digit after the decimal point but first I want to print the answer of the division.
example:
31/7 should be 4,428 but when I use
def spiel():
anzahl=int(raw_input("Anzahl der Spieler"))
spieler=int(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q
I get the answer 4.00, what have I done wrong.
If you could tell me how I can store the first decimal point after the decimal point THAT WOULD BE AMAZING!
Thanks in advance
In python2.7:
If you divide two integer, answer will be integer always as it will skip the decimal value.
If you want precise float output, try this:
>>>float(10)/3
>>>3.3333333333333335
Any of the value should be float.
You're dividing an int by an int. You should use floats
def spiel():
anzahl=float(raw_input("Anzahl der Spieler"))
spieler=float(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q
In response to comment:
There are multiple ways to do that, what's best would depend on your applicaiton:
q =anzahl/spieler
print "{}".format(int(10*(q%1)))
print "{}".format(int((q-int(q))*10))
print "{}".format(str(a).split(".")[1][0])
and probably some easier ones that I didn't think of
The thing that you are doing wrong here is, you are making it believe that operands of division are integers( during division) .
I am sure you want to take two integers. You can do following things:
use float() during division. In here you do not need to convert both Anzahl and spieler to float. Just convert spieler :
q = anzahl/float(spieler)
**2. Use future module. then you do not need to change anything in your code. Write the following line at the beginning of your code :
from __future__ import division
Use Python 3. In python 3 '/' means you will non-truncating division and '//' means truncating division
If you divide an integer by an integer you will receive an integer. An integer is a whole number, no decimal points.
If you divide a float/integer by a float you will receive a float. A float is a whole number, including decimal points.
When you are doing your operations, change spieler to a float. That can be done with float(spieler).
Your code will look like this:
def spiel():
anzahl=int(raw_input("Anzahl der Spieler"))
float(spieler)=int(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q
Related
When calculating the following 2**1000 for example you get the whole value
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
But if you do the same for a float i.e 1.2**1000 it gives
1.5179100891722457e+79
Is there a built-in way to get the whole value of such a calculation (Not in scientific notation)?
The reason for the behavior you're seeing is that the first expression results in an integer since both of its operands are integers, while the second expression is a floating point number because one of the operands is a float. To get the result you want, you can cast the result of the second expression to an int:
>>> int(1.2**1000)
15179100891722457049849556131606991918673074938672571271083893226004713928916992L
You should be able to use format()
a = 1.2**1000
print(format(a, 'f'))
Gives the output 15179100891722457049849556131606991918673074938672571271083893226004713928916992.000000
Try casting to an integer.
int(1.2 ** 1000)
If you want to get decimals though you'll need to do some additional work depending on your goal
You can use this to print it
print("{:.3E}".format(1234567890987654321))
This will output:
1.235E+18
You can also have decimal values. It will format it similarly.
print("{0:.3E}".format(1234567890987654321.98765432))
1.235E+18
If you want to get the full number printed, then you can do the following:
y = 1234567890987654321.98765432
print(f"{y:.22}")
It will output:
1234567890987654400.0
I want to convert string number to float and keep zeros at the end like this f=float('.270') and f should be 0.270, not 0.27 or '0.270' how I can do it?
Depending of the application, you should use the Decimal lib - specially if you are dealing with critical calculations like money
https://docs.python.org/3.8/library/decimal.html
import decimal
decimal.getcontext().prec = 3
f = decimal.Decimal('0.270')
print(f)
Or simply "%.3f" % f
Have you considered saving the float as a string rather than a float? If needed for calculations then it can be casted to a float. If you need to have this for significant figures, then this article on rounding numbers in Python should help. It uses the format() method.
I hope this was able to help!
phylo
I'm trying to take a large integer, ie: 123123123 and format it with 3-digits of precision and commas. Format can add the commas using:
'{:,}'.format(123123123) # '123,123,123'
And specify precision for floating points:
'{0:.2f}'.format(3.141592) # '3.14'
But what if I want to do both?
ie:
'{:,3d}'.format(123123123) # ValueError
I would like to have it return: 123,000,000
There is no way to do this directly. The whole point of Python integers is that they're infinite-precision; if you want to round them, you have to do it explicitly. In fact, when you attempted the obvious, the message in the exception told you this:
>>> '{:,.3d}'.format(123123123)
ValueError: Precision not allowed in integer format specifier
So, your attempt at this is in the right directly… but it's more than a little funky:
'{:,.0f}'.format(round(123123123,-6))
There's no reason to explicitly force the int to a float just so you can print it without any fractional values. Just let it stay an int:
'{:,}'.format(round(123123123, -6))
Besides being simpler, this also means that when you try to one day print a giant integer, it won't give you an OverflowError or lose more digits than you wanted…
In earlier versions of Python (that is, 2.x), where round always returns float no matter what type you give it, you can't do that; you will probably want to write a trivial intround function instead. For example:
def intround(number, ndigits):
return (number + 5 * 10**(-ndigits-1)) // 10**-ndigits * 10**-ndigits
If you know for a fact that you will never have an integer too large to fit losslessly into a float, you can just use int(round(*args)) instead—but really, if you can avoid converting integers to floats, you should.
And, while we're at it, there's no reason to build up a {} string to call the format method on when you can just call the free function:
format(round(123123123, -6), ',')
The 'right' way to do this that is Python version independent (well -- it has to have with so 2.5+) is use the Decimal module:
from __future__ import print_function
import decimal
import sys
if sys.version_info.major<3:
ic=long
else:
ic=int
def ri(i, places=6):
with decimal.localcontext() as lct:
lct.prec=places
n=ic(decimal.Decimal(i,)+decimal.Decimal('0'))
return format(n,',')
print(ri(2**99, 4))
# 633,800,000,000,000,000,000,000,000,000
print(ri(12349159111, 7))
# 12,349,160,000
print(ri(12349111111, 3))
# 12,300,000,000
If you use the round method it is fairly fragile on Python 2:
Python 2:
>>> format(round(12349999999999999,-6),',')
'1.235e+16' # wrong....
It works on Python 3, but this is the way to do it so the rounding is left to right:
def rir(i, places=6):
return format(round(i, places-len(str(i))), ',')
print(rir(2**99, 4))
# 633,800,000,000,000,000,000,000,000,000
print(rir(12349159111, 7))
# 12,349,160,000
With a negative offset for ndigits, round(number[, ndigits]) will round the mantissa of the floating point right to left:
>>> round(123456789,-4)
123456789123460000
Works great on Python 3 with larger numbers:
>>> round(123456789123456789,-8)
123456789100000000
On Python 2, the functionality breaks with larger numbers:
>>> round(123456789,-4)
123460000.0
>>> round(123456789123456789,-4)
1.2345678912346e+17
With the decimal module, it works as expected on Python 2 and Python 3.
Looking to format a output to show a very small number..
a= 6500
b= 3600
c=.000900
d= int((b/a)-c)
print d
Answer comes out to be zero, but looking for the .###### numbers after the .
sorry try this
Looks like you got bitten by integer division in python 2.x.
>>> a= 6500
>>> b= 3600
>>> c=.000900
>>> from __future__ import division
>>> print b/a - c
0.552946153846
There may be two issues with your calculation:
If you're using Python 2, division using / between two integers will always be an integer also. This will discard the fractional part of the calculation, which can be unexpected. One fix for this is to force one of the values to be a float value (e.g. float(b)/a). An alternative is to put at the top of your file from __future__ import division, which tells Python to use the Python 3 semantics for division (you'll only get an integer from integer division if the result is an exact integer).
The second issue seems to be about formatting a floating point value. First you seem to want only the fractional part of the value (not the integer part). Usually the best option is to simply subtract the integer part of the value:
d = someFloatingPointValue()
d_frac = d - int(d)
Next, to get a string to output (where you want several decimal places, but not a huge number of them), you probably want to explore Python's string formatting operations:
d = someFloatingPointValue()
d_to4decimalPlaces = "{:.4f}".format(d)
I'm a programming newbie having difficulty with Python multiplication. I have code like this:
def getPriceDiscount():
price = int(input())
if price > 3000:
priceDiscount = price * 0.6
return priceDiscount
else:
return price
But when I execute it and type an input which is a decimal number like 87.94, I get the following error:
ValueError: invalid literal for int() with base 10: '87.94'
Isn't the int() method able to convert the string '87.94' into a number allowing me to multiply it by 0.6? What should I do to perform that conversion?
I'm using Python 3.2.2.
Actually, you CAN pass a floating point value to int(). In that case int() just rounds the number down and converts that value to an integer type.
However, what you're doing when you call int("87.94") is passing a string resembling a decimal point value to int(). int() can't directly convert from such a string to an integer. You hence must use float(), which can convert from strings to floats.
You can't pass a string with a decimal point to int(). You can use float() instead. If you want only the integral part i.e. to truncate the .94 in 87.94, you can do int(float('87.94')).
An int (short for "integer") is a whole number. A float (short for "floating-point number") is a number with a decimal point.
int() returns an int created from its input argument. You can use it to convert a string like "15" into the int 15, or a float like 12.059 into the int 12.
float() returns a float created from its input argument. You can use it to convert a string like "10.5" into the float 10.5, or even an int like 12 into the float 12.0.
If you want to force price to be an integer, but you want to accept a floating point number as typed input, you need to make the input a float first, then convert it with int():
price = int(float(input())
Note that if you multiply an int by a float such as your discount factor, the result will be a float.
Also note that my example above doesn't round the number -- it just truncates the stuff after the decimal point. For example, if the input is "0.6" then price will end up being 0. Not what you want? Then you'll need to use the round() function on the float first.
price = int(round(float(input()))
If you intended to use floating point calculations (which makes sense if we're talking about a commodity price), then don't perform the int conversion. Just use float. You may still want to do some rounding. If you want to round to 2 decimal places, you can call round with the second argument as 2:
price = round(float(input()),2)
Finally, you might want to look into Python's decimal module, since there are limitations when using floating point numbers. See here for more information: http://docs.python.org/tutorial/floatingpoint.html
def getPriceDiscount():
while True:
try:
price, percent = float(input()), 0.6
break
except ValueError:
continue
return price * percent if price > 3000 else price
print(getPriceDiscount())
The problem is that you're trying to do two convertions at a time, and one of them is implicit.
The following will work because there's an obvious way to transfrom the number '87' to the integer 87.
>>> int('87')
87
And for the same reason, the following will work too:
>>> float('87')
87.0
>>> float('87.94')
87.94
>>> int(87.94)
87
Keep in mind what's been said and look at the difference between:
>>> int(float('87.94'))
87
and
>>> int('87.94')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '87.94'
As you see the problem is that you're implying a float() conversion before passing to int(), but how could the compiler guess that? There are plenty of available working conversions for the string '87.94'. Should the compiler tried them all before finding out which onw will work with int? And what if there are two or more that will return something that will work with integer?
Examples:
>>> int(hash('87.94'))
4165905645189346193
>>> int(id('87.94'))
22325264
>>> int(max('87.94'))
9
>>> int(input('87.94'))
87.94111
111
Should the compiler choose float() for you?
I don't think so: Explicit is better than implicit.
Anyway if you are going to use that number to perform a multiplication with a float number 0.6. You could directly convert it to a float().
Change this line:
price = int(input())
with:
price = float(input())
And everything will be ok.
Also, the operation you are presenting in your example is a multiplication, not a division. In case you might be interested, there is the floor division // that will return an integer insted of a float. Take a look at PEP238 for more informations about this.