How does this code work?

I have this program that I wrote, but received some help shrinking from MNA4. I would like to know how the print statement in line 5 works. Now matter how hard I try, I can neither replicate it nor understand it, yet it works flawlessly in this program.

Repl link:

while 1:
  n,g,x=__import__('random').randint(i(I("Low num: ")),i(I("High num: "))),i,1
  while g!=n: g=i(I("Your guess: "));P([[f"You found it in {x} tries!","Lower!"][g>n],"Higher!"][g<n]);x+=1
  if I("Again? ").lower()in("n","no"):break

Oh gosh. Somebody is playing the minimum bytes game here :stuck_out_tongue:

Yes. But I can’t figure out how that print statement works. I can’t get anything similar to that to work.

This code works if you put in 17 but not if you put in 18 because it thinks it’s a list index.

print([["Adult"][(age := int(input("Enter your age\n")))>=18],"Minor"][age<18])

I don’t know what’s happening.

Is like:

age = int(input("Enter your age\n"))
if age >= 18:

Except that it crashes.

You missed a comma … and more actually

What comma? I have no idea what the syntax is for such wild print statements.

All he is doing is to create a list [[a,b],c] and use [condition] to select a or c, while b is used to execute a command. With a print in front.

Oh. I’m going to look into that.

Somebody seems to like messing code around … but this is slower than doing a normal if then else …

I’m not sure my mind can grasp this. I got something similar working. I think I’ll just do the easy way and put if statements inside the print statement because this is too hard.

1 Like

I can explain it better when I am back home burning’s you understand it. It is easy. Just useless …

So, take [[a,b][d],c][e].
Python first evaluate what is inside the innermost list [a,b].
a first and b, second. So if one of those is a command, it gets executed.
Then is looks at [d] because it is an index. d can be a command or even a condition (remember in python true is 1, false is 0] . Based on [d] it will take a or b.
Then, python look at the second innermost list […, c] and does the same.
And looks at [e] and does the same.

The trick here is that you need to first look at the innermost list with index, then the one containing that, etc etc

To be honest this is pretty useless and using if then else is better :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.