I'm trying to write a program in Python to tell me one thing if the inputed number is between 1 and 100. This is the code I have so far:
number = int (raw_input ("give me a number."))
if number < 100 and number > 1:
print ("Great! The number " + number + " is in fact between 1 and 100. I am happy " + number + " times")
if number < 1 or number < 100:
print ("Not so great! The number " + number + " is not between 1 and 100.")
I can run the first bit, but once I input a number that is between 1 and 100, I keep getting this error:
Traceback (most recent call last):
File "/Downloads/number (1).py", line 3, in <module>
print "Great! " + number + " is in fact between 1 and 100"
TypeError: cannot concatenate 'str' and 'int' objects
How can I fix this?
4 Answers 4
You can't combine int and str directly. Either convert to string or use string formatting:
Preferred:
print ("Not so great! The number {} is not between 1 and 100.".format(number))
At one point deprecated, now sticking around, but considered "old":
print ("Not so great! The number %i is not between 1 and 100." % number)
Most explicit, slowest, least preferred, and bad style (thanks @Stefano Sanfilippo!):
print ("Not so great! The number " + str(number) + " is not between 1 and 100.")
If you had "5" + 5, what would you want? Do you want 10, or do you want "55"? Because of the ambiguity, it's safer to raise an error and force you to be explicit with your intention
3 Comments
You need to convert 'number' into a string. You can do this by wrapping it up with the 'str' function.
Comments
This should work:
print ("Great! The number "+str(number)+" is in fact between 1 and 100. I am happy " +str(number)+" times")
Comments
You cannot add strings and integers together directly. Doing so will throw a TypeError:
>>> 'a' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>>
Instead, you can use str.format to insert the integers into the string:
print("Not so great! The number {0} is not between 1 and 100.".format(number))
Also, the logic of your comparisons is wrong. For example, the condition of this if-statement:
if number > 1 or number < 100:
will always evaluate to True because number will always be greater than 1 or less than 100.
With these problems addressed, your code should look like this:
number = int(raw_input("give me a number."))
# You can chain comparisons
if 1 < number < 100:
print("Great! The number {0} is in fact between 1 and 100. I am happy {0} times".format(number))
# You should use else here
else:
print("Not so great! The number {0} is not between 1 and 100.".format(number))
if 1 <= number <= 100:andelse:as it is right now thenumber100and1are not caughtnumber > 1 or number < 100always evaluate to True? Name a number that is both less than one and greater than a hundred ;-)NaN.