I am beginner in python and facing this problem. So how i can break the below expression in 2-3 lines
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (cla开发者_如何转开发ssCCost * float(classCSeatsSold))
Like this.
totalIncome = (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold))
Basic reason is i wanted to fit the line in 80 columns. And if i am not right about question Title please also suggest suitable title. Thanks in advance.
You always never have to use line continuation characters in python thanks to parentheses:
totalIncome = ( (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)) )
Which gives you the advantage of not having to remove the character in case you join the lines later. Same goes for strings:
longString = ( 'This is the one line '
'being continued here and '
'ending with a line break \n' )
You almost always can use parentheses instead of line continuation symbols and it just looks nicer.
Put your expression in parentheses:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)))
I despise breaking a line over into several lines using 'backslashes'. By wrapping the entire expression on the right hand side of the equals character, you can break the lines without worrying about ensuring there is trailing whitespace or not, such as:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost + float(classCSeatsSold)))
Just in case you revisit the scene:
You have excessive parentheses already. You also have unnecessary occurrences of float() ... if a cost is a float and a seatsSold is an int, then you don't need float() at all.
Instead of
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
you could have
totalIncome = classACost * classASeatsSold + classBCost * classBSeatsSold + classCCost * classCSeatsSold
which can be wrapped as
totalIncome = (
classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold
)
or
totalIncome = (classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold)
or whatever reasonable style takes your fancy. Splitting at some fixed limit is IMHO not reasonable:
totalIncome = (classACost * classASeatsSold + classBCost * classBSeatsSold +
classCCost * classCSeatsSold)
I prefer the first because it screams "Generalise me!" ...
total_income = sum(seat_price[c] * seats_sold[c] for c in class_codes)
精彩评论