Aiden
Aiden

Reputation: 375

Is there a greater than but less than function in python?

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.

Upvotes: 27

Views: 182651

Answers (2)

user2357112
user2357112

Reputation: 280335

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.

Upvotes: 68

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

In Python you can even write

while 10 < a < 20:
    do_smth()

Upvotes: 7

Related Questions