如何在python中将输入数字转换为百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28142688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to turn input number into a percentage in python
提问by Griffin Filmz
print ("How much does your meal cost")
meal = 0
tip = 0
tax = 0.0675
action = input( "Type amount of meal ")
if action.isdigit():
meal = (action)
print (meal)
tips = input(" type the perentage of tip you want to give ")
if tips.isdigit():
tip = tips
print(tip)
I have written this but I do not know how to get
我已经写了这个,但我不知道如何获得
print(tip)
to be a percentage when someone types a number in.
当有人输入数字时为百分比。
回答by merlin2011
Based on your usage of input()
rather than raw_input()
, I assume you are using python3
.
根据您对input()
而不是的使用raw_input()
,我假设您正在使用python3
.
You just need to convert the user input into a floating point number, and divide by 100.
您只需要将用户输入转换为浮点数,然后除以 100。
print ("How much does your meal cost")
meal = 0
tip = 0
tax = 0.0675
action = input( "Type amount of meal ")
if action.isdigit():
meal = float(action)
tips = input(" type the perentage of tip you want to give ")
if tips.isdigit():
tip = float(tips) / 100 * meal
print(tip)
回答by Corrupted MyStack
It will be
这将是
print "Tip = %.2f%%" % (100*float(tip)/meal)
The end %%
prints the percent sign. The number (100*float(tip)/meal)
is what you are looking for.
最后%%
打印百分号。号码(100*float(tip)/meal)
就是你要找的。
回答by Phil Cote
We're assuming that it's a number the user is putting in. We want to make sure that the number is a valid percentage that the program can work with. I would recommend anticipating both expressions of a percentage from the user. So the user might type in .155
or 15.5
to represent 15.5%. A run-of-the-mill if statement is one way to see to that. (assuming you've already converted to float)
我们假设它是用户输入的数字。我们希望确保该数字是程序可以使用的有效百分比。我建议预测用户对百分比的两种表达方式。因此,用户可能会输入.155
或15.5
代表 15.5%。普通的 if 语句是实现这一目标的一种方式。(假设您已经转换为浮动)
if tip > 1:
tip = tip / 100
Alternatively, you could use what's called a ternary expression to handle this case. In your case, it would look something like this:
或者,您可以使用所谓的三元表达式来处理这种情况。在您的情况下,它看起来像这样:
tip = (tip / 100) if tip > 1 else tip
There's another question hereyou could check out to find out more about ternary syntax.
这里还有另一个问题,您可以查看以了解有关三元语法的更多信息。
回答by jfs
>>> "{:.1%}".format(0.88)
'88.0%'