Dakota R. Rickel Dakota R. Rickel - 1 month ago 10
Python Question

I keep getting a box when printing a variable

I'm trying to print variable c but whenever I do I get "Cost of electricity: $□". But if I print the variable c with print(c) I get "6.122448979591836". So it must be something about substituting the variable in with the % right? I'm using Python 3.5.2 btw. Also I need the number displayed to be 6.12 and using round(c, 2) does nothing. Is it because it's not an int?

# print #100 Cost of Electricity
print("#100 Cost of Electricity")
# get wattage
w = int(input("Enter wattage: "))
# get hours used
h = int(input("Enter number of hours used: "))
# get price per/kWh
p = float(input("Enter price per kWh in cents: "))
# calculate cost
c = w*h/(1000*p)
# print price
print("Cost of electricity: $%c" % int(c))

Not that it matters anymore but I figured why I was so confused. I wasn't using %c because it displayed based on the ASCII values. I thought I had to put %c because I thought I had to put %(variable name). I forgot that what you normally use is %s or %r and that the variable name goes in later. An old book I have for Python 2 says %r is for displaying raw data and %s is for displaying to users.



print("Cost of electricity: $%.2f" % c)

The 'f' flag is for floating point format. The '.2' says print 2 digits after the decimal.