Please see the code below -
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
print "Let's do some math with just functions!"
age = add(float(raw_input("Add this:")), float(raw_input("To this:")))
Is there anyway, I can shorten the last line? Or, is there another way of getting user input?
Thanks
Applying "don't repeat yourself", we can take the repeated code and make a function out of it:
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
print "Let's do some math with just functions!"
def getf(prompt_mesg):
s = raw_input(prompt_mesg)
return float(s)
age = add(getf("Add this:"), getf("To this:"))
And then if you want you can make the input function handle errors better. Instead of raising an exception that takes down the whole program, you can handle errors gracefully:
def getf(prompt_mesg):
while True:
try:
s = raw_input(prompt_mesg)
return float(s)
except ValueError:
print("Could not convert that input. Please enter a number.")
This will loop forever until the user enters a valid input (or terminates the program).
I see you're using p2.x. First thing - I'd recommend switching to p3.x (it has many enhancements, but in this case you'll be happy to see that raw_input() became input() and input () with evaluation is gone).
Other way to shorten this stuff is using input() instead of raw_input(). If user gives you anything that is not a number, you'll get some sort of exception at addition, if he gives you a number (float, int, whatever) - your program will work.
==EDIT==
As glglgl pointed out - second part is dangerous and warning here is appriopriate. Using input() is basically the same as eval(raw_input()). Unfortunately, I forgot about the fact, that it doesnt take locals and globals parameters like eval - if it would, you could make it safe. For real-life applications it shouldnt be used, because some rogue user could evaluate anything he wants, causing program (or even computer) to crash. For simple apps like that, I stand my ground, and keep saying that it is useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.