+ 4
[SOLVED] help to find bug in nested if blocks
why my program is printing "pass" 4 times? why else block is not working when second "philip" comes in the for loop ? my code : https://code.sololearn.com/cIbW9BOa6nKi/?ref=app
26 Respostas
+ 7
Ratnapal Shende
Change the "if" with "elif" of if-statement where the "pass" is located.
Then add "twice_flag += 1" to the same if clause where the "pass" is located.
The reason "if" is not correct is because the code also has an "if" statement above it, hence it will print the "pass" twice each element or iteration.
And the reason why "twice_flag += 1" is needed is because when the if statement before it has been executed in case it is True (the if clause with "twice_flag -= 1") the value of twice_flag will become 0, therefore the iteration or loop for the next element will never meet the condition in the last "if" statement because it is 0 or False.
That is also the reason why the second element of the list or "Adarsh" did not print or did not met the final condition because the twice_flag is 0 or False.
https://code.sololearn.com/cExhFnuGzHIa/?ref=app
+ 4
Thank you so much ! 《 Nicko12 》
+ 1
Sergey don't spam if you are not able to help !!
+ 1
You read Patern State instead nested if or switch case
0
You must to write clear code!) You rewrite your code without nested if
0
your code is dirty!!!))
0
and you create short functions
0
and you create variable for undetstanding
0
and you create algoritms only in functions
0
and better use dictionary, than if -elif-else
0
dictionary as switch case
0
first you are learning to write clear code, you will have less bugs
- 1
x = int(input())
for case in switch(x):
if case(1): pass
if case(2): pass
if case(3):
print('Число от 1 до 3')
break
if case(4):
print('Число 4')
if case(): # default
print('Другое число')
- 2
or
- 2
if unit in unit_to_multiplier:
mult = unit_to_multiplier[unit]
else:
# обработка отсутствия значения в словаре
- 3
unit_to_multiplier = {
'mm': 10**-3,
'cm': 10**-2,
'dm': 10**-1,
'm': 1,
'km': 10**3
}
- 3
try:
mult = unit_to_multiplier['cm']
except KeyError as e:
# можно также присвоить значение по умолчанию вместо бросания исключения
raise ValueError('Undefined unit: {}'.format(e.args[0]))
- 3
mult = unit_to_multiplier.get('ultra-meter', 0)
- 3
unit_to_multiplier = {
'mm': 10**-3,
'cm': 10**-2,
'dm': 10**-1,
'm': 1,
'km': 10**3
}.get('km', 0)
- 3
or