简体   繁体   中英

is there a way to find the greatest number from random numbers?

i am writing a code to find the max and min number from a python list. if i provide numbers in list it is easy to get output, but i want to get output from random numbers, how to do it.

i have tried using max() but it does not work with random numbers

import random
list = []
print (len(list))
for i in range(1,10):
    print (random.randint(100,200))
for num in list:
     list = [random]
     print (list)

also i have tried using

index = list.index(max(list))
print ('index of max is ', index)

this works if i provide the numbers, but not with random.

the output of both max and min is same.

You are not filling your list with numbers, you are just printing them. Your list is actually empty.

Try this:

import random

list_ = [random.randint(100,200) for _ in range(10)]
print(list_)
print(max(list_))

PS Don't name variables equal to the keywords, like list , dict etc. It is very bad idea that can lead to various errors.

First you need to populate the list, and later find the minimum and maximum values:

import random

lst = []
for i in range(1, 10):
    lst.append(random.randint(100, 200))

print(max(lst))
print(min(lst))

Notice that it's more idiomatic to use a list comprehension, as shown in @vurmux's answer.

print (len(list)) //It will always print 0. Because list is empty at this time. You need to populate it with random numbers.

Also it is not a good practice to use Python Keywords as name of lists,sets,variables etc. It could raise errors. You have used list which a constructor for creating lists.

Here's what you need to do:-

import random
numlist = []

for i in range(1,10):
     numlist.append(random.randint(100,200))

print(max(numlist))
print(min(numlist))

Read about max here :- https://docs.python.org/3/library/functions.html#max

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM