0

Can We do a conditional block in Python using lists?

Like: if num in Colors[] Without to put a indexed number in him

20th Oct 2021, 3:53 PM
Katdotbrush
Katdotbrush - avatar
6 Respostas
+ 5
Yes, you can do it. Example is below: color = ['red', 'blue', 'green', 'pink'] num = 'red' if num in color: print('It is there.') else: print('Sorry, not there.')
20th Oct 2021, 4:09 PM
Omkar Kamat
Omkar Kamat - avatar
+ 1
Simon Sauter Like: variable = variable_n in color But I don't know if the variable will take variable_n, and not do a boolean value 🤔
20th Oct 2021, 8:51 PM
Katdotbrush
Katdotbrush - avatar
+ 1
cat do Chrome I tried what you said. variable = variable_n in color But it was not working and I don't why it is not working.
22nd Oct 2021, 5:45 AM
Omkar Kamat
Omkar Kamat - avatar
0
You can use any expression in an if (or elif) clause that evaluates to a boolean (True or False) or to something that Python can implicitly convert to a boolean.
20th Oct 2021, 6:46 PM
Simon Sauter
Simon Sauter - avatar
0
You can either use the expression directly in the if clause or you can assign it to a variable first and use the variable in the if clause. So if n in color: does the same as x = n in color if x:
20th Oct 2021, 8:57 PM
Simon Sauter
Simon Sauter - avatar
0
#You can do it like this: color = ['red', 'blue', 'green', 'pink'] num = 'red' boolean = num in color if boolean: print('It is there.') else: print('Sorry, not there.')
22nd Oct 2021, 6:25 AM
Simon Sauter
Simon Sauter - avatar