Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Aiden Avatar asked Dec 01 '13 04:12

Aiden


People also ask

How do you use greater than function in Python?

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.

How do you write less than a function in Python?

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.

How do you code more than in Python?

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.


2 Answers

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.

like image 94
user2357112 supports Monica Avatar answered Oct 12 '22 11:10

user2357112 supports Monica


In Python you can even write

while 10 < a < 20:
    do_smth()
like image 27
Mihai Maruseac Avatar answered Oct 12 '22 12:10

Mihai Maruseac