I have this code I'm just playing with, As I'm new to python, which is this:
a = 0
while a < 10:
a = a + 1
print("A is Less than 10")
I want to add some more code that says:
If a is more than 10 but less than 20, print this:
I tried:
a = 0
while a < 10:
a = a + 1
print("A is Less than 10")
while a < 20:
a = a + 1
print("A is More than 10, but less than 20.")
But all that does is print "A is more than 10, but less than 20"
Basically, is there a "Less than but greater than" function in python?
I'm running version 3 by the way.
The Python greater than or equal to >= operator can be used in an if statement as an expression to determine whether to execute the if branch or not. For example, the if condition x>=3 checks if the value of variable x is greater than or equal to 3, and if so, enters the if branch.
The Python less than ( left<right ) operator returns True when its left operand is smaller than its right operand. When the left operand is greater than or equal to the right operand, the < operator returns False . For example, 2<3.
Many programming beginners wonder how to write “greater than or equal to” in Python. Well, to write greater than or equal to in Python, you need to use the >= comparison operator. It will return a Boolean value – either True or False.
while 10 < a < 20:
whatever
This doesn't work in most languages, but Python supports it. Note that you should probably be using a for
loop:
for a in range(11, 20):
whatever
or if you just want to test a single number rather than looping, use an if
:
if 10 < a < 20:
whatever
Be careful with the boundary conditions. When your first loop ends, a
is set to 10
. (In fact, it's already set to 10 when you print the last "less than 10" message.) If you immediately check whether it's greater than 10, you'll find it's not.
In Python you can even write
while 10 < a < 20:
do_smth()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With