0
点赞
收藏
分享

微信扫一扫

if --- Sort Three Numbers

cwq聖泉寒江2020 2022-09-19 阅读 148

今天做练习遇到如下题目,只用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






举报

相关推荐

0 条评论