Andrew Harmsworth
Andrew Harmsworth

Reputation: 11

This is a simple Python question for list

Im trying to take in user input to get a list of numbers and then use a for loop to grab the largest value. For what I have now I can use 8237483294 but It will list each integer as its own independent value and will have its own place in the list so it would be [8,2,3,7,4,8,3,2,9,4] Which was an A+ for what I wanted. But now I want to take it to another place and take multi digit values such as [23,44332,32523,243,22,] my code is

users_number = input("list number")
numbers = users_number
max = numbers[0]
for number in numbers:
    if number > max:
        max = number
print(max)

Upvotes: 1

Views: 98

Answers (3)

funnydman
funnydman

Reputation: 11346

Simple and elegant one liner:

max(map(int, input("Enter a list: ").split()))

Upvotes: 0

blackbrandt
blackbrandt

Reputation: 2095

Use string.split().

#Get user input 
# (no need for the two variables you used in your example)
numbers = input("List numbers separated by spaces").split()
#Convert to list of ints
numbers = [int(num) for num in numbers]

#Solution 1: use max()
print("Max value:", max(numbers))

#Solution 2: Iterate through list
max_val = numbers[0]
for num in numbers:
    if num > max_val:
        max_val = num
print(max_val)

On an additional note, I presented 2 possible methods for finding the max value. max() is a built-in that finds the maximum value in the list. There is also the iterating method, which is what you do in your code.

Upvotes: 3

pakpe
pakpe

Reputation: 5479

Here is a more user-friendly approach that asks for the numbers one by one from the user. The advantage is that you don't have to rely on your users to enter the correct syntax for a list.

numbers = []
while True:
    number = input("Enter a number from your list. When finished with list, enter 'done': ")
    if number == "done":
        break
    else:
        numbers.append(int(number))
max_num = max(numbers)
print(max_num)

Upvotes: 0

Related Questions