Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Get 'i' variable assigned in if block

Hello I am trying to check some chars in a string. I found this code in the web. It works but I need to get i variable inside of the if block.

This is my code:

chars = set('qwertyuopasdfghjklizxcvbnm!"^+%&/()=?')

if any((i in chars) for i in myString):
   myIndex = myString.index(i)

But I’ve got this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

NameError: name 'i' is not defined

>Solution :

walrus operator to the rescue !

if any(((i := x) in chars) for x in myString):
   myIndex = myString.index(i)

this assigns x to i outside the comprehension so it’s visible inside the block.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading