在python程序中需要了解print语句和float的用法以及format函数的用法是什么?

2024-04-25 12:00:15 发布

您现在位置:Python中文网/ 问答频道 /正文

num1=1.0

num2=5.0

sum=float (num1)+float (num2)

print ('The sum of {0} and {1} is {2}'.format (num1,num2,sum))

在这个节目里,你能解释一下打印报表吗?格式化函数有什么用?那是什么?你知道吗

Sum语句中,num1num2的值已经在float中了为什么我们必须再次使用类似float的float(num)?你知道吗


Tags: andofthe函数format报表is语句
1条回答
网友
1楼 · 发布于 2024-04-25 12:00:15

这个程序返回相同的结果

num1 = 1.
num2 = 5. 
sum = num1 + num2
print ('The sum of {0} and {1} is {2}'.format (num1, num2, sum))
>>> The sum of 1.0 and 5.0 is 6.0

所以,你不必做包裹num1,num2。因为(num1+num2)已经是浮动的,你知道的。你知道吗

{0}, {1}, {2}是格式的顺序,您可以跳过{}, {}, {}的顺序,在本例中,var replace continuously。(如{0}, {1}, {2}

您可以学习有关python格式的更多信息 在这个site


在Python3.6及更高版本中,您将很容易理解。你知道吗

它是f-string

print (f"The sum of {num1} and {num2} is {sum}")

.format作为替换。如下所示

print ('The sum of {0} and {1} is {2}'.format (num1,num2,sum))

>>> The sum of {value of num1} and {value of num2} is {value of sum}

012可以改变顺序

print ('The sum of {2} and {1} is {0}'.format (sum, num1, num2))

>>> The sum of {value of num2} and {value of num1} is {value of sum}

相关问题 更多 >

    热门问题