0
Can We do a conditional block in Python using lists?
Like: if num in Colors[] Without to put a indexed number in him
6 Antworten
+ 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.')
+ 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 🤔
+ 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.
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.
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:
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.')