Why 5 is greater than 10 python?

三世轮回 提交于 2021-02-05 11:19:28

问题


while True:
    x = input().split()
    if len(x) != 2:
        continue
    a, b = x
    if a > b:
        print(a, 'is greater than', b)

Hi, why when i input: '5 10', output: '5 is greater than 10'?


回答1:


in python all that's returned from input are strings, and they are still strings even after you use split() on them. '5' (the string) is larger than '10' (the string) because string comparison works on the first letter first!

To do it properly, convert them both to int:

while True:
    x = input().split()
    if len(x) != 2:
        continue
    a, b = x
    if int(a) > int(b):
        print(a, 'is greater than', b)



回答2:


In string comparison, do this instead.

x = list(map(int, input().split()))


来源:https://stackoverflow.com/questions/58531100/why-5-is-greater-than-10-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!