I would like to know how to write >>> print("Size = %4.2f cm" % Size) and what does %4.2f mean

Asked

Viewed 172 times

2

I’m doing a college assignment and I’d like to know what the %4.2f in >>> print("Tamanho = %4.2f cm" % Tamanho) and how a value (8.47826) is represented by following this parameter after the program runs

  • %4.2f = F is the type float, 4 means at least 4 characters; the 2means two decimal places after the comma.

  • >>> print("Size = %4.2f cm" % Size) The task is to represent the number 8.47826 within this programming line. However, when I try Size = 8.47 cm appears that it is wrong. I don’t know what else to do.

  • I get it, you want it rounded down: read this question: https://answall.com/questions/44715/como-rounder-um-float-em-python?noredirect=1&lq=1

  • I got it, but thank you so much for your help!

2 answers

1

Assuming you have the following code:

Tamanho = 8.4726
print("Tamanho = %4.2f cm" % Tamanho)

Then the return of the print using the variable Size of value 8.4726 would be:

Size = 8.47 cm

  • 1

    already got! thanks so much for the help!

1

This is called formatting, this means that you are telling python that the variable output formatting Tamanho that will be displayed in the function print() have a maximum of 4 boxes before the comma and 2 boxes after the comma. % indicates the start of training and f the type of variable you are formatting, ie, float.

However this is a very old format, today the most used is .format() take a look at this documentation here:

https://pyformat.info

Browser other questions tagged

You are not signed in. Login or sign up in order to post.