0

How can I check if a variable is equal to something, and set to a new variable in the child scope?

For example:

bar = 'foobar'
my_slice = bar[:3]
if my_slice == 'foo':
   print(my_slice)

It seems like the new walrus operator here would be useful, but it's not immediately straightforward how you'd go about using it here

arshbot
  • 4,458
  • 4
  • 25
  • 47

1 Answers1

0

Walrus operators work here very well, we just need to understand exactly how they work.

if (my_slice := bar[3:]) == 'foo':
   print(my_slice)

Walrus operators set a variable to the output of some expression. It's almost identical to the equal sign in function except it can be used inline.

So this expression:

(my_slice := bar[3:]) == 'foo'

Can be boiled down to (variable = expression) == value

So because the output of my_slice := bar[:3] is equal to bar[:3], the above is equivalent to

bar[3:] == 'foo'

Note: The parenthesis here are required, or else variable is going to equal the output of the comparison operation, i.e. True or False

arshbot
  • 4,458
  • 4
  • 25
  • 47