compare items in list to x

M

Matt Herzog

I want a program that loops over a list of numbers (y) and tells me whether each number in the list is less than, greater than or equal to another number (x).

In the below code, I can't get python to see that 2 is equal to 2.

x = 2

def compare():

for y in ['12', '33', '2']:

if x < y:
print x, "is less than", y

elif x > y:
print x, "is greater than", y

else:
print x, "and", y, "are equal"


compare()
 
B

Bruno Desthuilliers

Matt Herzog a écrit :
I want a program that loops over a list of numbers (y) and tells me whether each number in the list is less than, greater than or equal to another number (x).

In the below code, I can't get python to see that 2 is equal to 2.

x = 2

def compare():

for y in ['12', '33', '2']:

if x < y:
print x, "is less than", y

elif x > y:
print x, "is greater than", y

else:
print x, "and", y, "are equal"


compare()

def compare(x, alist):
formats = {
-1 : "%d is less than %d",
0 : "%d and %d are equals",
1 : "%d is greater than %d"
}
print "\n".join(formats[cmp(x, y)] % (x, y) for y in map(int, alist))


compare(2, ['12', '1', '33', '2'])
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,816
Latest member
nipsseyhussle

Latest Threads

Top