if --- Sort Three Numbers

来源:互联网 发布:汪涵的胡子 知乎 编辑:程序博客网 时间:2024/06/07 01:14

今天做练习遇到如下题目,只用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 thatx \leq y \leq z 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 xX, xY or xZ. 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.pya = input("a = ")b = input("b = ")c = input("c = ")if a < b :    max = b    b = a    a = max    print a,bif b < c :    max = c    c = b    b = max    print b,cif a < b :    max = b    b = a    a = max    print a,bprint a,b,c

python 还有另一种交换数值的方法  a,b = b,a   ,这样就不用再设置中间变量了,如下:

>>> a6>>> b3>>> a,b = b,a>>> a3>>> b6>>> 

上面的3行用一行就可以解决。


if 的格式书写如下:

if expression :    suite

或者:if expression :    suiteelif expression :    suite


expression 可以是:条件一 or 条件二:条件一 and 条件二:

if expression :    suiteelif expression :    suiteelse:    suiteif expression :    suiteelse:    suite以上if也可以缩减为一句话:suite  表达式1 or/and 表达式2 等eg:average = sum/count if count != 0 else Noneaverage = count != 0 and float(sum)/count





原创粉丝点击