Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework help
#1
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)
Reply
#2
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.
Reply
#3
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020