I keep getting a box when printing a variable [duplicate] - python

This question already has answers here:
What does %c character formatting do in Python and it's use?
(3 answers)
Closed 6 years ago.
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.

Use:
print("Cost of electricity: $%.2f" % c)
The 'f' flag is for floating point format. The '.2' says print 2 digits after the decimal.

Related

Program printing a number a certain times instead of multiplying [duplicate]

This question already has answers here:
Why does multiplication repeats the number several times? [closed]
(7 answers)
Closed 1 year ago.
I’ve written a piece of code that instead of print the product, prints a number a certain number of times. Whats wrong with it?
twelve = 12
name = input("What is your name? \nAnswer: ")
print("Cool name!")
nums = input("\n\nHow much pocket money did you receive last month?\nAnswer: ")
total = nums * twelve
print("\n\nI think you get ", total + " pounds in pocket money per year! Nice!")
The reason is that your nums variable is a string, which is the default with all Python inputs. Try converting it to int:
nums = int(input(...))
Or float if you are inputting a floating point number.

Everything appears to be defined as a string? Python [duplicate]

This question already has answers here:
Specify input() type in Python?
(2 answers)
Closed 4 years ago.
I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me.
The current script I have is:
x = input()
print(x)
print(type(x))
However, regardless of i input a string, integer or float it will always print string? Any suggestions?
In Python input always returns a string.
If you want to consider it as an int you have to convert it.
num = int(input('Choose a number: '))
print(num, type(num))
If you aren't sure of the type you can do:
num = input('Choose a number: ')
try:
num = int(num)
except:
pass
print(num, type(num))
1111 or 1.10 are valid strings
If the user presses the "1" key four times and then Enter, there's no magic way to tell if they wanted to enter the number 1111 or the string "1111". The input function gives your program the arbitrary textual data entered by user as a string, and it's up to you to interpret it however you wish.
If you want different treatment for data in particular format (e.g. if they enter "1111" do something with it as a number 1111, and if they enter "111x" show a message "please enter a valid number") then your program needs to implement that logic.

Python 2.3: how can get exact float value after conversation? [duplicate]

This question already has answers here:
How to display a float with two decimal places?
(13 answers)
Closed 6 years ago.
x="1,234.00"
y =x.replace(',','')
k = float(y)
print k
output=1234.0 but i need 1234.00 value
please solve this problem
There is no difference in value between 1234.0 and 1234.00. You can't save more or less non-significant digits in a float.
However, you can print more or less (non-)significant digits. In older versions of python you can use the % method (documentation). In Python 2.7 and up, use the string format method. An example:
f = float('156.2')
# in Python 2.3
no_decimals = "%.0f" % f
print no_decimals # "156" (no decimal numbers)
five_decimals = "%.5f" % f
print five_decimals # "156.20000" (5 decimal numbers)
# in Python 2.7
no_decimals = "{:.0f}".format(f)
print no_decimals # "156" (no decimal numbers)
five_decimals = "{:.5f}".format(f)
print five_decimals # "156.20000" (5 decimal numbers)
If you for some reason have no access to the code that prints the value, you can create your own class, inherit from float and supply your own __str__ value. This could break some behaviour (it shouldn't, but it could), so be careful. Here is an example:
class my_float(float):
def __str__(self):
return "%.2f" % self
f = my_float(1234.0)
print f # "1234.00"
(I ran this on Python 2.7, I have 2.3 not installed; please consider upgrading Python to 2.7 or 3.5; 2.3 is seriously outdated.)

Meanings of percent sign(%) [duplicate]

This question already has answers here:
What does % do to strings in Python?
(4 answers)
Closed 8 years ago.
Can you explain what this python code means.
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
The output for the print is
x 3
y 5
The '3' and '5' are values of '(v.varName, v.x)' I don't get how it knows to print 'x' and 'y' and what other uses are there for '%' other than finding the remainder.
The command
for v in m.getVars():
Assigns the list of all Var objects in model m to variable v.
You can then query various attributes of the individual variables in the list.
For example, to obtain the variable name and solution value for the first variable in list v, you would issue the following command
print v.varName, v.x
You can type help(v) to get a list of all methods on a Var object
As others mentioned % is just place holders
To understand how your code works, inspect the model m
It is a way to simplify strings when contain many variables. In python, as you see, you made a string in your print statement which reflects the variables v.varName and v.x. When a percent sign is used in a string, it will be matched, in order, with the parameters you give it.
There are specific letters used for each TYPE of variable. In your case you used "s" and "g" representing a string and a number. Of course numbers are turned into strings if you are creating a string (like in this case).
Example:
x = 20
y = "hello"
z = "some guy"
resulting_string = "%s, my name is %s. I am %g years old" % (y, z, x)
print resulting_string
The result will be:
hello, my name is some guy. I am 20 years old
Notice that the order in the variables section is what gives the correct ordering.

unsupported operand type(s) for /: 'str' and 'int' [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is:
Hours = raw_input ("How many Hours you worked for today : ")
minutes = (Hours * 60)
Percentage = (minutes * 100) / 60
print "Today you worked : ", "percentage"
You have to convert your Hours variable to a number, since raw_input() gives you a string:
Hours = int(raw_input("How many hours you worked for today: "))
The reason why this is failing so late is because * is defined for string and int: it "multiplies" the string by the int argument. So if you type 7 at the prompt, you'll get:
Hours = '7'
minutes = '777777....77777' # 7 repeated 60 times
Percentage = '77777....77777' / 60 # 7 repeated 60*100 = 6000 times
So when it tries to do / on a string and a number it finally fails.
Hours is read as a string. First convert it to an integer:
Hours = int(raw_input("..."))
Note that Hours*60 works because that concatenates Hours with itself 60 times. But that certainly is not what you want so you have to convert to int at the first opportunity.
Your value Hours is a string. To convert to an integer,
Hours = int(raw_input("How many hours you worked for today : "))
Values in Python have a specific type, and although a string may contain only digits, you still can't treat it as a number without telling Python to convert it. This is unlike some other languages such as Javascript, Perl, and PHP, where the language automatically converts the type when needed.
raw_input() returns a string. Convert it to a number before proceeding (since multiplying a string by an integer is a valid operation).

Categories