
在Python中没有百分比运算符来计算百分比,但自己实现是不相关的。
Python 百分比
在Python中计算 百分比,使用除法运算符 **(/)得到两个数字的商,然后使用乘法运算符(*)**将这个商乘以100,得到百分比。这是一个简单的数学公式,可以得到百分比。
quotient = 3 / 5
percent = quotient * 100
print(percent)
输出
60.0
这意味着它是一个60%。
你可以在Python中创建一个自定义函数来计算百分比。
def percentage(part, whole):
percentage = 100 * float(part)/float(whole)
return str(percentage) + "%"
print(percentage(3, 5))
输出
60.0%
你可能想添加一个if语句,如果整数为0,则返回0,否则,这将抛出一个异常。
如果你想知道彼此之间的百分比,那么你需要使用下面的代码。
def percent(x, y):
if not x and not y:
print("x = 0%\ny = 0%")
elif x < 0 or y < 0:
print("The inputs can't be negative!")
else:
final = 100 / (x + y)
x *= final
y *= final
print('x = {}%\ny = {}%'.format(x, y))
percent(3, 6)
输出
x = 33.33333333333333%
y = 66.66666666666666%
Python % sign(Modulo Operator)
百分号在Python中被称为**模数运算符"%",**它返回左手操作数除以右手操作数后的剩余部分。
data = 3
info = 2
remainder = data % info
print(remainder)
输出结果
1
输出将显示为 "1"。这里,模运算符**"%"**返回两个数字相除后的余数。
%s运算符使你能够向Python字符串添加值。%s表示你要在字符串中添加字符串值;它也用于格式化字符串中的数字。
以上就是Python教程中查找百分比的内容。