我是python的初学者并面临这个问题。那么我怎么能在2-3行打破下面的表达
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
喜欢这个。
totalIncome = (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold))
基本原因是我希望在80列中填充该行。如果我对问题标题不对,请同时提出合适的标题。提前致谢。
答案 0 :(得分:14)
由于括号,你总是不必在python中使用行继续符:
totalIncome = ( (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)) )
这使您可以在以后加入这些行时不必删除该字符。字符串也是如此:
longString = ( 'This is the one line '
'being continued here and '
'ending with a line break \n' )
你几乎总是可以使用括号而不是行连续符号,它看起来更好。
答案 1 :(得分:4)
将表达式括在括号中:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)))
答案 2 :(得分:4)
我鄙视使用'反斜杠'将一条线分成几行。通过将整个表达式包装在equals字符的右侧,您可以打破这些行而不必担心确保存在尾随空格,例如:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost + float(classCSeatsSold)))
答案 3 :(得分:1)
以防你再次访问该场景:
您已经有过多的括号。你也有不必要的float()...如果cost是float而seatSold是int,那么你根本就不需要float()。
而不是
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
你可以
totalIncome = classACost * classASeatsSold + classBCost * classBSeatsSold + classCCost * classCSeatsSold
可以包装为
totalIncome = (
classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold
)
或
totalIncome = (classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold)
或任何合理的风格都会让你感到高兴。在某个固定限制上分裂是恕我直言不合理:
totalIncome = (classACost * classASeatsSold + classBCost * classBSeatsSold +
classCCost * classCSeatsSold)
我更喜欢第一个因为它尖叫“概括我!” ...
total_income = sum(seat_price[c] * seats_sold[c] for c in class_codes)