python中有大于但小于函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20308588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a greater than but less than function in python?
提问by Aiden
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:
I tried:
我想添加更多的代码,上面写着:如果 a 大于 10 但小于 20,请打印:
我试过:
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.
但所做的只是打印“A 大于 10,但小于 20”
基本上,python 中是否有“小于但大于”函数?顺便说一下,我正在运行版本 3。
采纳答案by user2357112 supports Monica
while 10 < a < 20:
whatever
This doesn't work in most languages, but Python supports it. Note that you should probably be using a forloop:
这在大多数语言中都不起作用,但 Python 支持它。请注意,您可能应该使用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, ais 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.
注意边界条件。当您的第一个循环结束时,a设置为10。(实际上,在打印最后一条“小于 10”消息时,它已经设置为 10。)如果您立即检查它是否大于 10,您会发现它不是。
回答by Mihai Maruseac
In Python you can even write
在 Python 中你甚至可以写
while 10 < a < 20:
do_smth()

