String format and floating points - python

I am trying to reach the .17 after zero how to pick two dec after the zero in this case
i tried the old way with % but wanna discover if that possible with the .format anyone can help?
km = float(input('Enter "km" numbers: '))
conv_fac = 0.621371
round(miles,-2)
miles = km * conv_fac
print('{} km is equal to {} miles'.format(km, miles))
Output:
Enter "km" numbers: 3.5
3.5 km is equal to 2.1747985 miles

You can use {:.2f} to format a float with 2 digits after the decimal point:
print('{:.2f} km is equal to {:.2f} miles'.format(km, miles))
You can also use an f-string:
print(f'{km:.2f} km is equal to {miles:.2f} miles')
You don't have to call round before formatting the floats.
Refer to the string formatting docs for more information.

You can round of to two decimal places as you have attempted but you have to give the decimal point as second argument which is 2 and not -2 like below.
km = float(input('Enter "km" numbers: '))
conv_fac = 0.621371
miles = round(km * conv_fac,2)
print('{} km is equal to {} miles'.format(km, miles))

Related

Avoiding infinite loop in simple Python code [duplicate]

I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back when it should be 4. Is there a way to round up these pennies?
I know the value of a penny is .01, but python reads this as .100000000001 which I believe is the problem.
Any help is appreciated, here is the section I need rounded:
# get the amount to change from the user
change = input("Please enter the amount to change: $")
print "To make change for $",change,"give the customer back:"
# calculate number of twenties
twenties = int(change/ 20)
print twenties, "twenties"
change = change - twenties *20
# calculate tens
tens = int(change / 10)
print tens, "tens"
change = change - tens *10
#calculate fives
fives = int(change / 5)
print fives, "fives"
change = change - fives *5
#calculate ones
ones = int(change / 1)
print ones, "ones"
change = change - ones * 1
#calculate quarters
quarters = int(change / .25)
print quarters, "quarters"
change = change - quarters * .25
#calculate dimes
dimes = int(change / .10)
print dimes, "dimes"
change = change - dimes * .10
#calculate nickels
nickels = int(change / .05)
print nickels, "nickels"
change = change - nickels * .05
#calculate pennies
pennies = int(change / .01)
print pennies, "pennies"
Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.
Integer arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints.
The problem is that 0.01 cannot be accurately represented as a binary floating point value (which is how normal floats are stored – this is true for any language, not just Python). So if you need exact values for dollars and cents, you can use the decimal module. That way you can be sure that your values will be rounded exactly.
Or (since Decimals might be overkill here), first multiply every dollar value by 100 (this is not the same as dividing by 0.01 for the above reasons!), convert to int, do your calculations, and divide by 100.
The problems you are having are a result of imprecise floating-point arithmetic. There is no way to precisely represent 0.01 in IEEE floating point. That is one reason not to use floats when working with currency.
You should use decimals or even integers, because you know there are at most 2 digits after the decimal point. In that case, just work with the amount in pennies.
On the problem itself, I think the easiest way to do it is convert your amount in dollars to the amount in pennies, then iterate through a predefined list of values containing listing the equivalent amount of pennies (in descending order) for each denomination:
def change(amount):
# this can be removed if you pass the amount in pennies
# rather than dollars
amount = int(round(amount*100))
values = [2000, 1000, 500, 100, 25, 10, 5, 1]
denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies']
for i in range(len(values)):
num = amount / values[i]
amount -= num * values[i]
print str(num) + " " + denom[i]
Now calling change(58.79) will print
2 twenties
1 tens
1 fives
3 ones
3 quarters
0 dimes
0 nickels
4 pennies
As seen on codepad.org
use the decimal package
http://docs.python.org/library/decimal.html
it is meant exactly for this kind of use case
>>> from math import ceil
>>> a = 58.79
>>> ceil(a % 0.05 * 100)
4.0
>>>
[edit]
Now that I think of it, might aswell just go with
>>> a = 58.79
>>> a*100 % 5
4.0

python to calculate percent of cars over the speed limit

