How do you take a negative value in python?
I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this. here is the prog I turned in:
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
asked Mar 16, 2010 at 2:37
3 Perhaps you would accomplish this with something to the effect of
or maybe
answered Mar 16, 2010 at 2:52
Mike GrahamMike Graham 70.9k14 gold badges97 silver badges129 bronze badges 1 Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if answered Mar 16, 2010 at 2:50
2 The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
answered Mar 16, 2010 at 3:03
slackerslacker 2,13211 silver badges10 bronze badges Try this on your TA:
output:
answered Mar 16, 2010 at 4:13
John MachinJohn Machin 79.4k11 gold badges138 silver badges183 bronze badges 3 How about something like that? (Uses no abs() nor mulitiplication)
answered Mar 16, 2010 at 3:13
mjvmjv 71.2k14 gold badges111 silver badges156 bronze badges 4 Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
Thanks for all the help everyone. answered Mar 16, 2010 at 23:42
dman762000dman762000 1711 gold badge1 silver badge6 bronze badges 5 Try doing this:
answered Dec 2, 2021 at 2:46
answered Nov 10, 2014 at 20:34
KitiyoKitiyo 11 gold badge1 silver badge3 bronze badges 1 |