1

This code was written in VS Code, Python. I have a minimum variable in my code and another variable. Let's call them X and Xmin. I give Xmin and X numbers. Then when I compare them with < my code tells me that the smaller one is larger. Here is my code

Xmin = 100
print("X")
X = input()
if X < Xmin:
    print("X is too small.")

The problem is when I make X = 500, it will tell me that X is greater than Xmin, but when I give X something really big, like 1000000, it will tell me that X is too small.

Lazyboi
  • 13
  • 2
  • Something is fishy here. If this were Python 2, `input` would indeed return an `int` value if you entered `500` or `100000000`, and there shouldn't be a problem. If this is Python 3, you should be getting a `TypeError` when you try to compare a `str` like `"500"` to an `int`. – chepner May 24 '20 at 19:11
  • [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) might be useful – slesh May 24 '20 at 19:27

2 Answers2

3

If you are using python 3, you need to add an int() around the input statement in order for python to know the user input should be a number, not a string:

try:

    Xmin = 100
    print("X")
    X = int(input())
    if X < Xmin:
        print("X is too small.")

except:
    print('That is not an integer.')

If you are using python 2, watch out! input() in python 2 is the equivalent of eval(input()) in python 3, and we all know that 'eval is evil'.

Red
  • 26,798
  • 7
  • 36
  • 58
  • Can Python only print strings? Or can Python print both strings and integers? When I try to print another variable it gives me "TypeError: can only concatenate str (not "int") to str". – Lazyboi May 24 '20 at 19:35
  • Python can print both, but if you want to print them together, you need to convert each into the same type. So if you want, say: 'I will turn ' + 20, you need to convert 20 into a string, like so: str(20) – Red May 24 '20 at 19:36
  • This doesn't really work for me because I am trying to write something like print("Words here" + X*4 + "More words here. This just results in ypeError: can only concatenate str (not "int") to str. – Lazyboi May 24 '20 at 19:48
  • print("Words here" + str(X*4) + "More words here.") Or, print("Words here {} More words here.".format(X*4)) – Red May 24 '20 at 19:58
  • Ah okay thanks. That's all I need. Thank you for your time :) – Lazyboi May 24 '20 at 20:01
0
X = input() #takes input as string

Use below code instead of above:

X = int(input()) #takes input as integer
sigmapie8
  • 451
  • 3
  • 9