Code style query: multiple assignments in if/elif tree

Chris Angelico rosuav at gmail.com
Mon Mar 31 10:33:09 EDT 2014


Call this a code review request, if you like. I'm wondering how you'd
go about coding something like this.

Imagine you're in a train, and the brakes don't apply instantly. The
definition, in the interests of passenger comfort, is that the first
second of brake application has an acceleration of 0.2 m/s/s, the next
second has 0.425 m/s/s, and thereafter full effect of 0.85 m/s/s. You
have a state variable that says whether the brakes have just been
applied, have already been applied for at least two seconds, or
haven't yet been applied at all. Problem: Work out how far you'll go
before the brakes reach full power, and how fast you'll be going at
that point.

Here's how I currently have the code. The variable names are a tad
long, as this was also part of me teaching my brother Python.

# Already got the brakes fully on
if mode=="Brake2": distance_to_full_braking_power, speed_full_brake =
0.0, curspeed
# The brakes went on one second ago, they're nearly full
elif mode=="Brake1": distance_to_full_braking_power, speed_full_brake
= curspeed - 0.2125, curspeed - 0.425
# Brakes aren't on.
else: distance_to_full_braking_power, speed_full_brake = (curspeed -
0.1) + (curspeed - 0.4125), curspeed - 0.625
# If we hit the brakes now (or already have hit them), we'll go
another d meters and be going at s m/s before reaching full braking
power.

But I don't like the layout. I could change it to a single assignment
with expression-if, but that feels awkward too. How would you lay this
out?

(Note that the "else" case could have any of several modes in it, so I
can't so easily use a dict.)

ChrisA



More information about the Python-list mailing list