\(\renewcommand\AA{\unicode{x212B}}\)
if ... else
, for ...
, while
==
Tests for equality of two values, e.g. x == 2
!=
Tests for inequality of two values, e.g. x != 2
<
Tests if lhs is less than rhs, e.g. x < 2
>
Tests if lhs is greater than rhs, e.g. x > 2
<=
Tests if lhs is less than or equal to rhs, e.g. x <= 2
>=
Tests if lhs is greater than or equal rhs, e.g. x >= 2
x = 5
if x == 5:
print('x has the value 5')
else:
print('x does not equal 5')
x = 4
if x == 5:
print('x has the value 5')
else:
print('x does not equal 5')
Gives the output:
x has the value 5
x does not equal 5
and
keywordx = 2
if x > 0 and x < 5:
print('x is between 0 and 5 (not inclusive)')
else:
print('x is outside the range 0->5')
x = 7
if x > 0 and x < 5:
print('x is between 0 and 5 (not inclusive)')
else:
print('x is outside the range 0->5')
Gives the output:
x is between 0 and 5 (not inclusive)
x is outside the range 0->5
if x == 5:
print('In x = 5 routine')
print ('Doing correct thing') # Results in error "IndentationError:
# unindent does not match any outer
# indentation level"
else:
print('Everything else')
if ... else
using the keyword elif
to add
additional blocks, e.g.x = 3
if x == 1:
print('Running scenario 1')
elif x == 2:
print('Running scenario 2')
elif x == 3:
print('Running scenario 3')
else:
print('Unrecognized option')
Gives the output:
Running scenario 3
x = 2
if x == 1 or x == 2:
print('Running scenario first range')
Gives the output:
Running scenario first range