Use of for loop to adapt one or more variables

I created a small example program, but I want to use an efficient loop, but I do not know HOW.

My simple program:
vrb001 = 123.456
if isinstance(vrb001, (float, int, str)):
__if not isinstance(vrb001, str):
____vrb001 = str(vrb001)
vrb002 = 789
if isinstance(vrb002, (float, int, str)):
__if not isinstance(vrb002, str):
____vrb002 = str(vrb002)
vrb003 = ‘xyz’
if isinstance(vrb003, (float, int, str)):
__if not isinstance(vrb003, str):
____vrb003 = str(vrb003)
print(vrb001 + ‘—’ + vrb002 + ‘—’ + vrb003)

My new loop program could be like:

def xxx(inp):
__if isinstance(inp, (float, int, str)):
____if not isinstance(inp, str):
______inp = str(inp)
__return inp

vrb001 - 123.456
vrb002 = 789
vrb003 = ‘xyz’
for wrk in (vrb001, vrb002, vrb003):
__wrk = xxx(wrk)
print(vrb001 + ‘—’ + vrb002 + ‘—’ + vrb003)


Well played on the underscores. Next time, please surround your code with ``` above and below to make it monospaced

You probably want to use a list instead of a number of variables:

vrb = [123.456, 689, 'xyz']
vrb_strings = []
for item in vrb:
    if isinstance(item, (float, int)):
        new_item = str(item)
        new_item = item


Your example is also a great opportunity to use a list comprehension.

vrb = [123.456, 689, 'xyz']
vrb_strings = [str(item) for item in vrb]


Unfortunately I did not want that solution, because I want to use the variable names instead of the variable values, so that they will automatically be corrected. Is it possible?

Maybe you explain what your program should accomplish?

1 Like