I'm trying to calculate the percent of cars that go over the speed limit using this code, except there are errors in the second loop and I'm not sure how to use a loop to increment the amount of cars over the speed limit. My end goal is to print out the percent of cars that go above the speed limit. I'm new to programming so any tips or help would be appreciated, thanks :-)
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
if speed > speedLimit
carsAboveLimit =+ 1
i = i +1
percent = int(carsAboveLimit)/len(carSpeeds)
print("The percentage of cars over the speed limit is", percent)
You're doing an euclidian division. The type of carsAboveLimit is int, and it's the same thing for len(carSpeeds).
If you want to get the percent, just multiply by a floating number (typically 1.) like this :
percent = 1. * int(carsAboveLimit)/len(carSpeeds)
The major issues are
You are missing a colon at the end of the if statement
The if statement is only execute once, you didn't put it in a loop
You could change the if statement to:
for car_speed in carSpeeds:
if car_speed > speedLimit:
carsAboveLimit += 1
What this does is go through each item in the list. Each time the value of car_speed becomes the next item in the list.
The division is an integer division, so you won't get a decimal
You need to multiply by 100 to get a percent
Instead specify a float and multiply by 100:
percent = 100 * float(carsAboveLimit)/len(carSpeeds)
If you don't format the final string you will get many trailing digits
You should try it without formating first to see what I mean, then you could change it to:
print "The percentage of cars over the speed limit is %0.2f%%" % percent
Other things
Note that the usual convention for variable in Python is to use underscores instead of camelCase. That is, try to use: speed_limit instead of speedLimit.
You don't need the i variable. My guess is you were trying to have a counter to keep track of the loop maybe? Either way it isn't necessary.
Good luck!
You are missing a colon after if speed > speedLimit
carsAboveLimit is already an int; you do not need to cast it so again.
=+ is not an operator; += is
For a percentage you need to multiply by 100. ie
pct = 100. * carsAboveLimit / len(carSpeeds)
I would suggest writing it like
def get_int(prompt):
while True: # repeat until we get an integer
try:
return int(input(prompt))
except ValueError:
# that wasn't an integer! Try again.
pass
def get_speeds():
while True:
speed = get_int("Enter a car speed (or 0 to exit): ")
if speed == 0:
break
yield speed
def main():
# get list of car speeds
car_speeds = list(get_speeds())
# get number of speeders
limit = get_int("What's the speed limit? ")
num_speeders = sum(1 for speed in car_speeds if speed > limit)
# show % of speeders
pct = 100. * num_speeders / len(car_speeds)
print("{:0.1f} % of them are speeding!".format(pct))
main()
The problem you are facing is one a) casting of float to be able to have a fractional part, since int/int -> int and int/float -> float.
>>> 1/2
0
>>> 1/float(2)
0.5
and b) of proper formatting of the result to be displayed as a percentage value (assuming you want 2 decimal digits):
>>> '%0.2f%%' % (1/float(2))
'0.50%'
Reference to the 2 points mentioned above you can find here and here.
Your code would be complete as follows (including some minor details as other users have mentioned -- colon at if block, increment operator, etc). Note the for loop that was missing in your code but was mentioned:
numCars = int(input("Enter the number of cars: "))
carSpeeds = []
for i in range(numCars):
speed = int(input("Enter the car speed: "))
carSpeeds.append(speed)
carsAboveLimit = 0
speedLimit = int(input("Enter the speed limit: "))
for speed in carSpeeds:
if speed > speedLimit:
carsAboveLimit += 1
i += i
percent = int(carsAboveLimit)/float(len(carSpeeds))
print("The percentage of cars over the speed limit is %0.2f%%" % percent)
With output:
Enter the number of cars: 3
Enter the car speed: 1
Enter the car speed: 2
Enter the car speed: 3
Enter the speed limit: 2
The percentage of cars over the speed limit is 0.33%

getting an answer to two decimal places using the int function

I am brand new to python, only a week or two into my course. Here is what I have written:
#prompt user for input
purchaseAmount = eval(input("please enter Purchase Amount: "))
# compute sales tax
salesTax = purchaseAmount * 0.06
# display sales tax to two decimal points
print("sales tax is", int(salesTax * 100 / 100.0))
and this is what it returns:
please enter Purchase Amount: 197.55
sales tax is 11
My text suggest I should get the answer 11.85.
What should I change to get 2 decimal places in my answer?
You should use the string formatting mini-language.
>>> salesTax = 22.2
>>> print("sales tax is %0.2f" % salesTax)
sales tax is 22.20
Alternatively use the newer format method
>>> salesTax = 22.256
>>> print("sales tax is {:.2f}".format(salesTax))
sales tax is 22.26
Use float instead:
print("sales tax is", round(float(salesTax * 100 / 100.0),2))
This will print the value to 2 decimal places as 11.85
You're taking int of the whole thing, which will always be an integer. You need to first take the int and then divide the result of the int by 100. So instead of this:
int(salesTax * 100 / 100.0)
Do this:
int(salesTax * 100) / 100.0
Its a minor correction. You could use float to get the exact answer with the decimal point. You will lose precision with int.
purchaseAmount = eval(input("please enter Purchase Amount: "))
salesTax = purchaseAmount * 0.06
# get salesTax in floating point number
salesTax = float(salesTax * 100 / 100.0)
print salesTax
-> 11.853

Rounding in Python

