Can anyone tell me why this program doesn't work? (it's an exercise in the assigned reading): print ('Give me two numbers.') print ("What's your first number?") no1 = raw_input() print ("What's your second number?") no2 = raw_input() if (no1 + no2 > 100): #if both are added and are greater than 100 print ("That's a big number, dude.") exit() if (no1 + no2 <= 100): exit() # nothing happens if the sum is less than 100
What's exactly wrong with the code? Does it fail to run when you Run Module (F5)? There's no need for another if statement after testing if the sum of no1 and no2 are greater than 100 (the code block won't run anyway if the number is equal to or smaller than 100). The code will work the same way if you delete the last if (no1 + no2 <= 100): exit() # nothing happens if the sum is less than 100 while moving the previous exit() statement 4 spaces back. Why use the exit function to exit the python interpreter?
The problem is that when you assign the raw-input to the variables, it is accepting those inputs as strings. You need to change the variables type when you add them together, from strings to integers so they can be added together. Otherwise you are concatenating two strings and trying to see if a bunch of characters is less than the integer 100. Understand? If you change one line of code, your program works. I tried it. Hope this helped. :) p.s. comment your code more when you ask for help so we don't have to try to guess what your intentions are :)
p.p.s are you using Python 3.x? Because your print statements look like the proper syntax for 3.0, but you will probably wanna use input() and not raw_input if you are using 3.0+. I use 3.2 and I've had to work through slight changes between the 2.x used in the lectures and what I'm using.
JustinNichol- thanks- totally makes sense! I'm using Python 2.7.2, so the raw_input statement is preferred I believe. That's exactly why I installed the 2. version- so I wouldn't have to work through differences in the lectures. And I thought I WAS commenting a lot. :D I will have to work harder at commenting more.
agdgdgdgwngo- I was using the exit so that when the program runs, you can actually see what it did before it shuts down. Without it, the program runs, prints out a result & the window closes all in the blink of an eye. I'll try the program without the last 2 lines- thanks.
Join our real-time social learning platform and learn together with your friends!