Apples and Oranges

What does the following python code print out?

# python code start
fruit1 = "apples"
fruit2 = "oranges"
fruit3 = fruit2
fruit2 = fruit1

if (fruit3 == fruit2):
    print 34
elif (fruit2 == fruit1):
    print 72
elif (fruit3 == fruit1):
    print 9
else:
    print 119


The answer is 72.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

The answer is 72 .

By the time the first 4 assignment statements are done, fruit1 = "apples", fruit2 = "apples", and fruit3 = "oranges". Thus fruit2 equals fruit1, and the "print 72" statement gets executed.

# python code start
fruit1 = "apples"
fruit2 = "oranges"
fruit3 = fruit2   # fruit3 = "oranges"
fruit2 = fruit1   # fruit2 = "apples"

if (fruit3 == fruit2):     # False -> "oranges" != "apples"
    print 34
elif (fruit2 == fruit1):  # True -> "apples" == "apples"
    print 72                   #     so this gets executed
elif (fruit3 == fruit1):
    print 9
else:
    print 119

The problem is a bit skewed by the fact that we have 3 tries although there are clearly 4 possible answers.

Max Merco - 4 years, 7 months ago
Kristian Iroy
Nov 18, 2014

programming is a linear solution. If you'll declare one variable on one line and declare another variable on the latter line, the latest declaration will be the one that prevails. So in this case fruit2="oranges" only applies to line 3 until line 4. After fruit2=fruit1, the variable of fruit2 assumes that of fruit1.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...