johnny_adventureman
johnny_adventureman

Reputation: 3

how does randint() evaluate in an if, and else statement?

I just started teaching myself programming a few days ago and I had a simple question as to why the following code block works the way it does.

I searched for quite a bit of time here and on google, but have had issues finding a specific answer. So I thought i'd break the ice here at SO and ask real people who can understand my question.

    if randint(0,1):
        print ("Choice 1")
    else:
        if randint(0,1):
            print("Choice 2")

When I run this, it works as I need it to, but the question I have is, "Why does it work?"

So in my mind I see a random number (0 or 1) being generated. Since there's only two possible numbers, does it evaluate into a true/false statement? like 0 is true, and 1 is false? I'm not trying to use this for any program, it's just an example I made up to illustrate my question.

Thanks for reading, and I apologize if I posted here incorrectly. I plan on using this awesome site quite a bit and don't want to get started on the wrong foot.

edit: Thanks everyone for replying so quickly, I wish I could give the 'answer' to everyone that replied.

Upvotes: 0

Views: 203

Answers (4)

whereswalden
whereswalden

Reputation: 4959

This is an example of duck typing in Python. Each call to randint produces either 1 or 0, and 0's booleanness is False. Note that in your example, 25% of the time neither condition will be met. What you might be attempting to do is something like this:

num = randint(0,1)
if num: 
  do something
else:
  do something else

Duck typing can be used in lots of other situations too. For example, empty lists, dictionaries, and sets all evaluate to false, so instead of using while len(my_list)>0 you can just use while my_list. None also evaluates to False, so you can do things like if re.match(pattern, string) instead of if re.match(pattern, string) != None.

A good rule of thumb is just to assume that things will work the way you think they will. Python's duck typing is pretty robust.

Upvotes: 1

Chris Arena
Chris Arena

Reputation: 1630

0 evaluates to False, nonzero evaluates to True.

if 0:
    print 'a'
elif 1:
    print 'b'

# prints 'b'

Your code has a 50% chance of outputting Choice 1, a 25% chance of outputting Choice 2, and a 25% chance of outputting nothing.

Upvotes: 2

Chobeat
Chobeat

Reputation: 3535

Yeah, it automatically evaluate them as boolean. This is a common behaviour of many programming languages. Actually 0 evaluates to False and 1 evaluates to True.

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22395

if statements not only check types, but for truthy and falsy statements as well. 0 for example, is falsy. so if 0 would trigger the else statement.

So, your code says: if a random number is 1, print Choice 1. If a random number is 0, the else triggers and once again asks if a random number is 1 to print choice 2

Upvotes: 0

Related Questions