Reputation: 1075
I am trying to do a python script where I enter a argument into the command line. The program is temperature.py so if I enter:
./temperature.py 56
sys.argv[1] = 56
Now the program is as such:
import sys
temp=sys.argv[1]
print temp
if temp < 65:
print "Temperature is Cold"
else:
print "Temperature is warm"
based on the above logic I would expect that if I entered in the prompt
./temperature.py 56
temp would be 56 which is less than 65, so I could have a response:
"Temperature is Cold"
but I get the response:
"Temperature is Warm"
no matter what temperature I put in the argument. I still get the correct temp value that equals what the first argument is correct (56) so I am at a loss as to why the logic is malfunctioning in the if then statement. How do I get the logic to work so that when I enter a temperature less than 65 (i.e. ./temperature.py 56) I get the response "Temperature is Cold" and if I enter a temperature greater than 65 (i.e. ./temperature.py 75), I would get the response temperature is warm? Any ideas?
Upvotes: 0
Views: 1166
Reputation: 54163
Arguments are strings, not integers. You're comparing "56" < 65
which is False
. Instead try:
# temperature.py
import sys
try:
temperature = float(sys.argv[1])
except ValueError:
print("Argument must be a number")
sys.exit(1)
# kick out with an error code
if temp < 65:
# etc as you have it
Upvotes: 2