Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need Help.
#2
I have to say that I think this is a really dumb exercise, but that's not your fault.

Here's what I think he is getting at when he talks about using lists:

x = 5
print(['x is not five', 'x is five'][x == 5])
On the second line, x == 5 resolves to True. But that is in brackets, so Python sees that as the index of the previous list (['x is not five', 'x is five']). So Python tries to convert True to an integer. True actually is an integer, and it's value is 1. So the print statement is equivalent to print(['x is not five', 'x is five'][1]), which prints 'x is five'. That's how you convert a conditional into a list. The general form is that:

if condition:
    true_result
else:
    false_result
is equivalent to:

[false_result, true_result][condition]
This is generally considered a bad way to code the conditional. In fact, the ternary expression was added to Python specifically to avoid this sort of construction.

To expand on True/False as integers a bit, you can combine two conditions using math. 2 * condition1 + condition2 is equal to:
  • 0 if neither condition is true
  • 1 if condition1 is false and condition2 is true
  • 2 if condition1 is true and condition2 is false
  • 3 if both conditions are true

He also mentions while loops. I expect this is the sort of thing he is talking about:

powers = [1, 10, 100, 1000]
index = 0
while x < powers[index]:
    max_value = powers[index]
    index += 1
print('x is no more than', max_value)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Need Help. - by simapatel - Jan-02-2019, 06:26 AM
RE: Need Help. - by ichabod801 - Jan-02-2019, 03:43 PM
RE: Need Help. - by simapatel - Jan-03-2019, 05:49 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020