Hi everyone I am currently doing a school project and even my teacher is stumped. In Canada the penny has been removed so now all purchases are rounded to either 0 or 5. For example 5.53 would become 5.55 and 5.52 would become 5.50. I am trying to get my program to round like this, but I can't figure out how. I know how to round to decimal places, but I don't know how to round to specifics like this. Any help would be appreciated!
Here is my code. The project is about making a program that a cashier would use in a coffee shop.
order = ['coffee', 'tea', 'hashbrown','jelly','cream','chocolate','glazed','sandwich','bagel','cookie','pannini']
quantity = ['0','0','0','0','0','0','0','0','0','0','0']
# coffee = $1
# Tea = $1.30
# hashbrown = $1.25
# all donuts = $1.50
# sandwich = $2.50
# bagel = $2
# cookie = $0.50
# pannini = $4
cashier = 1
total = 0
while cashier == 1:
print "What did the customer order?"
ordered = input ()
while ordered > 10 or ordered < 0:
print "Do you want to input a valid order?"
ordered = input ()
print "How many are being ordered?"
quantityorder = input ()
quantity[ordered] = quantityorder
print "Ordered",quantityorder,"",order[ordered],"!"
if ordered == 0:
ordered = 1.0
elif ordered == 1:
ordered = 1.30
elif ordered == 2:
ordered = 1.25
elif ordered == 3 or ordered == 4 or ordered == 5 or ordered == 6:
ordered = 1.50
elif ordered == 7:
ordered = 2.50
elif ordered == 8:
ordered = 2
elif ordered == 9:
ordered = 0.50
else:
ordered = 4.0
price = ordered * quantityorder
total = total + price
print "Anything else?"
cashier = input () #If the user inputs 1 then they can input another order if they didn't put in 1 then the program assumes that it is the end of a customers order
print "Your total is $", total * 1.13,"!"
total = total * 1.13
print
print "How much money was given?"
print
money = input ()* 1.0
while money < total:
print "Please input a valid number!"
money = input ()
print "The change should be $",money - total,"!"
This tortured me until I solved it. One rule I set for myself was NOT to use a case-by-case switch on modulo 5, but to use builtin functions. Nice puzzle. wim's "double it, round, then halve it" comment was close.
def nickelround(n):
N = int(n)
print "%0.2f" % (N + round((n - N) * 20) * 0.05)
In [42]:
x=0.57
int(x/0.05)*0.05
Out[42]:
0.55
Usually in these programming problems you're explicitly asked to solve for how to "make change", not just provide the total amount of change due (which is trivial). So you can just in-line the pennies correction into that function:
def make_change(bal):
bal = bal + .02 #correction for no pennies
currency = [20,10,5,1,.25,.1,.05]
change = {}
for unit in currency:
change[unit] = int(bal // unit)
bal %= unit
return change
This particular form returns a dict of change denominations and their corresponding counts.
As you already hinted, use the Decimal class (module decimal). Replace all floats in your code with decimal constructors like Decimal('13.52').
Now the function you want to use is 'quantize'.
You use it like that:
Decimal('1.63').quantize(Decimal('0.5'), rounding=ROUND_HALF_DOWN)
The parameter Decimal('0.5') indicates that you want to round to the halves.
UPDATE:
As the OP wanted to round to the units of 0.05, he must obviously use:
Decimal('1.63').quantize(Decimal('0.05'), rounding=ROUND_HALF_DOWN)
I'm going to be old-school and say, convert your number into a list of values with a null or some kind of tag to represent the decimal.
The make a variable to hold your rounded number and add each value from 1000s or whatever, to 100s, 10s and 1s. (You are looping of course).
Once your loop hits the tag, depending on how far you want to round, (this should be a parameter for your function) throw in a conditional to represent how you want to round ie. 5 means round up, 4 round down (this is another parameter). Then add the final value(s) and return your newly rounded number.
Step 2: Fire your teacher because this is an unbelievably easy problem.
Bare in mind, anyone who knows c or has worked with memory assignment should find this question a breeze.
You could use something as simple as this to round your numbers to a given base:
def round_func(x, base=0.05):
return round(base*round(float(x)/base), 2)
And since you want only 2 decimal places, you can just round it to 2 decimals. The inner round function is to round the given number as per the base, which is 0.05 in your case.
Do you know, how to use own functions?
Add this function to your code:
def nickelround(m):
return round(m/0.05,0)*0.05
and use it:
print "The change should be $", nickelround(money - total),"!"

Python fills string with unnessecary characters

In this Python code, I have the following problem. When the result is displayed, I get a bunch of zeros in the result (see below) - otherwise, the result is correct (the ending numbers of the string). Can anyone spot the error?
def menu():
binNumber = ''
decNumber = float(input("Enter a positive number: "))
decNumber, binNumber = decimalToBinary(decNumber, binNumber)
printResult(binNumber)
def decimalToBinary(dec, bin):
while dec != 0:
remain = dec % 2
dec = dec / 2
if remain > 0.5:
bin += '1'
else:
bin += '0'
return dec, bin
def printResult(binNumber):
print("The binary notation is:", binNumber[::-1]) # the last part is to reverse the string
menu()
This is the result if I type "2"
The binary notation is:
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010
Change
decNumber = float(input("Enter a positive number: "))
to
decNumber = int(input("Enter a positive number: "))
And use integer division. Instead of
dec = dec / 2
use
dec = dec // 2
with these changes, I get the following output
The binary notation is: 10
#Ragnar, before everything I should mention that your code is wrong. I tried to convert 12 and 41 with this code and it failed. To get a complete help, I suggest you to see this question.

Categories