dezz
dezz

Reputation: 41

My First Ever Python Program

Hello friends of the internet,

I just began working in Python a few days ago and I am trying to create a starter program. All I am looking to do is create something that can take an input set of numbers (non-negative), from the user, and print the value of the highest number in the set.

I have read a few things about recursion functions that may be able to accomplish this task, but like I said, I'm a newby! If any of you professionals can show me something that can do just that I would be incredibly grateful.

def Max(list):
    if len(list) == 1:
        return list[0]
    else:
        m = Max(list[1:])
        return m if m > list[0] else list[0]

def main():
    list = eval(raw_input(" please enter a list of numbers: "))
    print("the largest number is: ", Max(list))

main()

Upvotes: 0

Views: 139

Answers (2)

Mohd
Mohd

Reputation: 5613

You have few issues in the code:

  • Don't use Python keywords like list as variable names
  • Don't use eval() when taking input from user
  • You can use built-in max() unless you want to create the function for educational purposes

So heres a better version of your code:

def main():

    my_list = raw_input(" please enter a list of numbers: ").split()
    my_list = map(int, my_list) # convert each item to int
    print("the largest number is: ", max(my_list))

main()

If you are using Python3 change raw_input() to input() and if you are using Python2 change print('item1', 'item2') to print 'item1', 'item2'

EDIT:

You can use a generator expression with max() to do that too as the following:

def main():

    my_list = raw_input(" please enter a list of numbers: ").split()
    max_num = max(int(x) for x in my_list)
    print("the largest number is: {}".format(max_num))

main()

Upvotes: 3

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

Single line answer:

print (max(list(map(int,input().split()))))

Explanation:

a=raw_input() #Take input in string.
b=a.split() #Split string by space.
c=map(int,b) # Convert each token into int.
d=max(c) #Evalute max element from list using max function.
print (d)

Edit:

print (max(map(int,input().split())))

Upvotes: 0

Related Questions