Conditional
comparison OPerator
| Python | Meaning |
|---|---|
| < | less than |
| < = | less than or equal to |
| == | equal to |
| > = | greater than or equal to |
| > | greater than |
| ! = | not eqaul |
Example 1
x = 5
print('Before 5')
if x == 5:
print ('is 5')
print ('is still 5')
print('Third 5')
print ('afterward 5')
print('before 6')
if x == 6:
print('is 6')
print('is still 6')
print('third 6')
print ('afterward 6')
if x = 5 it will print all the true conditional here is an Output
Before 5
is 5
is still 5
Third 5
afterward 5
before 6
afterward 6
it prints afterward 6 because that command is out of conditional that x = 6 so it printed out
Example 2
x = 5
if x > 2:
print ('Bigger than 2')
print('still Bigger')
print('Done with 2' )
for i in range(5):
print(i)
if i > 2:
print('Bigger than 2')
print('Done with i')
print ('all Done')
if x > 2 it will print out everything in the scope of that conditional if not it will not print but it will print the second conditional for i in range(5) that mean range from zero to five and see which one is greater than 2 if it found the value that greater than 2 it will print out Bigger than 2
here is an output
Bigger than 2
still Bigger
Done with 2
0
Done with i
1
Done with i
2
Done with i
3
Bigger than 2
Done with i
4
Bigger than 2
Done with i
all Done
Example 3
Nested Decision
x = 42
if x > 1:
print ('More than one')
if x < 100:
print('less than 100')
print('all done')
Output
More than one
less than 100
all done
Example 4
Two way Decision with else
x = 4
if x > 2:
print('Bigger')
else:
print('Smaller')
print('All Done!')
Output
Bigger
All Done!
Example5
Multi-way
https://replit.com/@pinkeo/py#main.py
Example 5
astr = 'hello bob'
try:
istr = int(astr)
except:
istr = -1
print('First',istr)
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print ('second',istr)
except will work if try past blow up or doesn’t work but if it does except will be ingore
https://replit.com/@pinkeo/py#o.py
astr = input('Enter a number:')
try:
istr = int(astr)
except:
istr = -1
if istr > 0:
print('Nice work')
else :
print('Not a number')
if input is not a number or equal -1 it will print Not a number but if input is greater than zero it will print Nice work