How can I get rid of the excessive repetition in this code?
Code: http://pastebin.com/13e2nWM9
The program calculates equations of motion (SUVAT Equations) based on data provided by the user.
The section I refer to is:
while True:
a = raw_input("What is the value of a? Make sure it is in standard units, however, do not include the unit.")
try:
float(a)
print "a is " + str(a) + " ms^-2"
break
except:
print"You must enter a number. Don't include units!"
This is repeated many times, save for the variable 'a' and the unit which changes when the block is repeated.
Many thanks.
Here is one option, put the following function definition at the top of your module:
def get_float(name, units):
prompt = "What is the value of {0}? Make sure it is in standard units, however, do not include the unit.".format(name)
while True:
val = raw_input(prompt)
try:
val = float(val)
print '{0} is {1} {2}'.format(name, val, units)
return val
except Exception:
print "You must enter a number. Don't include units!"
Here is an example of how you could use it, the following code could replace everything from line 72 to 100:
name_units_pairs = [('v', 'ms^-1'), ('a', 'ms^-2'), ('t', 's'),]
vals = {}
for name, units in name_units_pairs:
vals[name] = get_float(name, units)
u = vals['v'] - vals['a'] * vals['t']
Do not use raw excepts, and encapsulate the tests, that is all. So instead of
while True:
a = raw_input("What is the value of a? Make sure it is in standard units, however, do not include the unit.")
try:
float(a)
print "a is " + str(a) + " ms^-2"
break
except:
print"You must enter a number. Don't include units!"
do
a = my_input(valuename='a', unit='m^-2', unitformat=float)
and do the tests (and prompts) in my_input.
my_input may look something like:
def my_input(valuename, unit, unitformat=float):
while True:
val = raw_input("What is the value of %s? Make sure it is in standard units"+
"(%s), however, do not include the unit." % (valuename, unit))
try:
unitformat(val)
except ValueError:
print"You must enter a number. Don't include units!"
else:
print "%s is %s %s" % (valuename, val, unit)
return val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With