Найти в Дзене
10 подписчиков

📑 Continue and Pass

📑 Task
1) Will the code print two identical lines?
2) How can you modify the code to avoid using external variables when
loading a string argument into the function exec()?

def command_string(command):
string = '''
for i in range(11):
x = i
if not i: ''' + command + '''
elif i % 3 == 0: x = 'x'
print(x, end=' ')
print()'''
return string
exec(command_string('continue'))
exec(command_string('pass'))

📑 Answer
1) The lines will be different:
- in the second case, the program will not perform any actions when i = 0,
- in the first case, it will skip this iteration
2)

def command_string_dict(command):
dict_ = {'continue': 'continue',
'pass': 'pass'}
string = f'''
for i in range(11):
x = i
if not i: {dict_[command]}
elif i % 3 == 0: x = 'x'
print(x, end=' ')
print()'''
return string
exec(command_string_dict('continue'))
exec(command_string_dict('pass'))
📑 Continue and Pass python-puzzles.blogspot.com/...tml 📑 Task 1) Will the code print two identical lines?
Около минуты