今天做练习遇到如下题目,只用if 对3个数排序,又把很久没用的排序给忘了,只记得sort了。用if写了下从大到小排列,自测没问题,int条件下。
This is an exercise in constructingif-statements. Using only simple variables and if statements, youshould be able to get this to work; a loop is not needed.
Given 3 numbers (X, Y,Z),assign variablesx,y,z so that andx , y,and z are fromX,Y, andZ. Use only a series of if-statements and assignment statements.
Hint. You must define the conditions under which you choose between x← X, x ← Y or x ←Z. You will do a similar analysis for assigningvalues toy andz. Note that your analysisfor settingy will depend on the value set forx;similarly, your analysis for settingz will depend onvalues set forx andy.
#!/usr/bin/python
# Filename: sort_three.py
a = input("a = ")
b = input("b = ")
c = input("c = ")
if a < b :
max = b
b = a
a = max
print a,b
if b < c :
max = c
c = b
b = max
print b,c
if a < b :
max = b
b = a
a = max
print a,b
print a,b,c
python 还有另一种交换数值的方法 a,b = b,a ,这样就不用再设置中间变量了,如下:
>>> a
6
>>> b
3
>>> a,b = b,a
>>> a
3
>>> b
6
>>>
上面的3行用一行就可以解决。
if 的格式书写如下:
if expression :
suite
或者:
if expression :
suite
elif expression :
suite
expression 可以是:
条件一 or 条件二:
条件一 and 条件二:
if expression :
suite
elif expression :
suite
else:
suite
if expression :
suite
else:
suite
以上if也可以缩减为一句话:suite 表达式1 or/and 表达式2 等
eg:
average = sum/count if count != 0 else None
average = count != 0 and float(sum)/count
本文来自博客园,作者:{Julius},转载请注明原文链接:https://www.cnblogs.com/bestechshare/p/16447797.html
可微信加我,了解更多,WeChat:{KingisOK}