简体   繁体   English

python中有大于但不是函数吗?

[英]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: 我有这个代码,我只是在玩,因为我是python的新手,这是:

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: 我想添加更多代码,说:如果a大于10但小于20,请打印:
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" 但所有这一切都是打印“A超过10,但不到20”
Basically, is there a "Less than but greater than" function in python? 基本上,python中有“少于但大于”的功能吗? I'm running version 3 by the way. 顺便说一句,我正在运行第3版。

while 10 < a < 20:
    whatever

This doesn't work in most languages, but Python supports it. 这在大多数语言中都不起作用,但Python支持它。 Note that you should probably be using a for loop: 请注意,您可能应该使用for循环:

for a in range(11, 20):
    whatever

or if you just want to test a single number rather than looping, use an if : 或者如果您只想测试单个数字而不是循环,请使用if

if 10 < a < 20:
    whatever

Be careful with the boundary conditions. 小心边界条件。 When your first loop ends, a is set to 10 . 第一个循环结束时, a设置为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. (事实上​​,当你打印最后一个“少于10”的消息时,它已经被设置为10.)如果你立即检查它是否大于10,你会发现它不是。

In Python you can even write 在Python中你甚至可以写

while 10 < a < 20:
    do_smth()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM