Hello guys,
I’m trying the max function in Python 3.10 to select the highest value in a user-defined list but i’m getting the wrong result repetitively as follows:
Code:
numbers=input(“Enter 5 numbers separated by comma:”)
list=numbers.split(",")
print(“The list of user-input values is:”,list)
highest=max(list) #max is a builtin function
print(“The highest value in the list is:”,highest)
Hello, @PythonGuy.
“Input” returns a string, even you split it into ‘numbers’. And, because of that, max() function can’t do what it normally does -because it works with numeric values like integers-. To simply solve this problem, you can use a for loop, or a for-shorthand as below:
Thank you for posting your code as text. In future, you can format it as code using the </> button in the editor, or if posting from email, you can surround it using triple backticks:
```
code goes here
```
or just by indenting it.
Because you have posted the output as an image, I can’t see it, so I have to guess what the problem is.
You have a list of strings, not ints. Just because you tell the user to enter numbers, doesn’t mean that they do. And even if they type in digits, they are just strings of digits, not numbers.
Strings are compared in lexicographical order, not numeric order.
So "9" > "10000" (strings) even though 9 < 10000 (ints).
You need to convert the strings to ints. One way you can do that is with a list comprehension:
# Don't use the builtin name "list" as your own variable,
# it will cause trouble later on.
mylist = numbers.split(",")
mylist = [int(s) for s in mylist]
There is nothing wrong with using max() on a list of strings, so long as you understand that it returns the greatest string in lexicographical order, not numeric order.