Reputation: 25099
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)) + (classCCost * 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.
Upvotes: 1
Views: 994
Reputation: 82924
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)
Upvotes: 1
Reputation: 838076
Put your expression in parentheses:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)))
Upvotes: 4
Reputation: 10502
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)))
Upvotes: 4
Reputation: 28268
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.
Upvotes: 14