简体   繁体   中英

count method in 'if' doesn't work - python

I don't get it, I'm trying to count the 2 in this list and when it is like this:

hand=['D2', 'H5', 'S2', 'SK', 'CJ', 'H7', 'CQ', 'H9', 'D10', 'CK']
f=''.join(hand)
count2=f.count('2')
print count2

it works perfectly and it prints me 2 as the number of times the 2 is in the list. But when I'm putting it in an if it doesn't work:

def same_rank(hand, n):
    if hand.count('2')>n:
        print hand.count('2')
    else:
        print 'bite me'



hand=['D2', 'H5', 'S2', 'SK', 'CJ', 'H7', 'CQ', 'H9', 'D10', 'CK']
f=''.join(hand)
n=raw_input('Give n ')
print same_rank(hand,n)

If the user gives the n=1 then it is supposed to print 2 because the number 2 is twice in the list and I want it to be more than one that it is! So why it doesn't return that?

raw_input() returns a string; strings are always sorted after numbers, so 2 > '1' is always False:

>>> 2 > '1'
False

Convert your input to an integer first:

n = int(raw_input('Give n '))

Had you used Python 3, you'd have gotten an exception instead:

>>> 2 > '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() > str()

Because Python 3 has done away with giving arbitrary types a relative ordering.

Next, you don't pass in f , you are passing in hand , the list:

>>> hand.count('2')
0
>>> f
'D2H5S2SKCJH7CQH9D10CK'
>>> f.count('2')
2

You probably wanted to pass in the latter, your function doesn't work otherwise.

n is a string, not an integer, when you pass it to same_rank . Either use

n = int(raw_input('Give n '))

or convert n when passing the value:

print same_rank(hand, int(n))

or have same_rank handle the conversion:

def same_rank(hand, n):
    n = int(n)
    if hand.count('2')>n:
        print hand.count('2')
    else:
        print 'bite me'

n is string type please change into int Working Code:

def same_rank(hand, n):
    f=''.join(hand)
    if f.count('2')>int(n):
        print f.count('2')
    else:
        print 'bite me'



hand=['D2', 'H5', 'S2', 'SK', 'CJ', 'H7', 'CQ', 'H9', 'D10', 'CK']
f=''.join(hand)
n=raw_input('Give n ')
print same_rank(hand,n)

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