Home » Python » python – Unclear If statement functioning-Exceptionshub

python – Unclear If statement functioning-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Can you explain the reason for unclear if statement functioning of ordinary code below?

numbers = "677 2584 238 3126 1366 646 2560 2439 543 379 1048 2053 2518 1496 2537 1983 118 2105 1175 145 311 1881"
listed_numbers = numbers.split(" ")
max = listed_numbers[0]
min = listed_numbers[0]
for each in listed_numbers:
    if each >= max:
        max = each
    if each <= min:
        min = each

print(str(max) + " " + str(min))

Code link attached
https://repl.it/join/grsvacto-nihilisticrefor

PS if question seems to be unclear or inaccurate, please indicate the fragment that is perplexing, or edit my questions. This will help me to ask the question later.

How to&Answers:

When you use comparison operators (>, <, >=, <=) with strings, instead of numbers (int, float, etc), the two values are compared using alphabetical sorting to determine which one is greater – even if your string just contains numbers. Strings that start with a 1 will be sorted low, even if that string is 100; strings that start with a 9 will be sorted high, even if that string is 9.

For example, try this in your python REPL:

>>> 9 < 100
True
>>> "9" < "100"
False

As you can see, you’re doing string comparison instead of numerical comparison. You need to convert your values to ints first. Instead of:

listed_numbers = numbers.split(" ")

… which just creates a list of strings, try:

listed_numbers = [int(i) for i in numbers.split(" ")]

… which converts each value to an int and creates a list of those using list comprehension syntax.

Try your code with that one change and you’ll get the output 3126 118