A continuación aparece una instantánea de la página web tal y como aparecía en 5/18/2024 (la última vez que nuestro rastreador la visitó). Esta es la versión de la página que se usó para la clasificación de los resultados de búsqueda. Puede que la página haya cambiado desde la última vez que la guardamos en caché. Para ver lo que puede haber cambiado (sin la información destacada), ve a la página actual.
Bing no se hace responsable del contenido de esta página.
When i run this exercise code, it always prints ‘code1’ regardless of the input
i = input('if exercise:\n')
if i == 'A' or 'B' or 'C':
print('code1')
elif i == 'D' or 'E' or 'F':
print('code2')
elif i == 'G' or 'H' or 'I':
print('code3')
else:
print('code4')
if exercise:
D
code1
The IDE doesn’t show any syntax error and the debugger doesn’t flare anything.
What did i do wrong?
In Python, each condition in an if statement should be explicitly compared with the variable i. In your code snippet the variable “i” is not compared explicitly to its value like so:
if i == ‘A’ or ‘B’ or ‘C’:
To fix this issue, we need to explicitly compare each condition to the variable i.
Here’s the corrected code snippet:
Python
if i == 'A' or i == 'B' or i == 'C':
Explanation:
In the corrected code snippet, each condition (i == 'A', i == 'B', i == 'C') is explicitly compared to the variable i. This modification ensures that the logic of the if statement correctly checks whether i is equal to ‘A’, ‘B’, or ‘C’.
Assuming that you’re using Python 3.10 or later, you can also use the new match statement, which lets you do pretty much what you tried, except that you must spell “or” as “|”:
i = input('match exercise:\n')
match i:
case 'A' | 'B' | 'C':
print('code1')
case 'D' | 'E' | 'F':
print('code2')
case 'G' | 'H' | 'I':
print('code3')
case _:
print('code4')