Python Forum

Full Version: Homework help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My teacher requirement is to use format() function to display the result of the division to 2 decimal places and inform the user that only 2 decimal places are being shown but I have a problem with that.
Is there any way that when I do the division, for example, 7.5/3 will show 2.5 instead of 2.50? Because when I run the code it just only shows 2.50 not 2.5
'''This program demonstrated input,output and numeric operations
Created by Khanh Cao
01/14/2020'''
name=input("What is your name? ")
print("Hello",name)
firstnumber=float(input("Enter first number: "))
secondnumber=float(input("Enter second number: "))
sum=firstnumber + secondnumber
minus=firstnumber - secondnumber
times=firstnumber * secondnumber
divide=firstnumber / secondnumber
remainder=firstnumber % secondnumber
print ("The sum of", firstnumber, "and",secondnumber,"is: ",sum)
print (firstnumber, "minus", secondnumber, "is: ", minus)
print (firstnumber, "times", secondnumber, "is: ", times)
print (firstnumber, "divided", secondnumber, "is: ", format(divide,'.2f'))
print (divide, "rounded to 2 decimal places is: ", format(divide, '.2f'))
print ("The remainder of dividing", firstnumber,"and", secondnumber, "is: ",remainder)
2.50 is 2 decimal places. "Decimal places" are the numbers to the right of the decimal. 2.5 is 1 decimal place.

Your '.2f' is telling python to chop of everything beyond two places.

Allow me to suggest this page https://thepythonguru.com/python-string-formatting/ as additional reading.
There are also pretty good examples at pyformat.info. If one wants to master strings it's also necessary to be acquainted with f-strings.