Why Python allows comparison of a callable and a number?

  • Thread starter 一首诗
  • Start date
Ä

一首诗

I used python to write an assignment last week, here is a code snippet

#================================

def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t

#================================

Can you see the problem? I compare random.random with 0.8, which
should be random.random().

Of course this because of my careless, but I don't get it. In my
opinion, this kind of comparison should invoke a least a warning in
any programming language.

So why does python just ignore it?
 
C

Chris Rebert

I used python to write an assignment last week, here is a code snippet

#================================

def departTime():
   '''
   Calculate the time to depart a packet.
   '''
   if(random.random < 0.8):
       t = random.expovariate(1.0 / 2.5)
   else:
       t = random.expovariate(1.0 / 10.5)
   return t

#================================

Can you see the problem?  I compare random.random with 0.8,  which
should be random.random().

Of course this because of my careless, but I don't get it.  In my
opinion, this kind of comparison should invoke a least a warning in
any programming language.

So why does python just ignore it?

It's an historical anomaly that's been rectified in Python 3, where
such non-equality comparisons between unrelated types *do* now raise
an error.

Cheers,
Chris
 
M

MRAB

一首诗 said:
I used python to write an assignment last week, here is a code snippet

#================================

def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t

#================================

Can you see the problem? I compare random.random with 0.8, which
should be random.random().

Of course this because of my careless, but I don't get it. In my
opinion, this kind of comparison should invoke a least a warning in
any programming language.

So why does python just ignore it?

In Python 2 you can compare any 2 objects, for example an int with a
string. The result is arbitrary but consistent.

In Python 3 if the 2 objects aren't 'compatible' you'll get a TypeError
at runtime.

BTW, you don't need to put parentheses around the conditions in 'if' and
'while' statements. Python isn't C, etc. :)
 

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,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top