Python:习题

import re
def is_zero(d):
    d = float(d)
    if d > 0:
        print 'positive'
    elif d < 0:
        print 'negative'
    else:
        print 'zero'
while True:
    x = raw_input("Enter a number:").strip()
    if x == "quit" or x == "q":
        break
    if len(x) and re.search(r"^(\-)?\d+(\.\d+)?$",x):
        is_zero(x)
        break
    else:
        print 'please enter a number'

 

判断输入字符与0的大小比较

在python2.7中,raw_input返回一个字符串对象

先通过正则表达式判断这个字符串是否是数字(正数,负数,还是小数),再将其与0比较

还有一种简便方法,但不建议使用:

判断数字后,直接正则表达式判断开头是否有“-”,判断正负数,在判断其中是否为“00.000”的格式(该方法是纯字符串匹配)

 

不使用列表和元组比较3个数的大小

def compareTraditional(a,b,c):  #The traditional method
    if a > b:
        if a > c:
            if b > c:
                return a,b,c
            else:
                return a,c,b
        elif a < c:
            return c,a,b
    elif a < b:
        if a > c:
            return b,a,c
        elif a < c:
            if b > c:
                return b,c,a
            else:
                return c,b,a
def compareInPython(a,b,c):     #The method in Py
    if a < b:
        a, b = b, a
    if a < c:
        a, c = c, a
    if b < c:
        b, c = c, b
    return a,b,c
    #reverse
    #return c,b,a
s = raw_input("please enter 3 numbers, separated by spaces:")
x,y,z = s.split(" ")
x = float(x)
y = float(y)
z = float(z)
print("compareTraditional: %.f %.f %.f" % compareTraditional(x, y, z))
print("compareInPython: %.f %.f %.f" % compareInPython(x, y, z))
python支持直接交换2个变量的值,如x,y = y,x
compareInPython方法较便捷,切很容易切换到逆序排列
posted @ 2015-07-04 16:26  guojian2080  阅读(295)  评论(0编辑  收藏  举报